def dc_watcher(self): (r1, w1) = os.pipe() pid = os.fork() if pid != 0: # Parent process return the result socket to the caller. return r1 # Load the lp context for the Domain Controller, rather than the # member server. config_file = os.environ["DC_SERVERCONFFILE"] lp_ctx = LoadParm() lp_ctx.load(config_file) # # Is the message a SamLogon authentication? def is_sam_logon(m): if m is None: return False msg = json.loads(m) return (msg["type"] == "Authentication" and msg["Authentication"]["serviceDescription"] == "SamLogon") # # Handler function for received authentication messages. def message_handler(context, msgType, src, message): # Print the message to help debugging the tests. # as it's a JSON message it does not look like a sub-unit message. print(message) self.dc_msgs.append(message) # Set up a messaging context to listen for authentication events on # the domain controller. msg_ctx = Messaging((1, ), lp_ctx=lp_ctx) msg_ctx.irpc_add_name(AUTH_EVENT_NAME) msg_handler_and_context = (message_handler, None) msg_ctx.register(msg_handler_and_context, msg_type=MSG_AUTH_LOG) # Wait for the SamLogon message. # As there could be other SamLogon's in progress we need to collect # all the SamLogons and let the caller match them to the session. self.dc_msgs = [] start_time = time.time() while (time.time() - start_time < 1): msg_ctx.loop_once(0.1) # Only interested in SamLogon messages, filter out the rest msgs = list(filter(is_sam_logon, self.dc_msgs)) if msgs: for m in msgs: m += "\n" os.write(w1, get_bytes(m)) else: os.write(w1, get_bytes("None\n")) os.close(w1) msg_ctx.deregister(msg_handler_and_context, msg_type=MSG_AUTH_LOG) msg_ctx.irpc_remove_name(AUTH_EVENT_NAME) os._exit(0)
class SambaOptions(optparse.OptionGroup): """General Samba-related command line options.""" def __init__(self, parser): from samba import fault_setup fault_setup() from samba.param import LoadParm optparse.OptionGroup.__init__(self, parser, "Samba Common Options") self.add_option("-s", "--configfile", action="callback", type=str, metavar="FILE", help="Configuration file", callback=self._load_configfile) self.add_option("-d", "--debuglevel", action="callback", type=str, metavar="DEBUGLEVEL", help="debug level", callback=self._set_debuglevel) self.add_option("--option", action="callback", type=str, metavar="OPTION", help="set smb.conf option from command line", callback=self._set_option) self.add_option("--realm", action="callback", type=str, metavar="REALM", help="set the realm name", callback=self._set_realm) self._configfile = None self._lp = LoadParm() self.realm = None def get_loadparm_path(self): """Return path to the smb.conf file specified on the command line.""" return self._configfile def _load_configfile(self, option, opt_str, arg, parser): self._configfile = arg def _set_debuglevel(self, option, opt_str, arg, parser): self._lp.set('debug level', arg) parser.values.debuglevel = arg def _set_realm(self, option, opt_str, arg, parser): self._lp.set('realm', arg) self.realm = arg def _set_option(self, option, opt_str, arg, parser): if arg.find('=') == -1: raise optparse.OptionValueError( "--option option takes a 'a=b' argument") a = arg.split('=') try: self._lp.set(a[0], a[1]) except Exception as e: raise optparse.OptionValueError( "invalid --option option value %r: %s" % (arg, e)) def get_loadparm(self): """Return loadparm object with data specified on the command line.""" if self._configfile is not None: self._lp.load(self._configfile) elif os.getenv("SMB_CONF_PATH") is not None: self._lp.load(os.getenv("SMB_CONF_PATH")) else: self._lp.load_default() return self._lp
def force_drs_replication(source_dc=None, destination_dc=None, partition_dn=None, direction="in"): if not package_installed('univention-samba4'): print( 'force_drs_replication(): skip, univention-samba4 not installed.') return if not source_dc: source_dc = get_available_s4connector_dc() if not source_dc: return 1 if not destination_dc: destination_dc = socket.gethostname() if destination_dc == source_dc: return if not partition_dn: lp = LoadParm() lp.load('/etc/samba/smb.conf') samdb = SamDB("tdb://%s" % lp.private_path("sam.ldb"), session_info=system_session(lp), lp=lp) partition_dn = str(samdb.domain_dn()) print("USING partition_dn:", partition_dn) if direction == "in": cmd = ("/usr/bin/samba-tool", "drs", "replicate", destination_dc, source_dc, partition_dn) else: cmd = ("/usr/bin/samba-tool", "drs", "replicate", source_dc, destination_dc, partition_dn) return subprocess.call(cmd)
class SambaOptions(optparse.OptionGroup): """General Samba-related command line options.""" def __init__(self, parser): from samba.param import LoadParm optparse.OptionGroup.__init__(self, parser, "Samba Common Options") self.add_option("-s", "--configfile", action="callback", type=str, metavar="FILE", help="Configuration file", callback=self._load_configfile) self.add_option("-d", "--debuglevel", action="callback", type=int, metavar="DEBUGLEVEL", help="debug level", callback=self._set_debuglevel) self.add_option("--option", action="callback", type=str, metavar="OPTION", help="set smb.conf option from command line", callback=self._set_option) self.add_option("--realm", action="callback", type=str, metavar="REALM", help="set the realm name", callback=self._set_realm) self._configfile = None self._lp = LoadParm() self.realm = None def get_loadparm_path(self): """Return path to the smb.conf file specified on the command line.""" return self._configfile def _load_configfile(self, option, opt_str, arg, parser): self._configfile = arg def _set_debuglevel(self, option, opt_str, arg, parser): if arg < 0: raise optparse.OptionValueError("invalid %s option value: %s" % (opt_str, arg)) self._lp.set('debug level', str(arg)) def _set_realm(self, option, opt_str, arg, parser): self._lp.set('realm', arg) self.realm = arg def _set_option(self, option, opt_str, arg, parser): if arg.find('=') == -1: raise optparse.OptionValueError( "--option option takes a 'a=b' argument") a = arg.split('=') try: self._lp.set(a[0], a[1]) except Exception as e: raise optparse.OptionValueError( "invalid --option option value %r: %s" % (arg, e)) def get_loadparm(self): """Return loadparm object with data specified on the command line.""" if self._configfile is not None: self._lp.load(self._configfile) elif os.getenv("SMB_CONF_PATH") is not None: self._lp.load(os.getenv("SMB_CONF_PATH")) else: self._lp.load_default() return self._lp
def _wait_for_drs_replication(ldap_filter, attrs=None, base=None, scope=ldb.SCOPE_SUBTREE, lp=None, timeout=360, delta_t=1, verbose=True, should_exist=True, controls=None): # type: (str, Union[List[str], None, str], Optional[str], int, Optional[LoadParm], int, int, bool, bool, Optional[List[str]]) -> None if not package_installed('univention-samba4'): if package_installed('univention-samba'): time.sleep(15) print('Sleeping 15 seconds as a workaround for http://forge.univention.org/bugzilla/show_bug.cgi?id=52145') elif verbose: print('wait_for_drs_replication(): skip, univention-samba4 not installed.') return if not attrs: attrs = ['dn'] elif not isinstance(attrs, list): attrs = [attrs] if not lp: lp = LoadParm() lp.load('/etc/samba/smb.conf') samdb = SamDB("tdb://%s" % lp.private_path("sam.ldb"), session_info=system_session(lp), lp=lp) if not controls: controls = ["domain_scope:0"] if base is None: ucr = config_registry.ConfigRegistry() ucr.load() base = ucr['samba4/ldap/base'] else: if len(ldap.dn.str2dn(base)[0]) > 1: if verbose: print('wait_for_drs_replication(): skip, multiple RDNs are not supported') return if not base: if verbose: print('wait_for_drs_replication(): skip, no samba domain found') return if verbose: print("Waiting for DRS replication, filter: %r, base: %r, scope: %r, should_exist: %r" % (ldap_filter, base, scope, should_exist), end=' ') t = t0 = time.time() while t < t0 + timeout: try: res = samdb.search(base=base, scope=scope, expression=ldap_filter, attrs=attrs, controls=controls) if bool(res) is bool(should_exist): if verbose: print("\nDRS replication took %d seconds" % (t - t0, )) return # res except ldb.LdbError as exc: (_num, msg) = exc.args if _num == ldb.ERR_INVALID_DN_SYNTAX: raise if _num == ldb.ERR_NO_SUCH_OBJECT and not should_exist: if verbose: print("\nDRS replication took %d seconds" % (t - t0, )) return print("Error during samdb.search: %s" % (msg, )) print('.', end=' ') time.sleep(delta_t) t = time.time() raise DRSReplicationFailed("DRS replication for filter: %r failed due to timeout after %d sec." % (ldap_filter, t - t0))
def wait_for_drs_replication(ldap_filter, attrs=None, base=None, scope=ldb.SCOPE_SUBTREE, lp=None, timeout=360, delta_t=1, verbose=True, should_exist=True, controls=None): if not package_installed('univention-samba4'): if verbose: print('wait_for_drs_replication(): skip, univention-samba4 not installed.') return if not lp: lp = LoadParm() lp.load('/etc/samba/smb.conf') if not attrs: attrs = ['dn'] elif not isinstance(attrs, list): attrs = [attrs] samdb = SamDB("tdb://%s" % lp.private_path("sam.ldb"), session_info=system_session(lp), lp=lp) if not controls: controls = ["domain_scope:0"] if base is None: base = samdb.domain_dn() else: if len(ldap.dn.str2dn(base)[0]) > 1: if verbose: print('wait_for_drs_replication(): skip, multiple RDNs are not supported') return if not base or base == 'None': if verbose: print('wait_for_drs_replication(): skip, no samba domain found') return if verbose: print("Waiting for DRS replication, filter: %r, base: %r, scope: %r, should_exist: %r" % (ldap_filter, base, scope, should_exist), end=' ') t = t0 = time.time() while t < t0 + timeout: try: res = samdb.search(base=base, scope=scope, expression=ldap_filter, attrs=attrs, controls=controls) if res and should_exist: if verbose: print("\nDRS replication took %d seconds" % (t - t0, )) return res if not res and not should_exist: if verbose: print("\nDRS replication took %d seconds" % (t - t0, )) return res except ldb.LdbError as exc: (_num, msg) = exc.args if _num == ldb.ERR_INVALID_DN_SYNTAX: raise if _num == ldb.ERR_NO_SUCH_OBJECT and not should_exist: if verbose: print("\nDRS replication took %d seconds" % (t - t0, )) return print("Error during samdb.search: %s" % (msg, )) print('.', end=' ') time.sleep(delta_t) t = time.time() raise DRSReplicationFailed("DRS replication for filter: %r failed due to timeout after %d sec." % (ldap_filter, t - t0))
def parse_gpext_conf(smb_conf): lp = LoadParm() if smb_conf is not None: lp.load(smb_conf) else: lp.load_default() ext_conf = lp.state_path('gpext.conf') parser = ConfigParser() parser.read(ext_conf) return lp, parser
def wait_for_drs_replication(ldap_filter, attrs=None, base=None, scope=ldb.SCOPE_SUBTREE, lp=None, timeout=360, delta_t=1, verbose=True): if not package_installed('univention-samba4'): if verbose: print 'wait_for_drs_replication(): skip, univention-samba4 not installed.' return if not lp: lp = LoadParm() lp.load('/etc/samba/smb.conf') if not attrs: attrs = ['dn'] elif not isinstance(attrs, list): attrs = [attrs] samdb = SamDB("tdb://%s" % lp.private_path("sam.ldb"), session_info=system_session(lp), lp=lp) controls = ["domain_scope:0"] if base is None: base = samdb.domain_dn() if not base or base == 'None': if verbose: print 'wait_for_drs_replication(): skip, no samba domain found' return if verbose: print "Waiting for DRS replication, filter: '%s'" % (ldap_filter, ), t = t0 = time.time() while t < t0 + timeout: try: res = samdb.search(base=base, scope=scope, expression=ldap_filter, attrs=attrs, controls=controls) if res: if verbose: print "\nDRS replication took %d seconds" % (t - t0, ) return res except ldb.LdbError as (_num, msg): print "Error during samdb.search: %s" % (msg, ) print '.', time.sleep(delta_t) t = time.time()
def test_vgp_access_add(self): lp = LoadParm() lp.load(os.environ['SERVERCONFFILE']) (result, out, err) = self.runsublevelcmd( "gpo", ("manage", "access", "add"), self.gpo_guid, "allow", self.test_user, lp.get('realm').lower(), "-H", "ldap://%s" % os.environ["SERVER"], "-U%s%%%s" % (os.environ["USERNAME"], os.environ["PASSWORD"])) self.assertCmdSuccess(result, out, err, 'Access add failed') (result, out, err) = self.runsublevelcmd( "gpo", ("manage", "access", "add"), self.gpo_guid, "deny", self.test_group, lp.get('realm').lower(), "-H", "ldap://%s" % os.environ["SERVER"], "-U%s%%%s" % (os.environ["USERNAME"], os.environ["PASSWORD"])) self.assertCmdSuccess(result, out, err, 'Access add failed') allow_entry = '+:%s\\%s:ALL' % (lp.get('realm').lower(), self.test_user) deny_entry = '-:%s\\%s:ALL' % (lp.get('realm').lower(), self.test_group) (result, out, err) = self.runsublevelcmd( "gpo", ("manage", "access", "list"), self.gpo_guid, "-H", "ldap://%s" % os.environ["SERVER"], "-U%s%%%s" % (os.environ["USERNAME"], os.environ["PASSWORD"])) self.assertIn(allow_entry, out, 'The test entry was not found!') self.assertIn(deny_entry, out, 'The test entry was not found!') (result, out, err) = self.runsublevelcmd( "gpo", ("manage", "access", "remove"), self.gpo_guid, "allow", self.test_user, lp.get('realm').lower(), "-H", "ldap://%s" % os.environ["SERVER"], "-U%s%%%s" % (os.environ["USERNAME"], os.environ["PASSWORD"])) self.assertCmdSuccess(result, out, err, 'Access remove failed') (result, out, err) = self.runsublevelcmd( "gpo", ("manage", "access", "remove"), self.gpo_guid, "deny", self.test_group, lp.get('realm').lower(), "-H", "ldap://%s" % os.environ["SERVER"], "-U%s%%%s" % (os.environ["USERNAME"], os.environ["PASSWORD"])) self.assertCmdSuccess(result, out, err, 'Access remove failed') (result, out, err) = self.runsublevelcmd( "gpo", ("manage", "access", "list"), self.gpo_guid, "-H", "ldap://%s" % os.environ["SERVER"], "-U%s%%%s" % (os.environ["USERNAME"], os.environ["PASSWORD"])) self.assertNotIn(allow_entry, out, 'The test entry was still found!') self.assertNotIn(deny_entry, out, 'The test entry was still found!')
def get_samba_sam_ldb_path(self): """ Returns the 'sam.ldb' path using samba conf or defaults. """ print( "\nObtaining the Samba configuration to determine Samba private path" ) smb_conf_path = getenv("SMB_CONF_PATH") SambaLP = LoadParm() if smb_conf_path: SambaLP.load(smb_conf_path) else: SambaLP.load_default() return SambaLP.private_path('sam.ldb')
def test_admx_load(self): lp = LoadParm() lp.load(os.environ['SERVERCONFFILE']) local_path = lp.get('path', 'sysvol') admx_path = os.path.join(local_path, os.environ['REALM'].lower(), 'Policies', 'PolicyDefinitions') (result, out, err) = self.runsubcmd( "gpo", "admxload", "-H", "ldap://%s" % os.environ["SERVER"], "--admx-dir=%s" % os.path.join(source_path, 'libgpo/admx'), "-U%s%%%s" % (os.environ["USERNAME"], os.environ["PASSWORD"])) self.assertCmdSuccess(result, out, err, 'Filling PolicyDefinitions failed') self.assertTrue(os.path.exists(admx_path), 'PolicyDefinitions was not created') self.assertTrue(os.path.exists(os.path.join(admx_path, 'samba.admx')), 'Filling PolicyDefinitions failed') shutil.rmtree(admx_path)
def test_join_member(self): """Run a domain member join, and check that dns is updated""" smb_conf = os.environ["SERVERCONFFILE"] zone = os.environ["REALM"].lower() lp = LoadParm() lp.load(smb_conf) dnsname = netcmd_dnsname(lp) # Fetch the existing dns A records (result, out, err) = self.runsubcmd("dns", "query", os.environ["DC_SERVER"], zone, dnsname, 'A', "-s", smb_conf, "-U%s%%%s" % (os.environ["DC_USERNAME"], os.environ["DC_PASSWORD"])) self.assertCmdSuccess(result, out, err, 'Failed to find the record') existing_records = re.findall('A:\s+(\d+\.\d+\.\d+\.\d+)\s', out) # Remove the existing records for record in existing_records: (result, out, err) = self.runsubcmd("dns", "delete", os.environ["DC_SERVER"], zone, dnsname, 'A', record, "-s", smb_conf, "-U%s%%%s" % (os.environ["DC_USERNAME"], os.environ["DC_PASSWORD"])) self.assertCmdSuccess(result, out, err, 'Failed to remove record') # Perform the s3 member join (net ads join) (result, out, err) = self.runsubcmd("domain", "join", os.environ["REALM"], "member", "-s", smb_conf, "-U%s%%%s" % (os.environ["DC_USERNAME"], os.environ["DC_PASSWORD"])) self.assertCmdSuccess(result, out, err, 'Failed to join member') # Ensure the dns A record was created (result, out, err) = self.runsubcmd("dns", "query", os.environ["DC_SERVER"], zone, dnsname, 'A', "-s", smb_conf, "-U%s%%%s" % (os.environ["DC_USERNAME"], os.environ["DC_PASSWORD"])) self.assertCmdSuccess(result, out, err, 'Failed to find dns host records for %s' % dnsname)
def parametros(fichero=False): """ Intento ser un poco cuidadoso con la forma en que obtenemos la configuración """ try: lp = LoadParm() lp.load_default() if fichero is False else lp.load(fichero) return lp except RuntimeError as e: log.warning(e.message) raise ConfiguracionException(e)
def purge_computer_with_DC_objects(ucr, binddn, bindpw, computername): lp = LoadParm() lp.load('/etc/samba/smb.conf') samdb = SamDB(os.path.join(SAMBA_PRIVATE_DIR, "sam.ldb"), session_info=system_session(lp), lp=lp) backlink_attribute_list = [ "serverReferenceBL", "frsComputerReferenceBL", "msDFSR-ComputerReferenceBL" ] msgs = samdb.search( base=ucr["samba4/ldap/base"], scope=samba.ldb.SCOPE_SUBTREE, expression="(&(objectClass=computer)(sAMAccountName=%s$))" % computername, attrs=backlink_attribute_list) if not msgs: print "Samba 4 computer account '%s' not found." % (computername, ) sys.exit(1) answer = raw_input("Really remove %s from Samba 4? [y/N]: " % computername) if not answer.lower() in ('y', 'yes'): print "Ok, stopping as requested.\n" sys.exit(2) computer_obj = msgs[0] # Confirmation check answer = raw_input("If you are really sure type YES and hit enter: ") if not answer == 'YES': print "The answer was not 'YES', confirmation failed.\n" sys.exit(1) else: print "Ok, continuing as requested.\n" # Determine the NTDS_objectGUID NTDS_objectGUID = None if "serverReferenceBL" in computer_obj: msgs = samdb.search(base=computer_obj["serverReferenceBL"][0], scope=samba.ldb.SCOPE_SUBTREE, expression="(CN=NTDS Settings)", attrs=["objectGUID"]) if msgs and "objectGUID" in msgs[0]: NTDS_objectGUID = str( ndr_unpack(misc.GUID, msgs[0]["objectGUID"][0])) # Determine the Domain_GUID msgs = samdb.search(base=ucr["samba4/ldap/base"], scope=samba.ldb.SCOPE_BASE, attrs=["objectGUID"]) if not msgs: print "Samba 4 Domain_GUID for base dn '%s' not found." % ( ucr["samba4/ldap/base"], ) sys.exit(1) Domain_GUID = str(ndr_unpack(misc.GUID, msgs[0]["objectGUID"][0])) # Build current site list msgs = samdb.search(base="CN=Configuration,%s" % ucr["samba4/ldap/base"], scope=samba.ldb.SCOPE_SUBTREE, expression="(objectClass=site)", attrs=["cn"]) site_list = [obj["cn"][0] for obj in msgs] # Remove Samba 4 DNS records purge_s4_dns_records(ucr, binddn, bindpw, computername, NTDS_objectGUID, Domain_GUID, site_list) # remove objects from Samba 4 SAM database for backlink_attribute in backlink_attribute_list: if backlink_attribute in computer_obj: backlink_object = computer_obj[backlink_attribute][0] try: print "Removing %s from SAM database." % (backlink_object, ) samdb.delete(backlink_object, ["tree_delete:0"]) except: print >> sys.stderr, "Removal of Samba 4 %s objects %s from Samba 4 SAM database failed." % ( backlink_attribute, backlink_object, ) print traceback.format_exc() # Now delete the Samba 4 computer account and sub-objects # Cannot use tree_delete on isCriticalSystemObject, perform recursive delete like ldbdel code does it: msgs = samdb.search(base=computer_obj.dn, scope=samba.ldb.SCOPE_SUBTREE, attrs=["dn"]) obj_dn_list = [obj.dn for obj in msgs] obj_dn_list.sort(key=len) obj_dn_list.reverse() for obj_dn in obj_dn_list: try: print "Removing %s from SAM database." % (obj_dn, ) samdb.delete(obj_dn) except: print >> sys.stderr, "Removal of Samba 4 computer account object %s from Samba 4 SAM database failed." % ( obj_dn, ) print >> sys.stderr, traceback.format_exc() answer = raw_input("Really remove %s from UDM as well? [y/N]: " % computername) if not answer.lower() in ('y', 'yes'): print "Ok, stopping as requested.\n" sys.exit(2) # Finally, for consistency remove S4 computer object from UDM purge_udm_computer(ucr, binddn, bindpw, computername)
def test_vgp_access_list(self): lp = LoadParm() lp.load(os.environ['SERVERCONFFILE']) local_path = lp.get('path', 'sysvol') vgp_xml = os.path.join( local_path, lp.get('realm').lower(), 'Policies', self.gpo_guid, 'Machine/VGP/VTLA/VAS' 'HostAccessControl/Allow/manifest.xml') stage = etree.Element('vgppolicy') policysetting = etree.SubElement(stage, 'policysetting') pv = etree.SubElement(policysetting, 'version') pv.text = '1' name = etree.SubElement(policysetting, 'name') name.text = 'Host Access Control' description = etree.SubElement(policysetting, 'description') description.text = 'Represents host access control data (pam_access)' apply_mode = etree.SubElement(policysetting, 'apply_mode') apply_mode.text = 'merge' data = etree.SubElement(policysetting, 'data') listelement = etree.SubElement(data, 'listelement') etype = etree.SubElement(listelement, 'type') etype.text = 'USER' entry = etree.SubElement(listelement, 'entry') entry.text = 'goodguy@%s' % lp.get('realm').lower() adobject = etree.SubElement(listelement, 'adobject') name = etree.SubElement(adobject, 'name') name.text = 'goodguy' domain = etree.SubElement(adobject, 'domain') domain.text = lp.get('realm').lower() etype = etree.SubElement(adobject, 'type') etype.text = 'user' groupattr = etree.SubElement(data, 'groupattr') groupattr.text = 'samAccountName' listelement = etree.SubElement(data, 'listelement') etype = etree.SubElement(listelement, 'type') etype.text = 'GROUP' entry = etree.SubElement(listelement, 'entry') entry.text = '%s\\goodguys' % lp.get('realm').lower() adobject = etree.SubElement(listelement, 'adobject') name = etree.SubElement(adobject, 'name') name.text = 'goodguys' domain = etree.SubElement(adobject, 'domain') domain.text = lp.get('realm').lower() etype = etree.SubElement(adobject, 'type') etype.text = 'group' ret = stage_file(vgp_xml, etree.tostring(stage, 'utf-8')) self.assertTrue(ret, 'Could not create the target %s' % vgp_xml) uentry = '+:%s\\goodguy:ALL' % domain.text gentry = '+:%s\\goodguys:ALL' % domain.text (result, out, err) = self.runsublevelcmd( "gpo", ("manage", "access", "list"), self.gpo_guid, "-H", "ldap://%s" % os.environ["SERVER"], "-U%s%%%s" % (os.environ["USERNAME"], os.environ["PASSWORD"])) self.assertIn(uentry, out, 'The test entry was not found!') self.assertIn(gentry, out, 'The test entry was not found!') # Unstage the manifest.xml file unstage_file(vgp_xml)
action='store_true') credopts = optparse.OptionGroup(parser, 'Credentials Options') credopts.add_option('--password', dest='password', help='Password') credopts.add_option('-U', '--username', dest='username', help='Username') credopts.add_option('--krb5-ccache', dest='krb5_ccache', help='Kerberos Credentials cache') parser.add_option_group(credopts) # Set the options and the arguments (opts, args) = parser.parse_args() # Set the loadparm context lp = LoadParm() if os.getenv("SMB_CONF_PATH") is not None: lp.load(os.getenv("SMB_CONF_PATH")) else: lp.load_default() # Initialize the session creds = Credentials() if opts.username and opts.password: creds.set_username(opts.username) creds.set_password(opts.password) elif opts.krb5_ccache: creds.set_named_ccache(opts.krb5_ccache) creds.guess(lp) from dialogs import GPMC, GPME from yast import UISequencer s = UISequencer(lp, creds)
parser.add_argument("--check", action="store_true", help="Check registered LDB modules", default=[]) parser.add_argument("--ignore-exists", action="store_true", help="Don't add LDB modules already registered") parser.add_argument("--dry-run", action="store_true", help="Dry run") opts = parser.parse_args() if not (opts.prepend or opts.append or opts.remove or opts.check): parser.print_help() sys.exit(1) lp = LoadParm() lp.load('/etc/samba/smb.conf') ldb_object = Ldb(opts.ldburl, lp=lp, session_info=system_session()) msg = ldb_object.search(base="@MODULES", scope=ldb.SCOPE_BASE, attrs=['@LIST']) assert len(msg) == 1 assert "@LIST" in msg[0] if opts.verbose: print("Current @LIST:", msg[0]["@LIST"]) if opts.check and not opts.dry_run: sys.exit(0) if len(msg[0]["@LIST"]) == 1:
class SambaOptions(optparse.OptionGroup): """General Samba-related command line options.""" def __init__(self, parser): from samba.param import LoadParm optparse.OptionGroup.__init__(self, parser, "Samba Common Options") self.add_option("-s", "--configfile", action="callback", type=str, metavar="FILE", help="Configuration file", callback=self._load_configfile) self.add_option("-d", "--debuglevel", action="callback", type=int, metavar="DEBUGLEVEL", help="debug level", callback=self._set_debuglevel) self.add_option("--option", action="callback", type=str, metavar="OPTION", help="set smb.conf option from command line", callback=self._set_option) self.add_option("--realm", action="callback", type=str, metavar="REALM", help="set the realm name", callback=self._set_realm) self._configfile = None self._lp = LoadParm() def get_loadparm_path(self): """Return the path to the smb.conf file specified on the command line. """ return self._configfile def _load_configfile(self, option, opt_str, arg, parser): self._configfile = arg def _set_debuglevel(self, option, opt_str, arg, parser): self._lp.set('debug level', str(arg)) def _set_realm(self, option, opt_str, arg, parser): self._lp.set('realm', arg) def _set_option(self, option, opt_str, arg, parser): if arg.find('=') == -1: print("--option takes a 'a=b' argument") sys.exit(1) a = arg.split('=') self._lp.set(a[0], a[1]) def get_loadparm(self): """Return a loadparm object with data specified on the command line. """ if self._configfile is not None: self._lp.load(self._configfile) elif os.getenv("SMB_CONF_PATH") is not None: self._lp.load(os.getenv("SMB_CONF_PATH")) else: self._lp.load_default() return self._lp def get_hostconfig(self): return Hostconfig(self.get_loadparm())
import ldb from samba.ndr import ndr_pack, ndr_unpack from samba.dcerpc import security from samba.idmap import IDmapDB from samba.auth import system_session from samba.param import LoadParm name='samba4-idmap' description='Update local IDmap entries' filter='(&(|(objectClass=sambaSamAccount)(objectClass=sambaGroupMapping))(sambaSID=*))' attributes=['sambaSID', 'univentionSamba4SID', 'uidNumber', 'gidNumber'] modrdn='1' ### Globals lp = LoadParm() lp.load('/etc/samba/smb.conf') sidAttribute='sambaSID' if listener.configRegistry.is_false('connector/s4/mapping/sid', False): sidAttribute='univentionSamba4SID' def open_idmap(): global lp listener.setuid(0) try: idmap = IDmapDB('/var/lib/samba/private/idmap.ldb', session_info=system_session(), lp=lp) except ldb.LdbError: univention.debug.debug(univention.debug.LISTENER, univention.debug.ERROR, "%s: /var/lib/samba/private/idmap.ldb could not be opened" % name ) raise