Ignore:
Timestamp:
Nov 24, 2016, 1:14:11 PM (9 years ago)
Author:
Silvan Scherrer
Message:

Samba Server: update vendor to version 4.4.3

Location:
vendor/current/source4/scripting
Files:
15 added
3 deleted
18 edited

Legend:

Unmodified
Added
Removed
  • vendor/current/source4/scripting/bin/enablerecyclebin

    r740 r988  
    33# enabled the Recycle Bin optional feature
    44#
    5 import base64
    65import optparse
    7 import os
    86import sys
    97
     
    1311import samba
    1412from samba import getopt as options, Ldb
    15 from ldb import SCOPE_SUBTREE, SCOPE_BASE, LdbError
     13from ldb import SCOPE_BASE
    1614import sys
    1715import ldb
     
    4947msg.dn = ldb.Dn(sam_ldb, "")
    5048msg["enableOptionalFeature"] = ldb.MessageElement(
    51                              "CN=Partitions," +  str(configbase) + ":766ddcd8-acd0-445e-f3b9-a7f9b6744f2a",
    52                              ldb.FLAG_MOD_ADD, "enableOptionalFeature")
     49     "CN=Partitions," +  str(configbase) + ":766ddcd8-acd0-445e-f3b9-a7f9b6744f2a",
     50     ldb.FLAG_MOD_ADD, "enableOptionalFeature")
    5351res = sam_ldb.modify(msg)
    5452
  • vendor/current/source4/scripting/bin/minschema

    r740 r988  
    66import base64
    77import optparse
    8 import os
    98import sys
    109
  • vendor/current/source4/scripting/bin/mymachinepw

    r414 r988  
    4343secrets = ldb.Ldb(path)
    4444
    45 search = "(&(objectclass=primaryDomain)(samaccountname=" + \
    46           netbios + "$))"
     45search = ("(&(objectclass=primaryDomain)(samaccountname=" +
     46      netbios + "$))")
    4747
    4848msg = secrets.search(expression=search, attrs=['secret'])
  • vendor/current/source4/scripting/bin/rebuildextendeddn

    r740 r988  
    99# Copyright (C) Andrew Bartlett <abartlet@samba.org> 2008
    1010#
    11 #   
    1211# This program is free software; you can redistribute it and/or modify
    1312# it under the terms of the GNU General Public License as published by
    1413# the Free Software Foundation; either version 3 of the License, or
    1514# (at your option) any later version.
    16 #   
     15#
    1716# This program is distributed in the hope that it will be useful,
    1817# but WITHOUT ANY WARRANTY; without even the implied warranty of
    1918# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    2019# GNU General Public License for more details.
    21 #   
     20#
    2221# You should have received a copy of the GNU General Public License
    2322# along with this program.  If not, see <http://www.gnu.org/licenses/>.
     
    4847parser.add_option_group(credopts)
    4948parser.add_option("--targetdir", type="string", metavar="DIR",
    50                           help="Set target directory")
     49                  help="Set target directory")
    5150
    5251opts = parser.parse_args()[0]
    5352
    5453def message(text):
    55         """print a message if quiet is not set."""
    56         if not opts.quiet:
    57                 print text
     54    """print a message if quiet is not set."""
     55    if not opts.quiet:
     56        print text
    5857
    5958if len(sys.argv) == 1:
    60         opts.interactive = True
     59    opts.interactive = True
    6160
    6261lp = sambaopts.get_loadparm()
     
    7170
    7271def get_paths(targetdir=None,smbconf=None):
    73         if targetdir is not None:
    74                 if (not os.path.exists(os.path.join(targetdir, "etc"))):
    75                         os.makedirs(os.path.join(targetdir, "etc"))
    76                 smbconf = os.path.join(targetdir, "etc", "smb.conf")
    77         if smbconf is None:
    78                         smbconf = param.default_path()
     72    if targetdir is not None:
     73        if (not os.path.exists(os.path.join(targetdir, "etc"))):
     74            os.makedirs(os.path.join(targetdir, "etc"))
     75        smbconf = os.path.join(targetdir, "etc", "smb.conf")
     76    if smbconf is None:
     77            smbconf = param.default_path()
    7978
    80         if not os.path.exists(smbconf):
    81                 print >>sys.stderr, "Unable to find smb.conf .. "+smbconf
    82                 parser.print_usage()
    83                 sys.exit(1)
     79    if not os.path.exists(smbconf):
     80        print >>sys.stderr, "Unable to find smb.conf .. "+smbconf
     81        parser.print_usage()
     82        sys.exit(1)
    8483
    85         lp = param.LoadParm()
    86         lp.load(smbconf)
    87         paths = provision_paths_from_lp(lp,"foo")
    88         return paths
     84    lp = param.LoadParm()
     85    lp.load(smbconf)
     86    paths = provision_paths_from_lp(lp,"foo")
     87    return paths
    8988
    9089
    9190
    9291def rebuild_en_dn(credentials,session_info,paths):
    93         lp = param.LoadParm()
    94         lp.load(paths.smbconf)
    95         names = ProvisionNames()
    96         names.domain = lp.get("workgroup")
    97         names.realm = lp.get("realm")
    98         names.rootdn = "DC=" + names.realm.replace(".",",DC=")
    99        
    100         attrs = ["dn" ]
    101         dn = ""
    102         sam_ldb = Ldb(paths.samdb, session_info=session_info, credentials=credentials,lp=lp)
    103         attrs2 = ["schemaNamingContext"]
    104         res2 = sam_ldb.search(expression="(objectClass=*)",base="", scope=SCOPE_BASE, attrs=attrs2)
    105         attrs.extend(get_linked_attributes(ldb.Dn(sam_ldb,str(res2[0]["schemaNamingContext"])),sam_ldb).keys())
    106         attrs.extend(get_dnsyntax_attributes(ldb.Dn(sam_ldb,str(res2[0]["schemaNamingContext"])),sam_ldb)),     
    107         sam_ldb.transaction_start()
    108         res = sam_ldb.search(expression="(cn=*)", scope=SCOPE_SUBTREE, attrs=attrs,controls=["search_options:1:2"]
    109 )
    110         mod = ""
    111         for i in range (0,len(res)):
    112                 #print >>sys.stderr,res[i].dn
    113                 dn = res[i].dn
    114                 for att in res[i]:
    115                         if ( (att != "dn" and att != "cn") and not (res[i][att] is None) ):
    116                                 m = ldb.Message()
    117                                 m.dn = ldb.Dn(sam_ldb, str(dn))
    118                                 saveatt = []
    119                                 for j in range (0,len( res[i][att])):
    120                                         mod = mod +att +": "+str(res[i][att][j])+"\n"
    121                                         saveatt.append(str(res[i][att][j]))
    122                                 m[att] = ldb.MessageElement(saveatt, ldb.FLAG_MOD_REPLACE, att)
    123                                 sam_ldb.modify(m)
    124                                 res3 = sam_ldb.search(expression="(&(dn=%s)(%s=*))"%(dn,att),scope=SCOPE_SUBTREE, attrs=[att],controls=["search_options:1:2"])
    125                                 if( len(res3) == 0  or (len(res3[0][att])!= len(saveatt))):
    126                                         print >>sys.stderr, str(dn) + " has no attr " +att+ " or a wrong value"
    127                                         for satt in saveatt:
    128                                                 print >>sys.stderr,str(att)+"   =       "+satt
    129                                         sam_ldb.transaction_cancel()
    130         sam_ldb.transaction_commit()
     92    lp = param.LoadParm()
     93    lp.load(paths.smbconf)
     94    names = ProvisionNames()
     95    names.domain = lp.get("workgroup")
     96    names.realm = lp.get("realm")
     97    names.rootdn = "DC=" + names.realm.replace(".",",DC=")
     98
     99    attrs = ["dn" ]
     100    dn = ""
     101    sam_ldb = Ldb(paths.samdb, session_info=session_info, credentials=credentials,lp=lp)
     102    attrs2 = ["schemaNamingContext"]
     103    res2 = sam_ldb.search(expression="(objectClass=*)",base="", scope=SCOPE_BASE, attrs=attrs2)
     104    attrs.extend(get_linked_attributes(ldb.Dn(sam_ldb,str(res2[0]["schemaNamingContext"])),sam_ldb).keys())
     105    attrs.extend(get_dnsyntax_attributes(ldb.Dn(sam_ldb,str(res2[0]["schemaNamingContext"])),sam_ldb))
     106    sam_ldb.transaction_start()
     107    res = sam_ldb.search(expression="(cn=*)", scope=SCOPE_SUBTREE, attrs=attrs,controls=["search_options:1:2"])
     108    mod = ""
     109    for i in range (0,len(res)):
     110        #print >>sys.stderr,res[i].dn
     111        dn = res[i].dn
     112        for att in res[i]:
     113            if ( (att != "dn" and att != "cn") and not (res[i][att] is None) ):
     114                m = ldb.Message()
     115                m.dn = ldb.Dn(sam_ldb, str(dn))
     116                saveatt = []
     117                for j in range (0,len( res[i][att])):
     118                    mod = mod +att +": "+str(res[i][att][j])+"\n"
     119                    saveatt.append(str(res[i][att][j]))
     120                m[att] = ldb.MessageElement(saveatt, ldb.FLAG_MOD_REPLACE, att)
     121                sam_ldb.modify(m)
     122                res3 = sam_ldb.search(expression="(&(distinguishedName=%s)(%s=*))"%(dn,att),scope=SCOPE_SUBTREE, attrs=[att],controls=["search_options:1:2"])
     123                if( len(res3) == 0  or (len(res3[0][att])!= len(saveatt))):
     124                    print >>sys.stderr, str(dn) + " has no attr " +att+ " or a wrong value"
     125                    for satt in saveatt:
     126                        print >>sys.stderr,str(att)+"    =    "+satt
     127                    sam_ldb.transaction_cancel()
     128    sam_ldb.transaction_commit()
    131129
    132130
    133 
    134                
    135 paths = get_paths(targetdir=opts.targetdir,smbconf=smbconf)
    136 
     131paths = get_paths(targetdir=opts.targetdir, smbconf=smbconf)
    137132
    138133rebuild_en_dn(creds,session,paths)
  • vendor/current/source4/scripting/bin/rpcclient

    r740 r988  
    2424        if attr == 'this' or attr == 'thisown':
    2525            continue
    26        
     26
    2727        result[attr] = getattr(obj, attr)
    2828
     
    5252        except dcerpc.NTSTATUS, arg:
    5353            print 'The command returned an error: %s' % arg[1]
    54            
     54
    5555    # Command handlers
    5656
     
    6868        else:
    6969            print 'Command exited with signal %d' % os.WTERMSIG(status)
    70            
     70
    7171    def do_EOF(self, line):
    7272        """Exits rpcclient."""
     
    7878    def do_SamrEnumDomains(self, line):
    7979        """Enumerate domain names."""
    80        
     80
    8181        usage = 'usage: SamrEnumDomains'
    8282
     
    117117
    118118    def do_SamrQueryDomInfo(self, line):
    119         """Return information about a domain designated by its SID."""
    120 
    121         usage = 'SamrQueryDomInfo DOMAIN_SID [info_level]'
    122 
    123         parser = OptionParser(usage)
    124         options, args = parser.parse_args(string.split(line))
    125 
    126         if (len(args) == 0) or (len(args) > 2):
    127             print 'usage:', usage
    128             return
    129 
    130         pipe = dcerpc.pipe_connect(
    131             'ncacn_np:%s' % self.server,
    132             dcerpc.DCERPC_SAMR_UUID, int(dcerpc.DCERPC_SAMR_VERSION),
    133             self.cred)
    134 
    135         connect_handle = samr.Connect(pipe)
    136         domain_handle = connect_handle.OpenDomain(args[0])
    137 
    138         if (len(args) == 2):
    139             result = domain_handle.QueryDomainInfo(int(args[1]))
    140         else:
    141             result = domain_handle.QueryDomainInfo()
     119        """Return information about a domain designated by its SID."""
     120
     121        usage = 'SamrQueryDomInfo DOMAIN_SID [info_level]'
     122
     123        parser = OptionParser(usage)
     124        options, args = parser.parse_args(string.split(line))
     125
     126        if (len(args) == 0) or (len(args) > 2):
     127            print 'usage:', usage
     128            return
     129
     130        pipe = dcerpc.pipe_connect(
     131            'ncacn_np:%s' % self.server,
     132            dcerpc.DCERPC_SAMR_UUID, int(dcerpc.DCERPC_SAMR_VERSION),
     133            self.cred)
     134
     135        connect_handle = samr.Connect(pipe)
     136        domain_handle = connect_handle.OpenDomain(args[0])
     137
     138        if (len(args) == 2):
     139            result = domain_handle.QueryDomainInfo(int(args[1]))
     140        else:
     141            result = domain_handle.QueryDomainInfo()
    142142
    143143        pprint(swig2dict(result))
    144144
    145145    def do_SamrQueryDomInfo2(self, line):
    146         """Return information about a domain designated by its SID.
     146        """Return information about a domain designated by its SID.
    147147        (Windows 2000 and >)"""
    148148
    149         usage = 'SamrQueryDomInfo2 DOMAIN_SID [info_level] (Windows 2000 and >)'
    150         parser = OptionParser(usage)
    151         options, args = parser.parse_args(string.split(line))
    152 
    153         if len(args) == 0 or len(args) > 2:
    154             print 'usage:', usage
    155             return
    156 
    157         pipe = dcerpc.pipe_connect(
    158             'ncacn_np:%s' % self.server,
    159             dcerpc.DCERPC_SAMR_UUID, int(dcerpc.DCERPC_SAMR_VERSION),
    160             self.cred)
    161 
    162         connect_handle = samr.Connect(pipe)
    163         domain_handle = connect_handle.OpenDomain(args[0])
    164 
    165         if (len(args) == 2):
    166             result = domain_handle.QueryDomainInfo2(int(args[1]))
    167         else:
    168             result = domain_handle.QueryDomainInfo2()
     149        usage = 'SamrQueryDomInfo2 DOMAIN_SID [info_level] (Windows 2000 and >)'
     150        parser = OptionParser(usage)
     151        options, args = parser.parse_args(string.split(line))
     152
     153        if len(args) == 0 or len(args) > 2:
     154            print 'usage:', usage
     155            return
     156
     157        pipe = dcerpc.pipe_connect(
     158            'ncacn_np:%s' % self.server,
     159            dcerpc.DCERPC_SAMR_UUID, int(dcerpc.DCERPC_SAMR_VERSION),
     160            self.cred)
     161
     162        connect_handle = samr.Connect(pipe)
     163        domain_handle = connect_handle.OpenDomain(args[0])
     164
     165        if (len(args) == 2):
     166            result = domain_handle.QueryDomainInfo2(int(args[1]))
     167        else:
     168            result = domain_handle.QueryDomainInfo2()
    169169
    170170        pprint(swig2dict(result))
    171171
    172172    def do_SamrEnumDomainGroups(self, line):
    173         """Return the list of groups of a domain designated by its SID."""
    174 
    175         usage = 'SamrEnumDomainGroups DOMAIN_SID'
     173        """Return the list of groups of a domain designated by its SID."""
     174
     175        usage = 'SamrEnumDomainGroups DOMAIN_SID'
    176176
    177177        parser = OptionParser(usage)
     
    187187            self.cred)
    188188
    189         connect_handle = samr.Connect(pipe)     
    190         domain_handle = connect_handle.OpenDomain(args[0])
    191 
    192         result = domain_handle.EnumDomainGroups()
     189        connect_handle = samr.Connect(pipe)
     190        domain_handle = connect_handle.OpenDomain(args[0])
     191
     192        result = domain_handle.EnumDomainGroups()
    193193
    194194        pprint(result)
     
    198198        by its SID."""
    199199
    200         usage = 'SamrEnumDomainAliases DOMAIN_SID'
     200        usage = 'SamrEnumDomainAliases DOMAIN_SID'
    201201
    202202        parser = OptionParser(usage)
     
    215215        domain_handle = connect_handle.OpenDomain(args[0])
    216216
    217         result = domain_handle.EnumDomainAliases()
     217        result = domain_handle.EnumDomainAliases()
    218218
    219219        pprint(result)
    220220
    221221    def do_SamrEnumDomainUsers(self, line):
    222         """Return the list of users of a domain designated by its SID."""
    223 
    224         usage = 'SamrEnumDomainUsers DOMAIN_SID [user_account_flags]'
    225 
    226         parser = OptionParser(usage)
    227         options, args = parser.parse_args(string.split(line))
    228 
    229         if (len(args) == 0) or (len(args) > 2):
    230             print 'usage:', usage
    231             return
    232 
    233         pipe = dcerpc.pipe_connect(
    234             'ncacn_np:%s' % self.server,
    235             dcerpc.DCERPC_SAMR_UUID, int(dcerpc.DCERPC_SAMR_VERSION),
    236             self.cred)
    237 
    238         connect_handle = samr.Connect(pipe)
    239         domain_handle = connect_handle.OpenDomain(args[0])
    240 
    241         if (len(args) == 2):
    242             result = domain_handle.EnumDomainUsers(int(args[1]))
    243         else:
    244             result = domain_handle.EnumDomainUsers()
     222        """Return the list of users of a domain designated by its SID."""
     223
     224        usage = 'SamrEnumDomainUsers DOMAIN_SID [user_account_flags]'
     225
     226        parser = OptionParser(usage)
     227        options, args = parser.parse_args(string.split(line))
     228
     229        if (len(args) == 0) or (len(args) > 2):
     230            print 'usage:', usage
     231            return
     232
     233        pipe = dcerpc.pipe_connect(
     234            'ncacn_np:%s' % self.server,
     235            dcerpc.DCERPC_SAMR_UUID, int(dcerpc.DCERPC_SAMR_VERSION),
     236            self.cred)
     237
     238        connect_handle = samr.Connect(pipe)
     239        domain_handle = connect_handle.OpenDomain(args[0])
     240
     241        if (len(args) == 2):
     242            result = domain_handle.EnumDomainUsers(int(args[1]))
     243        else:
     244            result = domain_handle.EnumDomainUsers()
    245245
    246246        pprint(result)
     
    289289
    290290    if username != '':
    291         cred = (domain, username, password)
     291        cred = (domain, username, password)
    292292
    293293    # Run command loop
  • vendor/current/source4/scripting/bin/samba3dump

    r740 r988  
    1414import samba
    1515import samba.samba3
     16from samba.samba3 import param as s3param
     17from samba.dcerpc import lsa
    1618
    1719parser = optparse.OptionParser("samba3dump <libdir> [<smb.conf>]")
     
    3032def print_samba3_policy(pol):
    3133    print_header("Account Policies")
    32     print "Min password length: %d" % pol.min_password_length
    33     print "Password history length: %d" % pol.password_history
    34     if pol.user_must_logon_to_change_password:
    35         print "User must logon to change password: %d" % pol.user_must_logon_to_change_password
    36     if pol.maximum_password_age:
    37         print "Maximum password age: %d" % pol.maximum_password_age
    38     if pol.minimum_password_age:
    39         print "Minimum password age: %d" % pol.minimum_password_age
    40     if pol.lockout_duration:
    41         print "Lockout duration: %d" % pol.lockout_duration
    42     if pol.reset_count_minutes:
    43         print "Reset Count Minutes: %d" % pol.reset_count_minutes
    44     if pol.bad_lockout_minutes:
    45         print "Bad Lockout Minutes: %d" % pol.bad_lockout_minutes
    46     if pol.disconnect_time:
    47         print "Disconnect Time: %d" % pol.disconnect_time
    48     if pol.refuse_machine_password_change:
    49         print "Refuse Machine Password Change: %d" % pol.refuse_machine_password_change
     34    print "Min password length: %d" % pol['min password length']
     35    print "Password history length: %d" % pol['password history']
     36    if pol['user must logon to change password']:
     37        print "User must logon to change password: %d" % pol['user must logon to change password']
     38    if pol['maximum password age']:
     39        print "Maximum password age: %d" % pol['maximum password age']
     40    if pol['minimum password age']:
     41        print "Minimum password age: %d" % pol['minimum password age']
     42    if pol['lockout duration']:
     43        print "Lockout duration: %d" % pol['lockout duration']
     44    if pol['reset count minutes']:
     45        print "Reset Count Minutes: %d" % pol['reset count minutes']
     46    if pol['bad lockout attempt']:
     47        print "Bad Lockout Minutes: %d" % pol['bad lockout attempt']
     48    if pol['disconnect time']:
     49        print "Disconnect Time: %d" % pol['disconnect time']
     50    if pol['refuse machine password change']:
     51        print "Refuse Machine Password Change: %d" % pol['refuse machine password change']
    5052
    5153def print_samba3_sam(samdb):
    5254    print_header("SAM Database")
    53     for user in samdb:
    54         print "%s" % user
     55    for user in samdb.search_users(0):
     56        print "%s (%d): %s" % (user['account_name'], user['rid'], user['fullname'])
    5557
    56 def print_samba3_shares(shares):
     58def print_samba3_shares(lp):
    5759    print_header("Configured shares")
    58     for s in shares:
    59         print "--- %s ---" % s.name
    60         for p in s:
    61             print "\t%s = %s" % (p.key, p.value)
     60    for s in lp.services():
     61        print "--- %s ---" % s
     62        for p in ['path']:
     63            print "\t%s = %s" % (p, lp.get(p, s))
    6264        print ""
    6365
     
    114116    print_header("Group Mappings")
    115117   
    116     for sid in groupdb.groupsids():
    117         print "\t--- Group: %s ---" % sid
     118    for g in groupdb.enum_group_mapping(samba.samba3.passdb.get_global_sam_sid(),
     119                                        lsa.SID_NAME_DOM_GRP):
     120        print "\t--- Group: %s ---" % g.sid
    118121
    119122def print_samba3_aliases(groupdb):
    120     for sid in groupdb.aliases():
    121         print "\t--- Alias: %s ---" % sid
     123    for g in groupdb.enum_group_mapping(samba.samba3.passdb.get_global_sam_sid(),
     124                                        lsa.SID_NAME_ALIAS):
     125        print "\t--- Alias: %s ---" % g.sid
    122126
    123127def print_samba3_idmapdb(idmapdb):
     
    134138
    135139def print_samba3(samba3):
    136     print_samba3_policy(samba3.get_policy_db())
     140    passdb = samba3.get_sam_db()
     141    print_samba3_policy(passdb.get_account_policy())
    137142    print_samba3_winsdb(samba3.get_wins_db())
    138143    print_samba3_regdb(samba3.get_registry())
    139144    print_samba3_secrets(samba3.get_secrets_db())
    140145    print_samba3_idmapdb(samba3.get_idmap_db())
    141     print_samba3_sam(samba3.get_sam_db())
    142     groupdb = samba3.get_groupmapping_db()
    143     print_samba3_groupmappings(groupdb)
    144     print_samba3_aliases(groupdb)
    145     print_samba3_shares(samba3.get_shares())
     146    print_samba3_sam(passdb)
     147    print_samba3_groupmappings(passdb)
     148    print_samba3_aliases(passdb)
     149    print_samba3_shares(samba3.lp)
    146150
    147151def print_samba3_summary(samba3):
    148152    print "WINS db entries: %d" % len(samba3.get_wins_db())
    149153    print "Registry key count: %d" % len(samba3.get_registry())
    150     groupdb = samba3.get_groupmapping_db()
    151     print "Groupmap count: %d" % len(list(groupdb.groupsids()))
    152     print "Alias count: %d" % len(list(groupdb.aliases()))
     154    passdb = samba3.get_sam_db()
     155    print "Groupmap count: %d" % len(passdb.enum_group_mapping())
     156    print "Alias count: %d" % len(passdb.search_aliases())
    153157    idmapdb = samba3.get_idmap_db()
    154158    print "Idmap count: %d" % (len(list(idmapdb.uids())) + len(list(idmapdb.gids())))
    155159
     160if len(args) < 1:
     161    parser.print_help()
     162    sys.exit(1)
     163
    156164libdir = args[0]
    157 if len(args) > 1:
     165if len(args) < 1:
    158166    smbconf = args[1]
    159167else:
    160168    smbconf = os.path.join(libdir, "smb.conf")
    161169
    162 samba3 = samba.samba3.Samba3(libdir, smbconf)
     170s3_lp = s3param.get_context()
     171s3_lp.set("private dir", libdir)
     172s3_lp.set("state directory", libdir)
     173s3_lp.set("lock directory", libdir)
     174s3_lp.load(smbconf)
     175samba3 = samba.samba3.Samba3(smbconf, s3_lp)
    163176
    164177if opts.format == "summary":
  • vendor/current/source4/scripting/bin/samba_backup

    r740 r988  
    11#!/bin/sh
    22#
    3 # Copyright (C) Matthieu Patou <mat@matws.net> 2010
     3# Copyright (C) Matthieu Patou <mat@matws.net> 2010-2011
    44#
    55# This program is free software; you can redistribute it and/or modify
     
    1616# along with this program.  If not, see <http://www.gnu.org/licenses/>.
    1717#
     18# Revised 2013-09-25, Brian Martin, as follows:
     19#    - Allow retention period ("DAYS") to be specified as a parameter.
     20#    - Allow individual positional parameters to be left at the default
     21#      by specifying "-"
     22#    - Use IS0 8601 standard dates (yyyy-mm-dd instead of mmddyyyy).
     23#    - Display tar exit codes when reporting errors.
     24#    - Don't send error messages to /dev/null, so we know what failed.
     25#    - Suppress useless tar "socket ignored" message.
     26#    - Fix retention period bug when deleting old backups ($DAYS variable
     27#      could be set, but was ignored).
     28
     29
    1830
    1931FROMWHERE=/usr/local/samba
    2032WHERE=/usr/local/backups
     33DAYS=90                         # Set default retention period.
    2134if [ -n "$1" ] && [ "$1" = "-h" -o "$1" = "--usage" ]; then
    22         echo "samba_backup [provisiondir] [destinationdir]"
    23         echo "Will backup your provision located in provisiondir to archive stored in destinationdir"
     35        echo "samba_backup [provisiondir] [destinationdir] [retpd]"
     36        echo "Will backup your provision located in provisiondir to archive stored"
     37        echo "in destinationdir for retpd days. Use - to leave an option unchanged."
    2438        echo "Default provisiondir: $FROMWHERE"
    2539        echo "Default destinationdir: $WHERE"
     40        echo "Default destinationdir: $DAYS"
    2641        exit 0
    2742fi
    2843
    29 [ -n "$1" -a -d "$1" ]&&FROMWHERE=$1
    30 [ -n "$2" -a -d "$2" ]&&WHERE=$2
     44[ -n "$1" -a "$1" != "-" ]&&FROMWHERE=$1        # Use parm or default if "-".  Validate later.
     45[ -n "$2" -a "$2" != "-" ]&&WHERE=$2            # Use parm or default if "-".  Validate later.
     46[ -n "$3" -a "$3" -eq "$3" 2> /dev/null ]&&DAYS=$3      # Use parm or default if non-numeric (incl "-").
    3147
    3248DIRS="private etc sysvol"
    3349#Number of days to keep the backup
    34 DAYS=90
    35 WHEN=`date +%d%m%y`
     50WHEN=`date +%Y-%m-%d`   # ISO 8601 standard date.
     51
     52if [ ! -d $WHERE ]; then
     53        echo "Missing backup directory $WHERE"
     54        exit 1
     55fi
     56
     57if [ ! -d $FROMWHERE ]; then
     58        echo "Missing or wrong provision directory $FROMWHERE"
     59        exit 1
     60fi
    3661
    3762cd $FROMWHERE
     
    4368                for ldb in `find $relativedirname -name "*.ldb"`; do
    4469                        tdbbackup $ldb
    45                         if [ $? -ne 0 ]; then
    46                                 echo "Error while backuping $ldb"
     70                        Status=$?       # Preserve $? for message, since [ alters it.
     71                        if [ $Status -ne 0 ]; then
     72                                echo "Error while backing up $ldb - status $Status"
    4773                                exit 1
    4874                        fi
    4975                done
    50                 tar cjf ${WHERE}/samba4_${n}.${WHEN}.tar.bz2  $relativedirname --exclude=*.ldb >/dev/null 2>&1
    51                 if [ $? -ne 0 ]; then
    52                         echo "Error while archiving ${WHERE}/samba4_${n}.${WHEN}.tar.bz2"
     76                # Run the backup.
     77                #    --warning=no-file-ignored set to suppress "socket ignored" messages.
     78                tar cjf ${WHERE}/samba4_${n}.${WHEN}.tar.bz2  $relativedirname --exclude=\*.ldb --warning=no-file-ignored --transform 's/.ldb.bak$/.ldb/'
     79                Status=$?       # Preserve $? for message, since [ alters it.
     80                if [ $Status -ne 0 -a $Status -ne 1 ]; then     # Ignore 1 - private dir is always changing.
     81                        echo "Error while archiving ${WHERE}/samba4_${n}.${WHEN}.tar.bz2 - status = $Status"
    5382                        exit 1
    5483                fi
    5584                find $relativedirname -name "*.ldb.bak" -exec rm {} \;
    5685        else
    57                 tar cjf ${WHERE}/${n}.${WHEN}.tar.bz2  $relativedirname >/dev/null 2>&1
    58                 if [ $? -ne 0 ]; then
    59                         echo "Error while archiving ${WHERE}/${n}.${WHEN}.tar.bz2"
     86                # Run the backup.
     87                #    --warning=no-file-ignored set to suppress "socket ignored" messages.
     88                tar cjf ${WHERE}/${n}.${WHEN}.tar.bz2  $relativedirname --warning=no-file-ignored
     89                Status=$?       # Preserve $? for message, since [ alters it.
     90                if [ $Status -ne 0 ]; then
     91                        echo "Error while archiving ${WHERE}/${n}.${WHEN}.tar.bz2 - status = $Status"
    6092                        exit 1
    6193                fi
     
    6395done
    6496
    65 find $WHERE -name "samba4_*bz2" -mtime +90 -exec rm  {} \; >/dev/null 2>&1
     97find $WHERE -name "samba4_*bz2" -mtime +$DAYS -exec rm  {} \;
  • vendor/current/source4/scripting/bin/samba_dnsupdate

    r740 r988  
    11#!/usr/bin/env python
     2# vim: expandtab
    23#
    34# update our DNS names using TSIG-GSS
     
    4243from samba import getopt as options
    4344from ldb import SCOPE_BASE
     45from samba import dsdb
    4446from samba.auth import system_session
    4547from samba.samdb import SamDB
    4648from samba.dcerpc import netlogon, winbind
    4749
    48 samba.ensure_external_module("dns", "dnspython")
     50samba.ensure_third_party_module("dns", "dnspython")
    4951import dns.resolver
    5052import dns.exception
     
    6365parser.add_option("--use-file", type="string", help="Use a file, rather than real DNS calls")
    6466parser.add_option("--update-list", type="string", help="Add DNS names from the given file")
     67parser.add_option("--update-cache", type="string", help="Cache database of already registered records")
    6568parser.add_option("--fail-immediately", action='store_true', help="Exit on first failure")
     69parser.add_option("--no-credentials", dest='nocreds', action='store_true', help="don't try and get credentials")
     70parser.add_option("--no-substiutions", dest='nosubs', action='store_true', help="don't try and expands variables in file specified by --update-list")
    6671
    6772creds = None
     
    9095    sys.exit(0)
    9196
     97IP6s = []
     98IP4s = []
     99for i in IPs:
     100    if i.find(':') != -1:
     101        IP6s.append(i)
     102    else:
     103        IP4s.append(i)
     104
     105
    92106if opts.verbose:
    93107    print "IPs: %s" % IPs
    94108
    95 ########################################################
    96 # get credentials if we haven't got them already
     109
    97110def get_credentials(lp):
     111    """# get credentials if we haven't got them already."""
    98112    from samba import credentials
    99     global ccachename, creds
    100     if creds is not None:
    101         return
     113    global ccachename
    102114    creds = credentials.Credentials()
    103115    creds.guess(lp)
     
    105117    creds.set_krb_forwardable(credentials.NO_KRB_FORWARDABLE)
    106118    (tmp_fd, ccachename) = tempfile.mkstemp()
    107     creds.get_named_ccache(lp, ccachename)
    108 
    109 
    110 #############################################
    111 # an object to hold a parsed DNS line
     119    try:
     120        creds.get_named_ccache(lp, ccachename)
     121    except RuntimeError as e:
     122        os.unlink(ccachename)
     123        raise e
     124
     125
    112126class dnsobj(object):
     127    """an object to hold a parsed DNS line"""
     128
    113129    def __init__(self, string_form):
    114130        list = string_form.split()
     131        if len(list) < 3:
     132            raise Exception("Invalid DNS entry %r" % string_form)
    115133        self.dest = None
    116134        self.port = None
     
    119137        self.existing_weight = None
    120138        self.type = list[0]
    121         self.name = list[1].lower()
     139        self.name = list[1]
     140        self.nameservers = []
    122141        if self.type == 'SRV':
    123             self.dest = list[2].lower()
     142            if len(list) < 4:
     143                raise Exception("Invalid DNS entry %r" % string_form)
     144            self.dest = list[2]
    124145            self.port = list[3]
    125         elif self.type == 'A':
     146        elif self.type in ['A', 'AAAA']:
    126147            self.ip   = list[2] # usually $IP, which gets replaced
    127148        elif self.type == 'CNAME':
    128             self.dest = list[2].lower()
     149            self.dest = list[2]
     150        elif self.type == 'NS':
     151            self.dest = list[2]
    129152        else:
    130             print "Received unexpected DNS reply of type %s" % self.type
    131             raise
     153            raise Exception("Received unexpected DNS reply of type %s: %s" % (self.type, string_form))
    132154
    133155    def __str__(self):
    134         if d.type == "A":     return "%s %s %s" % (self.type, self.name, self.ip)
    135         if d.type == "SRV":   return "%s %s %s %s" % (self.type, self.name, self.dest, self.port)
    136         if d.type == "CNAME": return "%s %s %s" % (self.type, self.name, self.dest)
    137 
    138 
    139 ################################################
    140 # parse a DNS line from
     156        if self.type == "A":
     157            return "%s %s %s" % (self.type, self.name, self.ip)
     158        if self.type == "AAAA":
     159            return "%s %s %s" % (self.type, self.name, self.ip)
     160        if self.type == "SRV":
     161            return "%s %s %s %s" % (self.type, self.name, self.dest, self.port)
     162        if self.type == "CNAME":
     163            return "%s %s %s" % (self.type, self.name, self.dest)
     164        if self.type == "NS":
     165            return "%s %s %s" % (self.type, self.name, self.dest)
     166
     167
    141168def parse_dns_line(line, sub_vars):
     169    """parse a DNS line from."""
     170    if line.startswith("SRV _ldap._tcp.pdc._msdcs.") and not samdb.am_pdc():
     171        # We keep this as compat to the dns_update_list of 4.0/4.1
     172        if opts.verbose:
     173            print "Skipping PDC entry (%s) as we are not a PDC" % line
     174        return None
    142175    subline = samba.substitute_var(line, sub_vars)
    143     d = dnsobj(subline)
    144     return d
    145 
    146 ############################################
    147 # see if two hostnames match
     176    if subline == '' or subline[0] == "#":
     177        return None
     178    return dnsobj(subline)
     179
     180
    148181def hostname_match(h1, h2):
     182    """see if two hostnames match."""
    149183    h1 = str(h1)
    150184    h2 = str(h2)
     
    152186
    153187
    154 ############################################
    155 # check that a DNS entry exists
    156188def check_dns_name(d):
     189    """check that a DNS entry exists."""
    157190    normalised_name = d.name.rstrip('.') + '.'
    158191    if opts.verbose:
    159192        print "Looking for DNS entry %s as %s" % (d, normalised_name)
    160  
     193
    161194    if opts.use_file is not None:
    162195        try:
     
    164197        except IOError:
    165198            return False
    166        
     199
    167200        for line in dns_file:
    168201            line = line.strip()
     
    173206        return False
    174207
     208    resolv_conf = os.getenv('RESOLV_WRAPPER_CONF')
     209    if not resolv_conf:
     210        resolv_conf = '/etc/resolv.conf'
     211    resolver = dns.resolver.Resolver(filename=resolv_conf, configure=True)
     212
     213    if d.nameservers != []:
     214        resolver.nameservers = d.nameservers
     215    else:
     216        d.nameservers = resolver.nameservers
     217
    175218    try:
    176         ans = dns.resolver.query(normalised_name, d.type)
     219        ans = resolver.query(normalised_name, d.type)
    177220    except dns.exception.DNSException:
    178221        if opts.verbose:
    179222            print "Failed to find DNS entry %s" % d
    180223        return False
    181     if d.type == 'A':
     224    if d.type in ['A', 'AAAA']:
    182225        # we need to be sure that our IP is there
    183226        for rdata in ans:
    184227            if str(rdata) == str(d.ip):
    185228                return True
    186     if d.type == 'CNAME':
     229    elif d.type == 'CNAME':
    187230        for i in range(len(ans)):
    188231            if hostname_match(ans[i].target, d.dest):
    189232                return True
    190     if d.type == 'SRV':
     233    elif d.type == 'NS':
     234        for i in range(len(ans)):
     235            if hostname_match(ans[i].target, d.dest):
     236                return True
     237    elif d.type == 'SRV':
    191238        for rdata in ans:
    192239            if opts.verbose:
     
    205252
    206253
    207 ###########################################
    208 # get the list of substitution vars
    209 def get_subst_vars():
     254def get_subst_vars(samdb):
     255    """get the list of substitution vars."""
    210256    global lp, am_rodc
    211257    vars = {}
    212258
    213     samdb = SamDB(url=lp.get("sam database"), session_info=system_session(),
    214                   lp=lp)
    215 
    216     vars['DNSDOMAIN'] = lp.get('realm').lower()
    217     vars['DNSFOREST'] = lp.get('realm').lower()
    218     vars['HOSTNAME']  = lp.get('netbios name').lower() + "." + vars['DNSDOMAIN']
     259    vars['DNSDOMAIN'] = samdb.domain_dns_name()
     260    vars['DNSFOREST'] = samdb.forest_dns_name()
     261    vars['HOSTNAME']  = samdb.host_dns_name()
    219262    vars['NTDSGUID']  = samdb.get_ntds_GUID()
    220263    vars['SITE']      = samdb.server_site_name()
    221     res = samdb.search(base=None, scope=SCOPE_BASE, attrs=["objectGUID"])
     264    res = samdb.search(base=samdb.get_default_basedn(), scope=SCOPE_BASE, attrs=["objectGUID"])
    222265    guid = samdb.schema_format_value("objectGUID", res[0]['objectGUID'][0])
    223266    vars['DOMAINGUID'] = guid
     267
     268    vars['IF_DC'] = ""
     269    vars['IF_RWDC'] = "# "
     270    vars['IF_RODC'] = "# "
     271    vars['IF_PDC'] = "# "
     272    vars['IF_GC'] = "# "
     273    vars['IF_RWGC'] = "# "
     274    vars['IF_ROGC'] = "# "
     275    vars['IF_DNS_DOMAIN'] = "# "
     276    vars['IF_RWDNS_DOMAIN'] = "# "
     277    vars['IF_RODNS_DOMAIN'] = "# "
     278    vars['IF_DNS_FOREST'] = "# "
     279    vars['IF_RWDNS_FOREST'] = "# "
     280    vars['IF_R0DNS_FOREST'] = "# "
     281
    224282    am_rodc = samdb.am_rodc()
     283    if am_rodc:
     284        vars['IF_RODC'] = ""
     285    else:
     286        vars['IF_RWDC'] = ""
     287
     288    if samdb.am_pdc():
     289        vars['IF_PDC'] = ""
     290
     291    # check if we "are DNS server"
     292    res = samdb.search(base=samdb.get_config_basedn(),
     293                   expression='(objectguid=%s)' % vars['NTDSGUID'],
     294                   attrs=["options", "msDS-hasMasterNCs"])
     295
     296    if len(res) == 1:
     297        if "options" in res[0]:
     298            options = int(res[0]["options"][0])
     299            if (options & dsdb.DS_NTDSDSA_OPT_IS_GC) != 0:
     300                vars['IF_GC'] = ""
     301                if am_rodc:
     302                    vars['IF_ROGC'] = ""
     303                else:
     304                    vars['IF_RWGC'] = ""
     305
     306        basedn = str(samdb.get_default_basedn())
     307        forestdn = str(samdb.get_root_basedn())
     308
     309        if "msDS-hasMasterNCs" in res[0]:
     310            for e in res[0]["msDS-hasMasterNCs"]:
     311                if str(e) == "DC=DomainDnsZones,%s" % basedn:
     312                    vars['IF_DNS_DOMAIN'] = ""
     313                    if am_rodc:
     314                        vars['IF_RODNS_DOMAIN'] = ""
     315                    else:
     316                        vars['IF_RWDNS_DOMAIN'] = ""
     317                if str(e) == "DC=ForestDnsZones,%s" % forestdn:
     318                    vars['IF_DNS_FOREST'] = ""
     319                    if am_rodc:
     320                        vars['IF_RODNS_FOREST'] = ""
     321                    else:
     322                        vars['IF_RWDNS_FOREST'] = ""
    225323
    226324    return vars
    227325
    228326
    229 ############################################
    230 # call nsupdate for an entry
    231 def call_nsupdate(d):
    232     global ccachename, nsupdate_cmd
    233 
    234     if opts.verbose:
    235         print "Calling nsupdate for %s" % d
     327def call_nsupdate(d, op="add"):
     328    """call nsupdate for an entry."""
     329    global ccachename, nsupdate_cmd, krb5conf
     330
     331    assert(op in ["add", "delete"])
     332
     333    if opts.verbose:
     334        print "Calling nsupdate for %s (%s)" % (d, op)
    236335
    237336    if opts.use_file is not None:
    238         wfile = open(opts.use_file, 'a')
    239         fcntl.lockf(wfile, fcntl.LOCK_EX)
    240         wfile.write(str(d)+"\n")
    241         fcntl.lockf(wfile, fcntl.LOCK_UN)
     337        try:
     338            rfile = open(opts.use_file, 'r+')
     339        except IOError:
     340            # Perhaps create it
     341            rfile = open(opts.use_file, 'w+')
     342            # Open it for reading again, in case someone else got to it first
     343            rfile = open(opts.use_file, 'r+')
     344        fcntl.lockf(rfile, fcntl.LOCK_EX)
     345        (file_dir, file_name) = os.path.split(opts.use_file)
     346        (tmp_fd, tmpfile) = tempfile.mkstemp(dir=file_dir, prefix=file_name, suffix="XXXXXX")
     347        wfile = os.fdopen(tmp_fd, 'a')
     348        rfile.seek(0)
     349        for line in rfile:
     350            if op == "delete":
     351                l = parse_dns_line(line, {})
     352                if str(l).lower() == str(d).lower():
     353                    continue
     354            wfile.write(line)
     355        if op == "add":
     356            wfile.write(str(d)+"\n")
     357        os.rename(tmpfile, opts.use_file)
     358        fcntl.lockf(rfile, fcntl.LOCK_UN)
    242359        return
    243360
     
    246363    (tmp_fd, tmpfile) = tempfile.mkstemp()
    247364    f = os.fdopen(tmp_fd, 'w')
     365    if d.nameservers != []:
     366        f.write('server %s\n' % d.nameservers[0])
    248367    if d.type == "A":
    249         f.write("update add %s %u A %s\n" % (normalised_name, default_ttl, d.ip))
     368        f.write("update %s %s %u A %s\n" % (op, normalised_name, default_ttl, d.ip))
     369    if d.type == "AAAA":
     370        f.write("update %s %s %u AAAA %s\n" % (op, normalised_name, default_ttl, d.ip))
    250371    if d.type == "SRV":
    251         if d.existing_port is not None:
     372        if op == "add" and d.existing_port is not None:
    252373            f.write("update delete %s SRV 0 %s %s %s\n" % (normalised_name, d.existing_weight,
    253374                                                           d.existing_port, d.dest))
    254         f.write("update add %s %u SRV 0 100 %s %s\n" % (normalised_name, default_ttl, d.port, d.dest))
     375        f.write("update %s %s %u SRV 0 100 %s %s\n" % (op, normalised_name, default_ttl, d.port, d.dest))
    255376    if d.type == "CNAME":
    256         f.write("update add %s %u CNAME %s\n" % (normalised_name, default_ttl, d.dest))
     377        f.write("update %s %s %u CNAME %s\n" % (op, normalised_name, default_ttl, d.dest))
     378    if d.type == "NS":
     379        f.write("update %s %s %u NS %s\n" % (op, normalised_name, default_ttl, d.dest))
    257380    if opts.verbose:
    258381        f.write("show\n")
     
    260383    f.close()
    261384
    262     os.environ["KRB5CCNAME"] = ccachename
     385    global error_count
     386    if ccachename:
     387        os.environ["KRB5CCNAME"] = ccachename
    263388    try:
    264389        cmd = nsupdate_cmd[:]
    265390        cmd.append(tmpfile)
    266         subprocess.check_call(cmd, shell=False)
     391        env = os.environ
     392        if krb5conf:
     393            env["KRB5_CONFIG"] = krb5conf
     394        if ccachename:
     395            env["KRB5CCNAME"] = ccachename
     396        ret = subprocess.call(cmd, shell=False, env=env)
     397        if ret != 0:
     398            if opts.fail_immediately:
     399                if opts.verbose:
     400                    print("Failed update with %s" % tmpfile)
     401                sys.exit(1)
     402            error_count = error_count + 1
     403            if opts.verbose:
     404                print("Failed nsupdate: %d" % ret)
    267405    except Exception, estr:
    268         global error_count
    269406        if opts.fail_immediately:
    270407            sys.exit(1)
     
    276413
    277414
    278 def rodc_dns_update(d, t):
     415def rodc_dns_update(d, t, op):
    279416    '''a single DNS update via the RODC netlogon call'''
    280417    global sub_vars
     418
     419    assert(op in ["add", "delete"])
    281420
    282421    if opts.verbose:
     
    303442    if d.port is not None:
    304443        name.port = int(d.port)
    305     name.dns_register = True
     444    if op == "add":
     445        name.dns_register = True
     446    else:
     447        name.dns_register = False
    306448    dns_names.names = [ name ]
    307449    site_name = sub_vars['SITE'].decode('utf-8')
     
    322464
    323465
    324 def call_rodc_update(d):
     466def call_rodc_update(d, op="add"):
    325467    '''RODCs need to use the netlogon API for nsupdate'''
    326468    global lp, sub_vars
     469
     470    assert(op in ["add", "delete"])
    327471
    328472    # we expect failure for 3268 if we aren't a GC
     
    345489        if subname.lower() == d.name.lower():
    346490            # found a match - do the update
    347             rodc_dns_update(d, t)
     491            rodc_dns_update(d, t, op)
    348492            return
    349493    if opts.verbose:
     
    357501    dns_update_list = lp.private_path('dns_update_list')
    358502
     503if opts.update_cache:
     504    dns_update_cache = opts.update_cache
     505else:
     506    dns_update_cache = lp.private_path('dns_update_cache')
     507
    359508# use our private krb5.conf to avoid problems with the wrong domain
    360509# bind9 nsupdate wants the default domain set
     
    364513file = open(dns_update_list, "r")
    365514
    366 # get the substitution dictionary
    367 sub_vars = get_subst_vars()
     515if opts.nosubs:
     516    sub_vars = {}
     517else:
     518    samdb = SamDB(url=lp.samdb_url(), session_info=system_session(), lp=lp)
     519
     520    # get the substitution dictionary
     521    sub_vars = get_subst_vars(samdb)
    368522
    369523# build up a list of update commands to pass to nsupdate
    370524update_list = []
    371525dns_list = []
     526cache_list = []
     527delete_list = []
     528
     529dup_set = set()
     530cache_set = set()
     531
     532rebuild_cache = False
     533try:
     534    cfile = open(dns_update_cache, 'r+')
     535except IOError:
     536    # Perhaps create it
     537    cfile = open(dns_update_cache, 'w+')
     538    # Open it for reading again, in case someone else got to it first
     539    cfile = open(dns_update_cache, 'r+')
     540fcntl.lockf(cfile, fcntl.LOCK_EX)
     541for line in cfile:
     542    line = line.strip()
     543    if line == '' or line[0] == "#":
     544        continue
     545    c = parse_dns_line(line, {})
     546    if c is None:
     547        continue
     548    if str(c) not in cache_set:
     549        cache_list.append(c)
     550        cache_set.add(str(c))
    372551
    373552# read each line, and check that the DNS name exists
     
    377556        continue
    378557    d = parse_dns_line(line, sub_vars)
    379     dns_list.append(d)
     558    if d is None:
     559        continue
     560    if d.type == 'A' and len(IP4s) == 0:
     561        continue
     562    if d.type == 'AAAA' and len(IP6s) == 0:
     563        continue
     564    if str(d) not in dup_set:
     565        dns_list.append(d)
     566        dup_set.add(str(d))
    380567
    381568# now expand the entries, if any are A record with ip set to $IP
    382569# then replace with multiple entries, one for each interface IP
    383570for d in dns_list:
    384     if d.type == 'A' and d.ip == "$IP":
    385         d.ip = IPs[0]
    386         for i in range(len(IPs)-1):
     571    if d.ip != "$IP":
     572        continue
     573    if d.type == 'A':
     574        d.ip = IP4s[0]
     575        for i in range(len(IP4s)-1):
    387576            d2 = dnsobj(str(d))
    388             d2.ip = IPs[i+1]
     577            d2.ip = IP4s[i+1]
     578            dns_list.append(d2)
     579    if d.type == 'AAAA':
     580        d.ip = IP6s[0]
     581        for i in range(len(IP6s)-1):
     582            d2 = dnsobj(str(d))
     583            d2.ip = IP6s[i+1]
    389584            dns_list.append(d2)
    390585
    391586# now check if the entries already exist on the DNS server
    392587for d in dns_list:
    393     if opts.all_names or not check_dns_name(d):
     588    found = False
     589    for c in cache_list:
     590        if str(c).lower() == str(d).lower():
     591            found = True
     592            break
     593    if not found:
     594        rebuild_cache = True
     595    if opts.all_names:
    394596        update_list.append(d)
    395 
    396 if len(update_list) == 0:
     597        if opts.verbose:
     598            print "force update: %s" % d
     599    elif not check_dns_name(d):
     600        update_list.append(d)
     601        if opts.verbose:
     602            print "need update: %s" % d
     603
     604
     605for c in cache_list:
     606    found = False
     607    for d in dns_list:
     608        if str(c).lower() == str(d).lower():
     609            found = True
     610            break
     611    if found:
     612        continue
     613    rebuild_cache = True
     614    if not opts.all_names and not check_dns_name(c):
     615        continue
     616    delete_list.append(c)
     617    if opts.verbose:
     618        print "need delete: %s" % c
     619
     620if len(delete_list) == 0 and len(update_list) == 0 and not rebuild_cache:
    397621    if opts.verbose:
    398622        print "No DNS updates needed"
    399623    sys.exit(0)
     624else:
     625    if opts.verbose:
     626        print "%d DNS updates and %d DNS deletes needed" % (len(update_list), len(delete_list))
    400627
    401628# get our krb5 creds
    402 get_credentials(lp)
     629if len(delete_list) != 0 or len(update_list) != 0:
     630    if not opts.nocreds:
     631        get_credentials(lp)
     632
     633# ask nsupdate to delete entries as needed
     634for d in delete_list:
     635    if am_rodc:
     636        if d.name.lower() == domain.lower():
     637            if opts.verbose:
     638                print "skip delete (rodc): %s" % d
     639            continue
     640        if not d.type in [ 'A', 'AAAA' ]:
     641            if opts.verbose:
     642                print "delete (rodc): %s" % d
     643            call_rodc_update(d, op="delete")
     644        else:
     645            if opts.verbose:
     646                print "delete (nsupdate): %s" % d
     647            call_nsupdate(d, op="delete")
     648    else:
     649        if opts.verbose:
     650            print "delete (nsupdate): %s" % d
     651        call_nsupdate(d, op="delete")
    403652
    404653# ask nsupdate to add entries as needed
     
    406655    if am_rodc:
    407656        if d.name.lower() == domain.lower():
     657            if opts.verbose:
     658                print "skip (rodc): %s" % d
    408659            continue
    409         if d.type != 'A':
     660        if not d.type in [ 'A', 'AAAA' ]:
     661            if opts.verbose:
     662                print "update (rodc): %s" % d
    410663            call_rodc_update(d)
    411664        else:
     665            if opts.verbose:
     666                print "update (nsupdate): %s" % d
    412667            call_nsupdate(d)
    413668    else:
     669        if opts.verbose:
     670            print "update(nsupdate): %s" % d
    414671        call_nsupdate(d)
     672
     673if rebuild_cache:
     674    (file_dir, file_name) = os.path.split(dns_update_cache)
     675    (tmp_fd, tmpfile) = tempfile.mkstemp(dir=file_dir, prefix=file_name, suffix="XXXXXX")
     676    wfile = os.fdopen(tmp_fd, 'a')
     677    for d in dns_list:
     678        wfile.write(str(d)+"\n")
     679    os.rename(tmpfile, dns_update_cache)
     680fcntl.lockf(cfile, fcntl.LOCK_UN)
    415681
    416682# delete the ccache if we created it
  • vendor/current/source4/scripting/bin/samba_spnupdate

    r740 r988  
    44#
    55# Copyright (C) Andrew Tridgell 2010
     6# Copyright (C) Matthieu Patou <mat@matws.net> 2012
    67#
    78# This program is free software; you can redistribute it and/or modify
     
    1920
    2021
    21 import os, sys
     22import os, sys, re
    2223
    2324# ensure we get messages out immediately, so they get in the samba logs,
     
    7172    vars = {}
    7273
    73     vars['DNSDOMAIN'] = lp.get('realm').lower()
    74     vars['HOSTNAME']  = lp.get('netbios name').lower() + "." + vars['DNSDOMAIN']
     74    vars['DNSDOMAIN'] = samdb.domain_dns_name()
     75    vars['DNSFOREST'] = samdb.forest_dns_name()
     76    vars['HOSTNAME']  = samdb.host_dns_name()
    7577    vars['NETBIOSNAME'] = lp.get('netbios name').upper()
    7678    vars['WORKGROUP'] = lp.get('workgroup')
    7779    vars['NTDSGUID']  = samdb.get_ntds_GUID()
    78     res = samdb.search(base=None, scope=ldb.SCOPE_BASE, attrs=["objectGUID"])
     80    res = samdb.search(base=samdb.get_default_basedn(), scope=ldb.SCOPE_BASE, attrs=["objectGUID"])
    7981    guid = samdb.schema_format_value("objectGUID", res[0]['objectGUID'][0])
    8082    vars['DOMAINGUID'] = guid
     
    8385try:
    8486    private_dir = lp.get("private dir")
    85     secrets_path = os.path.join(private_dir, lp.get("secrets database"))
     87    secrets_path = os.path.join(private_dir, "secrets.ldb")
    8688
    8789    secrets_db = Ldb(url=secrets_path, session_info=system_session(),
     
    104106        credentials = None
    105107
    106     samdb = SamDB(url=lp.get("sam database"), session_info=system_session(), credentials=credentials, lp=lp)
     108    samdb = SamDB(url=lp.samdb_url(), session_info=system_session(), credentials=credentials, lp=lp)
    107109except ldb.LdbError, (num, msg):
    108     print("Unable to open sam database %s : %s" % (lp.get("sam database"), msg))
     110    print("Unable to open sam database %s : %s" % (lp.samdb_url(), msg))
    109111    sys.exit(1)
    110112
     
    119121
    120122spn_list = []
     123
     124has_forest_dns = False
     125has_domain_dns = False
     126# check if we "are DNS server"
     127res = samdb.search(base=samdb.get_config_basedn(),
     128                   expression='(objectguid=%s)' % sub_vars['NTDSGUID'],
     129                   attrs=["msDS-hasMasterNCs"])
     130
     131basedn = str(samdb.get_default_basedn())
     132if len(res) == 1:
     133    if "msDS-hasMasterNCs" in res[0]:
     134        for e in res[0]["msDS-hasMasterNCs"]:
     135            if str(e) == "DC=DomainDnsZones,%s" % basedn:
     136                has_domain_dns = True
     137            if str(e) == "DC=ForestDnsZones,%s" % basedn:
     138                has_forest_dns = True
     139
    121140
    122141# build the spn list
     
    125144    if line == '' or line[0] == "#":
    126145        continue
     146    if re.match(r".*/DomainDnsZones\..*", line) and not has_domain_dns:
     147        continue
     148    if re.match(r".*/ForestDnsZones\..*", line) and not has_forest_dns:
     149        continue
    127150    line = samba.substitute_var(line, sub_vars)
    128151    spn_list.append(line)
    129152
    130153# get the current list of SPNs in our sam
    131 res = samdb.search(base="",
     154res = samdb.search(base=samdb.get_default_basedn(),
    132155                   expression='(&(objectClass=computer)(samaccountname=%s$))' % sub_vars['NETBIOSNAME'],
    133156                   attrs=["servicePrincipalName"])
     
    190213    net = Net(creds=creds, lp=lp)
    191214    try:
    192         cldap_ret = net.finddc(domain, nbt.NBT_SERVER_DS | nbt.NBT_SERVER_WRITABLE)
     215        cldap_ret = net.finddc(domain=domain, flags=nbt.NBT_SERVER_DS | nbt.NBT_SERVER_WRITABLE)
    193216    except Exception, reason:
    194217        print("Unable to find writeable DC for domain '%s' to send DRS writeSPN to : %s" % (domain, reason))
     
    197220    try:
    198221        binding_options = "seal"
    199         if lp.get("log level") >= 5:
     222        if int(lp.get("log level")) >= 5:
    200223            binding_options += ",print"
    201224        drs = drsuapi.drsuapi('ncacn_ip_tcp:%s[%s]' % (server, binding_options), lp, creds)
     
    221244    req1.spn_names = spn_names
    222245    (level, res) = drs.DsWriteAccountSpn(drs_handle, 1, req1)
     246    if (res.status != (0, 'WERR_OK')):
     247        print "WriteAccountSpn has failed with error %s" % str(res.status)
    223248
    224249if samdb.am_rodc():
  • vendor/current/source4/scripting/bin/setup_dns.sh

    r740 r988  
    1414
    1515[ -z "$PRIVATEDIR" ] && {
    16     PRIVATEDIR=$(bin/testparm --section-name=global --parameter-name='private dir' --suppress-prompt 2> /dev/null)
     16    PRIVATEDIR=$(bin/samba-tool testparm --section-name=global --parameter-name='private dir' --suppress-prompt 2> /dev/null)
    1717}
    1818
    1919OBJECTGUID=$(bin/ldbsearch -s base -H "$PRIVATEDIR/sam.ldb" -b "CN=NTDS Settings,CN=$HOSTNAME,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=$RSUFFIX" objectguid|grep ^objectGUID| cut -d: -f2)
    2020
     21samba4kinit=kinit
     22if test -x $BINDIR/samba4kinit; then
     23        samba4kinit=bin/samba4kinit
     24fi
     25
    2126echo "Found objectGUID $OBJECTGUID"
    2227
    2328echo "Running kinit for $HOSTNAME\$@$DOMAIN"
    24 bin/samba4kinit -e arcfour-hmac-md5 -k -t "$PRIVATEDIR/secrets.keytab" $HOSTNAME\$@$DOMAIN || exit 1
     29$samba4kinit -e arcfour-hmac-md5 -k -t "$PRIVATEDIR/secrets.keytab" $HOSTNAME\$@$DOMAIN || exit 1
    2530echo "Adding $HOSTNAME.$DOMAIN"
    2631scripting/bin/nsupdate-gss --noverify $HOSTNAME $DOMAIN $IP 300 || {
  • vendor/current/source4/scripting/bin/smbstatus

    r740 r988  
    33#
    44#  provide information on connected users and open files
    5 #  Copyright ǒ Jelmer Vernooij 2008
     5#  Copyright (c) Jelmer Vernooij 2008
    66#
    77#  Based on the original in EJS:
     
    1212import os, sys
    1313
     14# make sure the script dies immediately when hitting control-C,
     15# rather than raising KeyboardInterrupt. As we do all database
     16# operations using transactions, this is safe.
     17import signal
     18signal.signal(signal.SIGINT, signal.SIG_DFL)
     19
    1420sys.path.insert(0, "bin/python")
    1521
     
    1925
    2026def show_sessions(conn):
    21         """show open sessions"""
     27    """show open sessions"""
    2228
    23         sessions = conn.smbsrv_information(irpc.SMBSRV_INFO_SESSIONS).next()
    24         print "User                                  Client      Connected at"
    25         print "-" * 79
    26         for session in sessions:
    27                 fulluser = "%s/%s" % (session.account_name, session.domain_name)
    28                 print "%-30s %16s   %s" % (fulluser, session.client_ip, sys.httptime(session.connect_time))
    29         print ""
     29    sessions = conn.smbsrv_information(irpc.SMBSRV_INFO_SESSIONS).next()
     30    print "User                                  Client      Connected at"
     31    print "-" * 79
     32    for session in sessions:
     33        fulluser = "%s/%s" % (session.account_name, session.domain_name)
     34        print "%-30s %16s   %s" % (fulluser, session.client_ip, sys.httptime(session.connect_time))
     35    print ""
    3036
    3137def show_tcons(open_connection):
    32         """show open tree connects"""
    33         conn = open_connection("smb_server")
    34         tcons = conn.smbsrv_information(irpc.SMBSRV_INFO_TCONS).next()
    35         print "Share                                 Client      Connected at"
    36         print "-" * 79
    37         for tcon in tcons:
    38                 print "%-30s %16s   %s" % (tcon.share_name, tcon.client_ip, sys.httptime(tcon.connect_time))
     38    """show open tree connects"""
     39    conn = open_connection("smb_server")
     40    tcons = conn.smbsrv_information(irpc.SMBSRV_INFO_TCONS).next()
     41    print "Share                                 Client      Connected at"
     42    print "-" * 79
     43    for tcon in tcons:
     44        print "%-30s %16s   %s" % (tcon.share_name, tcon.client_ip, sys.httptime(tcon.connect_time))
    3945
    4046
    4147def show_nbt(open_connection):
    42         """show nbtd information"""
    43         conn = open_connection("nbt_server")
    44         stats = conn.nbtd_information(irpc.NBTD_INFO_STATISTICS).next()
    45         print "NBT server statistics:"
    46         fields = [("total_received", "Total received"),
    47                           ("total_sent", "Total sent"),
    48                           ("query_count", "Query count"),
    49                           ("register_count", "Register count"),
    50                           ("release_count", "Release count")]
    51         for (field, description) in fields:
    52                 print "\t%s:\t%s" % (description, getattr(stats, field))
    53         print
     48    """show nbtd information"""
     49    conn = open_connection("nbt_server")
     50    stats = conn.nbtd_information(irpc.NBTD_INFO_STATISTICS).next()
     51    print "NBT server statistics:"
     52    fields = [("total_received", "Total received"),
     53              ("total_sent", "Total sent"),
     54              ("query_count", "Query count"),
     55              ("register_count", "Register count"),
     56              ("release_count", "Release count")]
     57    for (field, description) in fields:
     58        print "\t%s:\t%s" % (description, getattr(stats, field))
     59    print
    5460
    5561parser = optparse.OptionParser("%s [options]" % sys.argv[0])
     
    5763parser.add_option_group(sambaopts)
    5864parser.add_option("--messaging-path", type="string", metavar="PATH",
    59                           help="messaging path")
     65                  help="messaging path")
    6066parser.add_option("--nbt", help="show NetBIOS status", action="store_true")
    6167
     
    6975
    7076def open_connection(name):
    71         return messaging.ClientConnection(name, messaging_path=messaging_path)
     77    return messaging.ClientConnection(name, messaging_path=messaging_path)
    7278
    7379if opts.nbt:
    74         show_nbt(open_connection)
     80    show_nbt(open_connection)
    7581else:
    76         try:
    77                 conn = open_connection("smb_server")
    78         except RuntimeError, (num, msg):
    79                 if msg == 'NT_STATUS_OBJECT_NAME_NOT_FOUND':
    80                         print "No active connections"
    81         else:
    82                 show_sessions(conn)
    83                 show_tcons(conn)
     82    try:
     83        conn = open_connection("smb_server")
     84    except RuntimeError, (num, msg):
     85        if msg == 'NT_STATUS_OBJECT_NAME_NOT_FOUND':
     86            print "No active connections"
     87    else:
     88        show_sessions(conn)
     89        show_tcons(conn)
  • vendor/current/source4/scripting/bin/subunitrun

    r740 r988  
    22
    33# Simple subunit testrunner for python
    4 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007
    5 #   
     4
     5# NOTE: This is deprecated - Using the standard subunit runner is
     6# preferred - e.g. "python -m samba.subunit.run YOURMODULE".
     7#
     8# This wrapper will be removed once all tests can be run
     9# without it. At the moment there are various tests which still
     10# get e.g. credentials passed via command-line options to this
     11# script.
     12
     13# Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2014
     14#
    615# This program is free software; you can redistribute it and/or modify
    716# it under the terms of the GNU General Public License as published by
    817# the Free Software Foundation; either version 3 of the License, or
    918# (at your option) any later version.
    10 #   
     19#
    1120# This program is distributed in the hope that it will be useful,
    1221# but WITHOUT ANY WARRANTY; without even the implied warranty of
    1322# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    1423# GNU General Public License for more details.
    15 #   
     24#
    1625# You should have received a copy of the GNU General Public License
    1726# along with this program.  If not, see <http://www.gnu.org/licenses/>.
     
    2029import sys
    2130
     31# make sure the script dies immediately when hitting control-C,
     32# rather than raising KeyboardInterrupt. As we do all database
     33# operations using transactions, this is safe.
     34import signal
     35signal.signal(signal.SIGINT, signal.SIG_DFL)
     36
    2237# Find right directory when running from source tree
    2338sys.path.insert(0, "bin/python")
     
    2540import optparse
    2641import samba
    27 samba.ensure_external_module("testtools", "testtools")
    28 samba.ensure_external_module("subunit", "subunit/python")
    29 from subunit.run import SubunitTestRunner
     42from samba.tests.subunitrun import TestProgram, SubunitOptions
     43
    3044import samba.getopt as options
    3145import samba.tests
    3246
    3347
    34 parser = optparse.OptionParser("subunitrun [options] <tests>")
     48usage = 'subunitrun [options] <tests>'
     49description = '''
     50This runs a Samba python test suite. The tests are typically located in
     51python/samba/tests/*.py
     52
     53To run the tests from one of those modules, specify the test as
     54samba.tests.MODULE. For example, to run the tests in common.py:
     55
     56   subunitrun samba.tests.common
     57
     58To list the tests in that module, use:
     59
     60   subunitrun -l samba.tests.common
     61
     62NOTE: This script is deprecated in favor of "python -m subunit.run". Don't use
     63it unless it can be avoided.
     64'''
     65
     66def format_description(formatter):
     67    '''hack to prevent textwrap of the description'''
     68    return description
     69
     70parser = optparse.OptionParser(usage=usage, description=description)
     71parser.format_description = format_description
    3572credopts = options.CredentialsOptions(parser)
     73sambaopts = options.SambaOptions(parser)
     74subunitopts = SubunitOptions(parser)
    3675parser.add_option_group(credopts)
    37 try:
    38     from subunit.run import TestProgram
    39 except ImportError:
    40     from unittest import TestProgram
    41 else:
    42     parser.add_option('-l', '--list', dest='listtests', default=False,
    43                       help='List tests rather than running them.',
    44                       action="store_true")
     76parser.add_option_group(sambaopts)
     77parser.add_option_group(subunitopts)
    4578
    4679opts, args = parser.parse_args()
    4780
    48 samba.tests.cmdline_credentials = credopts.get_credentials(samba.tests.env_loadparm())
    49 if getattr(opts, "listtests", False):
    50     args.insert(0, "--list")
     81if not getattr(opts, "listtests", False):
     82    lp = sambaopts.get_loadparm()
     83    samba.tests.cmdline_credentials = credopts.get_credentials(lp)
     84if getattr(opts, 'load_list', None):
     85    args.insert(0, "--load-list=%s" % opts.load_list)
    5186
    52 runner = SubunitTestRunner()
    53 program = TestProgram(module=None, argv=[sys.argv[0]] + args, testRunner=runner)
     87TestProgram(module=None, args=args, opts=subunitopts)
  • vendor/current/source4/scripting/devel/chgtdcpass

    r740 r988  
    3030from samba.auth import system_session
    3131from samba import param
     32from samba.provision import find_provision_key_parameters
    3233from samba.upgradehelpers import (get_paths,
    33                                  find_provision_key_parameters, get_ldbs,
     34                                  get_ldbs,
    3435                                 update_machine_account_password)
    3536
  • vendor/current/source4/scripting/devel/drs/vampire_ad.sh

    r740 r988  
    2424REALM="$(echo $DNSDOMAIN | tr '[a-z]' '[A-Z]')"
    2525
    26 sudo $GDB bin/samba-tool join $DNSDOMAIN DC -Uadministrator%$pass -s $PREFIX/etc/smb.conf --option=realm=$REALM --option="ads:dc function level=4" --option="ads:min function level=0" -d2 "$@" || exit 1
     26sudo $GDB bin/samba-tool domain join $DNSDOMAIN DC -Uadministrator%$pass -s $PREFIX/etc/smb.conf --option=realm=$REALM --option="ads:dc function level=4" --option="ads:min function level=0" -d2 "$@" || exit 1
    2727# PRIVATEDIR=$PREFIX/private sudo -E scripting/bin/setup_dns.sh $machine $DNSDOMAIN $machine_ip || exit 1
    2828#sudo rndc flush
  • vendor/current/source4/scripting/devel/getncchanges

    r740 r988  
    1414from samba.samdb import SamDB
    1515from samba.auth import system_session
     16from samba.ndr import ndr_unpack
    1617
    1718def do_DsBind(drs):
     
    101102    parser.add_option("", "--exop", dest="exop", help="extended operation",)
    102103    parser.add_option("", "--pas", dest="use_pas", action='store_true', default=False,
    103                       help="send partial attribute set",)
    104     parser.add_option("", "--dest-dsa", type='str',
    105                       default='"9c637462-5b8c-4467-aef2-bdb1f57bc4ef"', help="destination DSA GUID")
     104                      help="send partial attribute set (for RODC)")
     105    parser.add_option("", "--nb-iter", type='int', help="Number of getncchange iterations")
     106    parser.add_option("", "--dest-dsa", type='str', help="destination DSA GUID")
     107    parser.add_option("", "--rodc", action='store_true', default=False,
     108                      help='use RODC replica flags')
     109    parser.add_option("", "--partial-rw", action='store_true', default=False,
     110                      help='use RW partial replica flags, not be confused with --pas')
    106111    parser.add_option("", "--replica-flags", type='int',
    107112                      default=drsuapi.DRSUAPI_DRS_INIT_SYNC |
    108113                      drsuapi.DRSUAPI_DRS_PER_SYNC |
     114                      drsuapi.DRSUAPI_DRS_WRIT_REP |
    109115                      drsuapi.DRSUAPI_DRS_GET_ANC |
    110116                      drsuapi.DRSUAPI_DRS_NEVER_SYNCED,
     
    112118
    113119    (opts, args) = parser.parse_args()
     120    if opts.rodc:
     121        opts.replica_flags = drsuapi.DRSUAPI_DRS_INIT_SYNC |\
     122                             drsuapi.DRSUAPI_DRS_PER_SYNC |\
     123                             drsuapi.DRSUAPI_DRS_GET_ANC |\
     124                             drsuapi.DRSUAPI_DRS_NEVER_SYNCED |\
     125                             drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING |\
     126                             drsuapi.DRSUAPI_DRS_GET_ALL_GROUP_MEMBERSHIP
     127
     128    if opts.partial_rw:
     129        opts.replica_flags = drsuapi.DRSUAPI_DRS_INIT_SYNC |\
     130                             drsuapi.DRSUAPI_DRS_PER_SYNC |\
     131                             drsuapi.DRSUAPI_DRS_GET_ANC |\
     132                             drsuapi.DRSUAPI_DRS_NEVER_SYNCED
    114133
    115134    lp = sambaopts.get_loadparm()
     
    121140    if creds.is_anonymous():
    122141        parser.error("You must supply credentials")
     142
     143    if opts.partial_rw and opts.rodc:
     144        parser.error("Can't specify --partial-rw and --rodc")
    123145
    124146    server = args[0]
     
    148170        exop = int(opts.exop)
    149171
     172    dest_dsa = opts.dest_dsa
     173    if not dest_dsa:
     174        print "no dest_dsa specified trying to figure out from ldap"
     175        msgs = samdb.search(controls=["search_options:1:2"],
     176                           expression='(objectclass=ntdsdsa)')
     177        if len(msgs) == 1:
     178            dest_dsa = str(ndr_unpack(misc.GUID,  msgs[0]["invocationId"][0]))
     179            print "Found this dsa: %s" % dest_dsa
     180        else:
     181            # TODO fixme
     182            pass
     183        if not dest_dsa:
     184            print "Unable to find the dest_dsa automatically please specify it"
     185            import sys
     186            sys.exit(1)
     187
    150188    null_guid = misc.GUID()
    151     req8.destination_dsa_guid               = misc.GUID(opts.dest_dsa)
     189    req8.destination_dsa_guid               = misc.GUID(dest_dsa)
    152190    req8.source_dsa_invocation_id           = misc.GUID(samdb.get_invocation_id())
    153191    req8.naming_context                     = drsuapi.DsReplicaObjectIdentifier()
     
    171209    req8.mapping_ctr.mappings                = None
    172210
     211    nb_iter = 0
    173212    while True:
    174213        (level, ctr) = drs.DsGetNCChanges(drs_handle, 8, req8)
    175         if ctr.more_data == 0:
     214        nb_iter += 1
     215        if ctr.more_data == 0 or opts.nb_iter == nb_iter:
    176216            break
    177         req8.highwatermark.tmp_highest_usn = ctr.new_highwatermark.tmp_highest_usn
     217        req8.highwatermark = ctr.new_highwatermark
  • vendor/current/source4/scripting/devel/selftest-vars.sh

    r740 r988  
    33
    44export UID_WRAPPER=1
    5 export NSS_WRAPPER_PASSWD=st/dc/passwd
    6 export NSS_WRAPPER_GROUP=st/dc/group
    7 export CONFIGURATION="--configfile=$PWD/st/dc/etc/smb.conf"
     5export NSS_WRAPPER_PASSWD=$PWD/st/ad_dc_ntvfs/passwd
     6export NSS_WRAPPER_GROUP=$PWD/st/ad_dc_ntvfs/group
     7export CONFIGURATION="--configfile=$PWD/st/ad_dc_ntvfs/etc/smb.conf"
     8export VAMPIRE_DC_SERVER=localvampiredc
     9export VAMPIRE_DC_SERVER_IP=127.0.0.22
     10export VAMPIRE_DC_NETBIOSNAME=localvampiredc1
     11export VAMPIRE_DC_NETBIOSALIAS=localvampiredc
    812export MEMBER_SERVER=localmember3
    9 export MEMBER_SERVER_IP=127.0.0.3
     13export MEMBER_SERVER_IP=127.0.0.23
    1014export MEMBER_NETBIOSNAME=localmember3
    1115export MEMBER_NETBIOSALIAS=localmember
    1216export RPC_PROXY_SERVER=localrpcproxy4
    13 export RPC_PROXY_SERVER_IP=127.0.0.4
     17export RPC_PROXY_SERVER_IP=127.0.0.24
    1418export RPC_PROXY_NETBIOSNAME=localrpcproxy4
    1519export RPC_PROXY_NETBIOSALIAS=localrpcproxy
    16 export SELFTEST_TARGET="samba4"
    1720export SELFTEST_MAXTIME=1200
    1821export NETBIOSNAME=localdc1
    1922export REALM=SAMBA.EXAMPLE.COM
    20 export SOCKET_WRAPPER_DEFAULT_IFACE=1
     23export SOCKET_WRAPPER_DEFAULT_IFACE=21
    2124export SERVER=localdc1
    22 export WINBINDD_SOCKET_DIR=$PWD/st/dc/winbindd_socket
     25export SELFTEST_WINBINDD_SOCKET_DIR=$PWD/st/ad_dc_ntvfs/winbindd_socket
    2326export SELFTEST_PREFIX=$PWD/st
    2427export DOMAIN=SAMBADOMAIN
    25 export BUILDDIR=.
    26 export DC_SERVER_IP=127.0.0.1
     28export BINDIR=./bin
     29export DC_SERVER_IP=127.0.0.21
    2730export SELFTEST_INTERFACES=127.0.0.6/8,127.0.0.7/8,127.0.0.8/8,127.0.0.9/8,127.0.0.10/8,127.0.0.11/8
    2831export SOCKET_WRAPPER_DIR=$PWD/st/w
    2932export DC_USERNAME=Administrator
    3033export USERNAME=Administrator
    31 export SERVER_IP=127.0.0.1
    32 export KRB5_CONFIG=$PWD/st/dc/etc/krb5.conf
     34export SERVER_IP=127.0.0.21
     35export KRB5_CONFIG=$PWD/st/ad_dc_ntvfs/etc/krb5.conf
    3336export PREFIX_ABS=$PWD/st
    3437export SRCDIR_ABS=$PWD
    35 export PREFIX=./st
    36 export KRB5CCNAME=./st/krb5ticket
    37 export SRCDIR=.
     38export PREFIX=$PWD/st
     39export KRB5CCNAME=$PWD/st/krb5ticket
     40export SRCDIR=$PWD/
    3841export TLS_ENABLED=yes
    3942export DC_NETBIOSALIAS=localdc
     
    4447export PASSWORD=locDCpass1
    4548export NETBIOSALIAS=localdc
    46 export SMB_CONF_PATH=$PWD/st/dc/etc/smb.conf
     49export SMB_CONF_PATH=$PWD/st/ad_dc_ntvfs/etc/smb.conf
  • vendor/current/source4/scripting/devel/speedtest.py

    r740 r988  
    3131sys.path.insert(0, "bin/python")
    3232import samba
    33 samba.ensure_external_module("testtools", "testtools")
    34 samba.ensure_external_module("subunit", "subunit/python")
     33from samba.tests.subunitrun import TestProgram, SubunitOptions
    3534
    3635import samba.getopt as options
    3736
    38 from ldb import (
    39             SCOPE_BASE, SCOPE_SUBTREE, LdbError, ERR_NO_SUCH_OBJECT,
    40                 ERR_UNWILLING_TO_PERFORM, ERR_INSUFFICIENT_ACCESS_RIGHTS)
    41 from samba.ndr import ndr_pack, ndr_unpack
     37from ldb import SCOPE_BASE, SCOPE_SUBTREE
     38from samba.ndr import ndr_unpack
    4239from samba.dcerpc import security
    4340
     
    4845import samba.tests
    4946from samba.tests import delete_force
    50 from subunit.run import SubunitTestRunner
    51 import unittest
    5247
    5348parser = optparse.OptionParser("speedtest.py [options] <host>")
     
    5651parser.add_option_group(options.VersionOptions(parser))
    5752
    58 
    5953# use command line creds if available
    6054credopts = options.CredentialsOptions(parser)
    6155parser.add_option_group(credopts)
     56subunitopts = SubunitOptions(parser)
     57parser.add_option_group(subunitopts)
    6258opts, args = parser.parse_args()
    6359
     
    233229ldb = SamDB(host, credentials=creds, session_info=system_session(), lp=lp, options=ldb_options)
    234230
    235 runner = SubunitTestRunner()
    236 rc = 0
    237 if not runner.run(unittest.makeSuite(SpeedTestAddDel)).wasSuccessful():
    238     rc = 1
    239 if not runner.run(unittest.makeSuite(AclSearchSpeedTest)).wasSuccessful():
    240     rc = 1
    241 sys.exit(rc)
     231TestProgram(module=__name__, opts=subunitopts)
  • vendor/current/source4/scripting/wscript_build

    r740 r988  
    33from samba_utils import MODE_755
    44
    5 bld.INSTALL_FILES('${SBINDIR}','bin/upgradeprovision bin/samba_dnsupdate bin/samba_spnupdate',
     5sbin_files = None
     6if bld.CONFIG_SET('AD_DC_BUILD_IS_ENABLED'):
     7    sbin_files = 'bin/samba_dnsupdate bin/samba_spnupdate bin/samba_upgradedns bin/samba_kcc'
     8
     9if sbin_files:
     10    bld.INSTALL_FILES('${SBINDIR}',
     11                      sbin_files,
     12                      chmod=MODE_755, python_fixup=True, flat=True)
     13
     14if bld.CONFIG_SET('AD_DC_BUILD_IS_ENABLED'):
     15    bld.INSTALL_FILES('${BINDIR}',
     16                  'bin/samba-tool',
    617                  chmod=MODE_755, python_fixup=True, flat=True)
    7 bld.INSTALL_FILES('${BINDIR}','bin/testparm',
    8                   chmod=MODE_755, python_fixup=True, flat=True)
     18
     19bld.RECURSE('bin')
Note: See TracChangeset for help on using the changeset viewer.