def get_neighbours(self, info_type): req1 = drsuapi.DsReplicaGetInfoRequest1() req1.info_type = info_type try: (info_type, info) = self.drsuapi.DsReplicaGetInfo(self.drsuapi_handle, 1, req1) except Exception as e: raise CommandError( "DsReplicaGetInfo of type %u failed" % info_type, e) reps = [self.parse_neighbour(n) for n in info.array] return reps
def run(self, credopts=None, sambaopts=None, versionopts=None): lp = sambaopts.get_loadparm() path = lp.private_path("secrets.ldb") creds = credopts.get_credentials(lp) creds.set_kerberos_state(DONT_USE_KERBEROS) logger = self.get_logger() netlogon = lp.get("path", "netlogon") sysvol = lp.get("path", "sysvol") try: samdb = SamDB(session_info=system_session(), lp=lp) except Exception, e: raise CommandError("Unable to open samdb:", e)
def run(self, old_ou_dn, new_ou_dn, credopts=None, sambaopts=None, versionopts=None, H=None): lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp, fallback_machine=True) samdb = SamDB(url=H, session_info=system_session(), credentials=creds, lp=lp) domain_dn = ldb.Dn(samdb, samdb.domain_dn()) try: full_old_ou_dn = samdb.normalize_dn_in_domain(old_ou_dn) except Exception, e: raise CommandError('Invalid old_ou_dn "%s": %s' % (old_ou_dn, e.message))
def drsuapi_ReplicaInfo(self, info_type): '''call a DsReplicaInfo''' req1 = drsuapi.DsReplicaGetInfoRequest1() req1.info_type = info_type try: (info_type, info) = self.drsuapi.DsReplicaGetInfo(self.drsuapi_handle, 1, req1) except Exception as e: raise CommandError( "DsReplicaGetInfo of type %u failed" % info_type, e) return (info_type, info)
def run(self, H=None, partition=None, json=False, maximum=False, median=False, full=False, sambaopts=None, credopts=None, versionopts=None, quiet=False, verbose=False): lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp, fallback_machine=True) local_kcc, dsas = get_kcc_and_dsas(H, lp, creds) samdb = local_kcc.samdb short_partitions, _ = get_partition_maps(samdb) if partition: if partition in short_partitions: part_dn = short_partitions[partition] # narrow down to specified partition only short_partitions = {partition: part_dn} else: raise CommandError("unknown partition %s" % partition) filters = [] if maximum: filters.append('maximum') if median: filters.append('median') partitions_distances = {} partitions_summaries = {} for part_name, part_dn in short_partitions.items(): utdv_edges = get_utdv_edges(local_kcc, dsas, part_dn, lp, creds) distances = get_utdv_distances(utdv_edges, dsas) summary = get_utdv_summary(distances, filters=filters) partitions_distances[part_name] = distances partitions_summaries[part_name] = summary if full: # always print json format output = self.format_as_json(partitions_distances) else: if json: output = self.format_as_json(partitions_summaries) else: output = self.format_as_text(partitions_summaries) print(output, file=self.outf)
class cmd_ntacl_get(Command): """Get ACLs of a file.""" synopsis = "%prog <file> [options]" takes_optiongroups = { "sambaopts": options.SambaOptions, "credopts": options.CredentialsOptions, "versionopts": options.VersionOptions, } takes_options = [ Option("--as-sddl", help="Output ACL in the SDDL format", action="store_true"), Option("--xattr-backend", type="choice", help="xattr backend type (native fs or tdb)", choices=["native","tdb"]), Option("--eadb-file", help="Name of the tdb file where attributes are stored", type="string"), Option("--use-ntvfs", help="Get the ACLs directly from the TDB or xattr used with the ntvfs file server", action="store_true"), Option("--use-s3fs", help="Get the ACLs for use via the VFS layer used by the default s3fs file server", action="store_true") ] takes_args = ["file"] def run(self, file, use_ntvfs=False, use_s3fs=False, as_sddl=False, xattr_backend=None, eadb_file=None, credopts=None, sambaopts=None, versionopts=None): lp = sambaopts.get_loadparm() try: samdb = SamDB(session_info=system_session(), lp=lp) except Exception, e: raise CommandError("Unable to open samdb:", e) if not use_ntvfs and not use_s3fs: use_ntvfs = "smb" in lp.get("server services") elif use_s3fs: use_ntvfs = False s3conf = s3param.get_context() s3conf.load(lp.configfile) # ensure we are using the right samba_dsdb passdb backend, no matter what s3conf.set("passdb backend", "samba_dsdb:%s" % samdb.url) acl = getntacl(lp, file, xattr_backend, eadb_file, direct_db_access=use_ntvfs) if as_sddl: try: domain_sid = security.dom_sid(samdb.domain_sid) except: raise CommandError("Unable to read domain SID from configuration files") self.outf.write(acl.as_sddl(domain_sid)+"\n") else: self.outf.write(ndr_print(acl))
def run(self, account, sambaopts=None, credopts=None, versionopts=None, server=None): if server is None: raise Exception("You must supply a server") lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp, fallback_machine=True) # connect to the remote and local SAMs samdb = SamDB(url="ldap://%s" % server, session_info=system_session(), credentials=creds, lp=lp) local_samdb = SamDB(url=None, session_info=system_session(), credentials=creds, lp=lp) # work out the source and destination GUIDs dc_ntds_dn = samdb.get_dsServiceName() res = samdb.search(base=dc_ntds_dn, scope=ldb.SCOPE_BASE, attrs=["invocationId"]) source_dsa_invocation_id = misc.GUID( local_samdb.schema_format_value("objectGUID", res[0]["invocationId"][0])) dn = self.get_dn(samdb, account) self.outf.write("Replicating DN %s\n" % dn) destination_dsa_guid = misc.GUID(local_samdb.get_ntds_GUID()) local_samdb.transaction_start() repl = drs_Replicate("ncacn_ip_tcp:%s[seal,print]" % server, lp, creds, local_samdb, destination_dsa_guid) try: repl.replicate(dn, source_dsa_invocation_id, destination_dsa_guid, exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True) except Exception, e: local_samdb.transaction_cancel() raise CommandError("Error replicating DN %s" % dn, e)
def run(self, server, zone, name, rtype, olddata, newdata, sambaopts=None, credopts=None, versionopts=None): if rtype.upper() not in ('A','AAAA','PTR','CNAME','NS','MX','SOA','SRV','TXT'): raise CommandError('Updating record of type %s is not supported' % rtype) record_type = dns_type_flag(rtype) rec = data_to_dns_record(record_type, newdata) self.lp = sambaopts.get_loadparm() self.creds = credopts.get_credentials(self.lp) dns_conn = dns_connect(server, self.lp, self.creds) rec_match = dns_record_match(dns_conn, server, zone, name, record_type, olddata) if not rec_match: raise CommandError('Record does not exist') # Copy properties from existing record to new record rec.dwFlags = rec_match.dwFlags rec.dwSerial = rec_match.dwSerial rec.dwTtlSeconds = rec_match.dwTtlSeconds rec.dwTimeStamp = rec_match.dwTimeStamp add_rec_buf = dnsserver.DNS_RPC_RECORD_BUF() add_rec_buf.rec = rec del_rec_buf = dnsserver.DNS_RPC_RECORD_BUF() del_rec_buf.rec = rec_match dns_conn.DnssrvUpdateRecord2(dnsserver.DNS_CLIENT_VERSION_LONGHORN, 0, server, zone, name, add_rec_buf, del_rec_buf) self.outf.write('Record updated successfully\n')
def run(self, old_ou_dn, new_ou_dn, credopts=None, sambaopts=None, versionopts=None, H=None): lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp, fallback_machine=True) samdb = SamDB(url=H, session_info=system_session(), credentials=creds, lp=lp) domain_dn = ldb.Dn(samdb, samdb.domain_dn()) try: full_old_ou_dn = samdb.normalize_dn_in_domain(old_ou_dn) except Exception as e: raise CommandError('Invalid old_ou_dn "%s": %s' % (old_ou_dn, e)) try: full_new_ou_dn = samdb.normalize_dn_in_domain(new_ou_dn) except Exception as e: raise CommandError('Invalid new_ou_dn "%s": %s' % (new_ou_dn, e)) try: res = samdb.search(base=full_old_ou_dn, expression="(objectclass=organizationalUnit)", scope=ldb.SCOPE_BASE, attrs=[]) if len(res) == 0: self.outf.write('Unable to find ou "%s"\n' % old_ou_dn) return samdb.rename(full_old_ou_dn, full_new_ou_dn) except Exception as e: raise CommandError('Failed to rename ou "%s"' % full_old_ou_dn, e) self.outf.write('Renamed ou "%s" to "%s"\n' % (full_old_ou_dn, full_new_ou_dn))
def run(self, accountname, onoff, credopts=None, sambaopts=None, versionopts=None): on = False if onoff == "on": on = True elif onoff == "off": on = False else: raise CommandError( "invalid argument: '%s' (choose from 'on', 'off')" % onoff) lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp) paths = provision.provision_paths_from_lp(lp, lp.get("realm")) sam = SamDB(paths.samdb, session_info=system_session(), credentials=creds, lp=lp) # TODO once I understand how, use the domain info to naildown # to the correct domain (cleanedaccount, realm, domain) = _get_user_realm_domain(accountname) search_filter = "sAMAccountName=%s" % ldb.binary_encode(cleanedaccount) flag = dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION try: sam.toggle_userAccountFlags( search_filter, flag, flags_str="Trusted-to-Authenticate-for-Delegation", on=on, strict=True) except Exception, err: raise CommandError(err)
def run(self, DC=None, dsa_option=None, sambaopts=None, credopts=None, versionopts=None): self.lp = sambaopts.get_loadparm() if DC is None: DC = common.netcmd_dnsname(self.lp) self.server = DC self.creds = credopts.get_credentials(self.lp, fallback_machine=True) samdb_connect(self) ntds_dn = self.samdb.get_dsServiceName() res = self.samdb.search(base=ntds_dn, scope=ldb.SCOPE_BASE, attrs=["options"]) dsa_opts = int(res[0]["options"][0]) # print out current DSA options cur_opts = [x for x in self.option_map if self.option_map[x] & dsa_opts] self.message("Current DSA options: " + ", ".join(cur_opts)) # modify options if dsa_option: if dsa_option[:1] not in ("+", "-"): raise CommandError("Unknown option %s" % dsa_option) flag = dsa_option[1:] if flag not in self.option_map.keys(): raise CommandError("Unknown option %s" % dsa_option) if dsa_option[:1] == "+": dsa_opts |= self.option_map[flag] else: dsa_opts &= ~self.option_map[flag] #save new options m = ldb.Message() m.dn = ldb.Dn(self.samdb, ntds_dn) m["options"]= ldb.MessageElement(str(dsa_opts), ldb.FLAG_MOD_REPLACE, "options") self.samdb.modify(m) # print out new DSA options cur_opts = [x for x in self.option_map if self.option_map[x] & dsa_opts] self.message("New DSA options: " + ", ".join(cur_opts))
def run(self, groupname, new_parent_dn, credopts=None, sambaopts=None, versionopts=None, H=None): lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp, fallback_machine=True) samdb = SamDB(url=H, session_info=system_session(), credentials=creds, lp=lp) domain_dn = ldb.Dn(samdb, samdb.domain_dn()) filter = ("(&(sAMAccountName=%s)(objectClass=group))" % groupname) try: res = samdb.search(base=domain_dn, expression=filter, scope=ldb.SCOPE_SUBTREE) group_dn = res[0].dn except IndexError: raise CommandError('Unable to find group "%s"' % (groupname)) try: full_new_parent_dn = samdb.normalize_dn_in_domain(new_parent_dn) except Exception, e: raise CommandError('Invalid new_parent_dn "%s": %s' % (new_parent_dn, e.message))
def run(self, groupname, listofmembers, credopts=None, sambaopts=None, versionopts=None, H=None): lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp, fallback_machine=True) try: samdb = SamDB(url=H, session_info=system_session(), credentials=creds, lp=lp) samdb.add_remove_group_members(groupname, listofmembers.split(","), add_members_operation=False) except Exception, e: # FIXME: Catch more specific exception raise CommandError('Failed to remove members "%s" from group "%s"' % (listofmembers, groupname), e)
def run(self, domain, sambaopts=None, credopts=None, versionopts=None, server=None, targetdir=None, quiet=False, verbose=False, include_secrets=False): lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp) logger = self.get_logger(verbose=verbose, quiet=quiet) if targetdir is None: raise CommandError("--targetdir option must be specified") join_clone(logger=logger, server=server, creds=creds, lp=lp, domain=domain, dns_backend='SAMBA_INTERNAL', targetdir=targetdir, include_secrets=include_secrets)
def run(self, secret, sambaopts=None, credopts=None, versionopts=None): lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp, fallback_machine=True) url = lp.get("secrets database") secretsdb = Ldb(url=url, session_info=system_session(), credentials=creds, lp=lp) result = secretsdb.search(attrs=["secret"], expression="(&(objectclass=primaryDomain)(samaccountname=%s))" % secret) if len(result) != 1: raise CommandError("search returned %d records, expected 1" % len(result)) self.outf.write("%s\n" % result[0]["secret"])
def run(self, domain, role=None, sambaopts=None, credopts=None, versionopts=None, server=None, site=None, targetdir=None): lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp) net = Net(creds, lp, server=credopts.ipaddress) if site is None: site = "Default-First-Site-Name" netbios_name = lp.get("netbios name") if not role is None: role = role.upper() if role is None or role == "MEMBER": (join_password, sid, domain_name) = net.join_member(domain, netbios_name, LIBNET_JOIN_AUTOMATIC) self.outf.write("Joined domain %s (%s)\n" % (domain_name, sid)) return elif role == "DC": join_DC(server=server, creds=creds, lp=lp, domain=domain, site=site, netbios_name=netbios_name, targetdir=targetdir) return elif role == "RODC": join_RODC(server=server, creds=creds, lp=lp, domain=domain, site=site, netbios_name=netbios_name, targetdir=targetdir) return else: raise CommandError( "Invalid role %s (possible values: MEMBER, BDC, RODC)" % role)
def run(self, username, H=None, sambaopts=None, credopts=None, versionopts=None, server=None): self.url = H self.lp = sambaopts.get_loadparm() self.creds = credopts.get_credentials(self.lp, fallback_machine=True) samdb_connect(self) try: user_dn = self.samdb.search(expression='(&(samAccountName=%s)(objectclass=User))' % username)[0].dn except Exception, e: raise CommandError("Failed to find user %s" % username, e)
def run(self, ou_dn, credopts=None, sambaopts=None, versionopts=None, H=None, full_dn=False, recursive=False): lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp, fallback_machine=True) samdb = SamDB(url=H, session_info=system_session(), credentials=creds, lp=lp) domain_dn = ldb.Dn(samdb, samdb.domain_dn()) try: full_ou_dn = samdb.normalize_dn_in_domain(ou_dn) except Exception as e: raise CommandError('Invalid ou_dn "%s": %s' % (ou_dn, e)) minchilds = 0 scope = ldb.SCOPE_ONELEVEL if recursive: minchilds = 1 scope = ldb.SCOPE_SUBTREE try: childs = samdb.search(base=full_ou_dn, expression="(objectclass=*)", scope=scope, attrs=[]) if len(childs) <= minchilds: self.outf.write('ou "%s" is empty\n' % ou_dn) return for child in sorted(childs, key=attrgetter('dn')): if child.dn == full_ou_dn: continue if not full_dn: child.dn.remove_base_components(len(domain_dn)) self.outf.write("%s\n" % child.dn) except Exception as e: raise CommandError('Failed to list contents of ou "%s"' % full_ou_dn, e)
def run(self, ou_dn, credopts=None, sambaopts=None, versionopts=None, H=None, force_subtree_delete=False): lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp, fallback_machine=True) samdb = SamDB(url=H, session_info=system_session(), credentials=creds, lp=lp) domain_dn = ldb.Dn(samdb, samdb.domain_dn()) try: full_ou_dn = samdb.normalize_dn_in_domain(ou_dn) except Exception as e: raise CommandError('Invalid ou_dn "%s": %s' % (ou_dn, e.message)) controls = [] if force_subtree_delete: controls = ["tree_delete:1"] try: res = samdb.search(base=full_ou_dn, expression="(objectclass=organizationalUnit)", scope=ldb.SCOPE_BASE, attrs=[]) if len(res) == 0: self.outf.write('Unable to find ou "%s"\n' % ou_dn) return samdb.delete(full_ou_dn, controls) except Exception as e: raise CommandError('Failed to delete ou "%s"' % full_ou_dn, e) self.outf.write('Deleted ou "%s"\n' % full_ou_dn)
def run(self, car, action, objectdn, trusteedn, sddl, H=None, credopts=None, sambaopts=None, versionopts=None): lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp) if sddl is None and (car is None or action is None or objectdn is None or trusteedn is None): return self.usage() samdb = SamDB(url=H, session_info=system_session(), credentials=creds, lp=lp) cars = { 'change-rid': GUID_DRS_CHANGE_RID_MASTER, 'change-pdc': GUID_DRS_CHANGE_PDC, 'change-infrastructure': GUID_DRS_CHANGE_INFR_MASTER, 'change-schema': GUID_DRS_CHANGE_SCHEMA_MASTER, 'change-naming': GUID_DRS_CHANGE_DOMAIN_MASTER, 'allocate_rids': GUID_DRS_ALLOCATE_RIDS, 'get-changes': GUID_DRS_GET_CHANGES, 'get-changes-all': GUID_DRS_GET_ALL_CHANGES, 'get-changes-filtered': GUID_DRS_GET_FILTERED_ATTRIBUTES, 'topology-manage': GUID_DRS_MANAGE_TOPOLOGY, 'topology-monitor': GUID_DRS_MONITOR_TOPOLOGY, 'repl-sync': GUID_DRS_REPL_SYNCRONIZE, 'ro-repl-secret-sync': GUID_DRS_RO_REPL_SECRET_SYNC, } sid = self.find_trustee_sid(samdb, trusteedn) if sddl: new_ace = sddl elif action == "allow": new_ace = "(OA;;CR;%s;;%s)" % (cars[car], str(sid)) elif action == "deny": new_ace = "(OD;;CR;%s;;%s)" % (cars[car], str(sid)) else: raise CommandError("Wrong argument '%s'!" % action) self.print_new_acl(samdb, objectdn) self.add_ace(samdb, objectdn, new_ace) self.print_new_acl(samdb, objectdn)
def run(self, groupname, credopts=None, sambaopts=None, versionopts=None, H=None): lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp, fallback_machine=True) try: samdb = SamDB(url=H, session_info=system_session(), credentials=creds, lp=lp) search_filter = "(&(objectClass=group)(samaccountname=%s))" % groupname res = samdb.search(samdb.domain_dn(), scope=ldb.SCOPE_SUBTREE, expression=(search_filter), attrs=["objectSid"]) if (len(res) != 1): return group_dn = res[0].get('dn', idx=0) object_sid = res[0].get('objectSid', idx=0) object_sid = ndr_unpack(security.dom_sid, object_sid) (group_dom_sid, rid) = object_sid.split() search_filter = "(|(primaryGroupID=%s)(memberOf=%s))" % (rid, group_dn) res = samdb.search(samdb.domain_dn(), scope=ldb.SCOPE_SUBTREE, expression=(search_filter), attrs=["samAccountName", "cn"]) if (len(res) == 0): return for msg in res: member_name = msg.get("samAccountName", idx=0) if member_name is None: member_name = msg.get("cn", idx=0) self.outf.write("%s\n" % member_name) except Exception as e: raise CommandError( 'Failed to list members of "%s" group ' % groupname, e)
def run(self, fullcontactname=None, sambaopts=None, credopts=None, versionopts=None, H=None, ou=None, surname=None, given_name=None, initials=None, display_name=None, job_title=None, department=None, company=None, description=None, mail_address=None, internet_address=None, telephone_number=None, mobile_number=None, physical_delivery_office=None): lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp) try: samdb = SamDB(url=H, session_info=system_session(), credentials=creds, lp=lp) ret_name = samdb.newcontact( fullcontactname=fullcontactname, ou=ou, surname=surname, givenname=given_name, initials=initials, displayname=display_name, jobtitle=job_title, department=department, company=company, description=description, mailaddress=mail_address, internetaddress=internet_address, telephonenumber=telephone_number, mobilenumber=mobile_number, physicaldeliveryoffice=physical_delivery_office) except Exception as e: raise CommandError("Failed to create contact", e) self.outf.write("Contact '%s' created successfully\n" % ret_name)
class cmd_move(Command): """Move an organizational unit. The name of the organizational units can be specified as a full DN or without the domainDN component. Examples: samba-tool ou move 'OU=OrgUnit,DC=samdom,DC=example,DC=com' \ 'OU=NewParentOfOrgUnit,DC=samdom,DC=example,DC=com' samba-tool ou rename 'OU=OrgUnit' 'OU=NewParentOfOrgUnit' The examples show how an administrator would move an ou 'OrgUnit' into the ou 'NewParentOfOrgUnit'. The ou 'OrgUnit' would become a child of the 'NewParentOfOrgUnit' ou. The new DN would be 'OU=OrgUnit,OU=NewParentOfOrgUnit,DC=samdom,DC=example,DC=com' """ synopsis = "%prog <old_ou_dn> <new_parent_dn> [options]" takes_options = [ Option("-H", "--URL", help="LDB URL for database or target server", type=str, metavar="URL", dest="H"), ] takes_args = ["old_ou_dn", "new_parent_dn"] takes_optiongroups = { "sambaopts": options.SambaOptions, "credopts": options.CredentialsOptions, "versionopts": options.VersionOptions, } def run(self, old_ou_dn, new_parent_dn, credopts=None, sambaopts=None, versionopts=None, H=None): lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp, fallback_machine=True) samdb = SamDB(url=H, session_info=system_session(), credentials=creds, lp=lp) domain_dn = ldb.Dn(samdb, samdb.domain_dn()) try: full_old_ou_dn = samdb.normalize_dn_in_domain(old_ou_dn) except Exception, e: raise CommandError('Invalid old_ou_dn "%s": %s' % (old_ou_dn, e.message)) try: full_new_parent_dn = samdb.normalize_dn_in_domain(new_parent_dn) except Exception, e: raise CommandError('Invalid new_parent_dn "%s": %s' % (new_parent_dn, e.message))
def run(self, server, zone, name, rtype, data, sambaopts=None, credopts=None, versionopts=None): if rtype.upper() not in ('A', 'AAAA', 'PTR', 'CNAME', 'NS', 'MX', 'SRV', 'TXT'): raise CommandError('Deleting record of type %s is not supported' % rtype) record_type = dns_type_flag(rtype) rec = data_to_dns_record(record_type, data) self.lp = sambaopts.get_loadparm() self.creds = credopts.get_credentials(self.lp) dns_conn = dns_connect(server, self.lp, self.creds) del_rec_buf = dnsserver.DNS_RPC_RECORD_BUF() del_rec_buf.rec = rec try: dns_conn.DnssrvUpdateRecord2(dnsserver.DNS_CLIENT_VERSION_LONGHORN, 0, server, zone, name, None, del_rec_buf) except WERRORError as e: if e.args[0] == werror.WERR_DNS_ERROR_NAME_DOES_NOT_EXIST: raise CommandError( 'Zone does not exist; record could not be deleted.') raise e self.outf.write('Record deleted successfully\n')
def run(self, groupname, credopts=None, sambaopts=None, versionopts=None, H=None, groupou=None, group_scope=None, group_type=None, description=None, mail_address=None, notes=None, gid_number=None, nis_domain=None): if (group_type or "Security") == "Security": gtype = security_group.get(group_scope, GTYPE_SECURITY_GLOBAL_GROUP) else: gtype = distribution_group.get(group_scope, GTYPE_DISTRIBUTION_GLOBAL_GROUP) if (gid_number is None and nis_domain is not None) or (gid_number is not None and nis_domain is None): raise CommandError('Both --gid-number and --nis-domain have to be set for a RFC2307-enabled group. Operation cancelled.') lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp, fallback_machine=True) try: samdb = SamDB(url=H, session_info=system_session(), credentials=creds, lp=lp) samdb.newgroup(groupname, groupou=groupou, grouptype = gtype, description=description, mailaddress=mail_address, notes=notes, gidnumber=gid_number, nisdomain=nis_domain) except Exception, e: # FIXME: catch more specific exception raise CommandError('Failed to create group "%s"' % groupname, e)
def run(self, groupname, credopts=None, sambaopts=None, versionopts=None, H=None): lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp, fallback_machine=True) samdb = SamDB(url=H, session_info=system_session(), credentials=creds, lp=lp) filter = ("(&(sAMAccountName=%s)(objectClass=group))" % groupname) try: res = samdb.search(base=samdb.domain_dn(), scope=ldb.SCOPE_SUBTREE, expression=filter, attrs=["dn"]) group_dn = res[0].dn except IndexError: raise CommandError('Unable to find group "%s"' % (groupname)) try: samdb.delete(group_dn) except Exception, e: # FIXME: catch more specific exception raise CommandError('Failed to remove group "%s"' % groupname, e)
def get_fsmo_roleowner(samdb, roledn, role): """Gets the owner of an FSMO role :param roledn: The DN of the FSMO role :param role: The FSMO role """ try: res = samdb.search(roledn, scope=ldb.SCOPE_BASE, attrs=["fSMORoleOwner"]) except LdbError, (num, msg): if num == ldb.ERR_NO_SUCH_OBJECT: raise CommandError("The '%s' role is not present in this domain" % role) raise
def run(self, sambaopts, versionopts, section_name=None, parameter_name=None, client_ip=None, client_name=None, verbose=False, suppress_prompt=None, show_all_parameters=False, server=None): if server: raise NotImplementedError("--server not yet implemented") if show_all_parameters: raise NotImplementedError( "--show-all-parameters not yet implemented") if client_name is not None and client_ip is None: raise CommandError("Both a DNS name and an IP address are " "required for the host access check") try: lp = sambaopts.get_loadparm() except RuntimeError, err: raise CommandError(err)
def run(self, server, zone, name, rtype, data, sambaopts=None, credopts=None, versionopts=None): if rtype.upper() not in ('A','AAAA','PTR','CNAME','NS','MX','SRV','TXT'): raise CommandError('Adding record of type %s is not supported' % rtype) record_type = dns_type_flag(rtype) rec = data_to_dns_record(record_type, data) self.lp = sambaopts.get_loadparm() self.creds = credopts.get_credentials(self.lp) dns_conn = dns_connect(server, self.lp, self.creds) rec_match = dns_record_match(dns_conn, server, zone, name, record_type, data) if rec_match is not None: raise CommandError('Record already exists') add_rec_buf = dnsserver.DNS_RPC_RECORD_BUF() add_rec_buf.rec = rec dns_conn.DnssrvUpdateRecord2(dnsserver.DNS_CLIENT_VERSION_LONGHORN, 0, server, zone, name, add_rec_buf, None) self.outf.write('Record added successfully\n')
class cmd_list(Command): """list GPOs for a user""" synopsis = "%prog gpo list <username>" takes_optiongroups = { "sambaopts": options.SambaOptions, "versionopts": options.VersionOptions, "credopts": options.CredentialsOptions, } takes_args = ['username'] takes_options = [ Option("-H", help="LDB URL for database or target server", type=str) ] def run(self, username, H=None, sambaopts=None, credopts=None, versionopts=None, server=None): self.url = H self.lp = sambaopts.get_loadparm() self.creds = credopts.get_credentials(self.lp, fallback_machine=True) samdb_connect(self) try: user_dn = self.samdb.search( expression='(&(samAccountName=%s)(objectclass=User))' % username)[0].dn except Exception, e: raise CommandError("Failed to find user %s" % username, e) # check if its a computer account try: msg = self.samdb.search(base=user_dn, scope=ldb.SCOPE_BASE, attrs=['objectClass'])[0] is_computer = 'computer' in msg['objectClass'] except Exception, e: raise CommandError( "Failed to find objectClass for user %s" % username, e)