def lookup_name(self, username): user=active_directory.find_user(username) #print user.dump #x=user.properties #print x.cn print user.cn return user.cn
def get_user_info(user_name, domain=None): # TEST """ return ''' dn: whatver l: Fort Worth displayName: cow mail: [email protected] ''' """ user = active_directory.find_user(user_name, domain) if not user: print "WARNING: user [%s] cannot be found" % user_name return {} # TODO: need to find a way to get all properties #print "properties: ", user.properties #print "-"*20 #print "xxx: ", user.dump() attrs_map = { 'dn': 'dn', 'displayName': 'first_name', 'name': 'name', 'mail': 'email', 'telephoneNumber': 'phone_number', 'department': 'department', 'employeeID': 'employee_id', 'sAMAccountName': 'sAMAccountName', # some extras 'l': 'location', 'title': 'title', } data = [] for key in attrs_map.keys(): try: value = eval("user.%s" % key) data.append("%s: %s" % (key, value)) except AttributeError: #print "Attribute [%s] does not exist" % key pass if hasattr(user,'memberOf'): for memberOf in user.memberOf: memberOf = str(memberOf).replace("LDAP://", "") data.append("memberOf: %s" % (memberOf)) else: for memberOf in user: memberOf = str(memberOf).replace("LDAP://", "") data.append("memberOf: %s" % (memberOf)) return "\n".join(data)
def generate_signatures(signature_path,ad_username): env = Environment(loader=FileSystemLoader(r'\\domain\netlogon\signatures\templates')) # signature template location #All templates html_template = env.get_template('signature_template.html') rtf_template = env.get_template('signature_template.rtf') plaintext_template = env.get_template('signature_template.txt') #Get AD fields user = active_directory.find_user(ad_username) displayName= user.displayName title = user.title company = user.company homePhone = None if user.homePhone: homePhone = user.homePhone telephoneNumber = user.telephoneNumber fax = user.facsimileTelephoneNumber email = user.mail website = user.wWWHomePage streetAddress = user.streetAddress city = user.l state = user.st zip = user.postalCode mobile = user.mobile #render HTML html_rendering = html_template.render(displayName = displayName,title = title,company = company,homePhone = homePhone, telephoneNumber = telephoneNumber,fax = fax,email = email,website = website, streetAddress = streetAddress,city = city,state = state, zip = zip, mobile = mobile) with open(signature_path + r"\default.htm", "wb") as f_html: f_html.write(html_rendering) f_html.close() #render RTF rtf_rendering = rtf_template.render(displayName = displayName,title = title,company = company,homePhone = homePhone, telephoneNumber = telephoneNumber,fax = fax,email = email,website = website, streetAddress = streetAddress,city = city,state = state, zip = zip, mobile = mobile) with open(signature_path + r"\default.rtf", "wb") as f_rtf: f_rtf.write(rtf_rendering) f_rtf.close() #render TXT txt_rendering = plaintext_template.render(displayName = displayName,title = title,company = company,homePhone = homePhone, telephoneNumber = telephoneNumber,fax = fax,email = email,website = website, streetAddress = streetAddress,city = city,state = state, zip = zip, mobile = mobile) txt_rendering = txt_rendering.replace('\n','\r\n') print txt_rendering with open(signature_path + r"\default.txt", "wb") as f_txt: f_txt.write(txt_rendering) f_txt.close()
def getwmi(self): try: self.sb.showMessage("Online") hostname = str(self.host_e.currentText()) #resolve ip from hostname and update label data = socket.gethostbyname(hostname) ip = repr(data) rip = re.compile("\'(.*?)\'") mip = rip.search(ip) ipstrip = mip.group(1) self.ip_e.setText(ipstrip) #get os version c = wmi.WMI(hostname) for os in c.Win32_OperatingSystem(): self.os_e.setText(os.caption) #convert wmi timestamp and calc uptime now = datetime.now() boot = os.LastBootUpTime boot = boot.split('.')[0] boot = parse(boot, fuzzy=True) totuptime = str(now - boot) totuptime = totuptime.split('.')[0] self.uptime_e.setText(totuptime) #set serial for bios in c.Win32_BIOS(): self.serial_e.setText(bios.SerialNumber) #set model for sys in c.Win32_ComputerSystem(): self.model_e.setText(sys.Model) #set logon and fullname if sys.Username > " ": usersplit = str(sys.UserName) domain,login=usersplit.split("\\") self.login = login self.logon_e.setText(self.login) fullname = str(active_directory.find_user(login)) r = re.compile('CN=(.*?),OU') m = r.search(fullname) if m: fullnamedisplay = m.group(1) self.name_e.setText(fullnamedisplay) else: self.logon_e.setText("No user login") except Exception: self.sb.showMessage("WMI Failed")
def check_account(self): ''' Get the account list in checkbox and show the information ''' if not self.check_date_textbox(): return if not self.check_extend_date(): return reload(active_directory) # reload because of COM object caching self.ui.acctable_widget.setRowCount(0) #self.ui.acctable_widget.clear() account_list = self.ui.acclist_textbox.toPlainText() if account_list == None or account_list == '': QtGui.QMessageBox.critical(self, u'Input Error', u'Nhập danh sách account trước') return #make the account list separator is white space to split account_list = account_list.replace(';', ' ') account_list = account_list.replace(',', ' ') account_list = account_list.split() log.info(u'Scan danh sách account %s' % [str(i) for i in account_list]) for acc in account_list: try: user = active_directory.find_user(acc) except: user = None if user != None: status = '' color = None checked = False status = 'OK' if self.is_locked(user=user): status = 'LOCKED' color = QtGui.QColor(0, 0, 255) checked = False if self.is_expired(user): status = 'EXPIRED' color = QtGui.QColor(0, 255, 0) checked = False if self.is_disabled(user=user): status = 'DISABLED' color = QtGui.QColor(0, 0, 255) checked = False self.add_item_table(acc, status, self.get_acc_expires(user), self.get_groups(user), user.distinguishedName, checked, color) else: self.add_item_table(acc, status='NOT FOUND', checked=False, color=QtGui.QColor(255, 0, 0)) log.info(u'Hoàn tất')
def test_find_user(self): self.assertADEqual(active_directory.find_user(self.user_id), self.user)
def get_session(self, sid, authenticated=False): self.env.log.debug('Retrieving session for ID %r', sid) db = self.env.get_db_cnx() cursor = db.cursor() refresh_cookie = False if self.sid and sid != self.sid: refresh_cookie = True self.sid = sid cursor.execute( "SELECT last_visit FROM session " "WHERE sid=%s AND authenticated=%s", (sid, int(authenticated))) row = cursor.fetchone() if not row: return self._new = False self.last_visit = int(row[0]) if self.last_visit and time.time() - self.last_visit > UPDATE_INTERVAL: refresh_cookie = True cursor.execute( "SELECT name,value FROM session_attribute " "WHERE sid=%s and authenticated=%s", (sid, int(authenticated))) hademail = hadname = False # used by NEW LDAP CODE for name, value in cursor: self[name] = value if name.strip() == 'email': hademail = True # used by NEW LDAP CODE if name.strip() == 'name': hadname = True # used by NEW LDAP CODE self._old.update(self) #### BEGIN NEW LDAP CODE #################################################### if LDAP_AD_LOOKUP_AVAILABLE: _needsave = False ldap_user = None # so that we don't have to hit the ldap server twice if both features are enabled get_email_from_ldap_if_empty = self.env.config.getbool( 'session', 'get_email_from_ldap_if_empty') get_email_from_ldap_userattribute = self.env.config.get( 'session', 'get_email_from_ldap_userattribute', 'mail') if not hademail and get_email_from_ldap_if_empty: #self.env.log.debug("No email address in session data") self.env.log.info( "Searching for email address via LDAP (using active_directory module) for user '%s'..." % sid) """ To fix a bizarro error ultimately caused by the active_directory module's use of pywin32 (and pythoncom via pywin32) the error will be something like "com_error: (-2147221008, 'CoInitialize has not been called.', None, None)" http://mail.python.org/pipermail/python-win32/2006-December/005425.html """ if threading.currentThread().getName() <> 'MainThread': pythoncom.CoInitialize() if not ldap_user: ldap_user = active_directory.find_user(str(sid)) if ldap_user: try: ldap_address = '' ldap_address = str( getattr(ldap_user, get_email_from_ldap_userattribute)).strip( ).lower() if ldap_address != '': self.env.log.info( "Found email address for user via LDAP: %s -> %s" % (str(sid), str(ldap_address))) self['email'] = ldap_address _needsave = True except AttributeError, e: self.env.log.error( "Specified LDAP user attribute does not exist: %s" % get_email_from_ldap_userattribute) get_name_from_ldap_if_empty = self.env.config.getbool( 'session', 'get_name_from_ldap_if_empty') get_name_from_ldap_userattribute = self.env.config.get( 'session', 'get_name_from_ldap_userattribute', 'displayName') if not hadname and get_name_from_ldap_if_empty: self.env.log.info( "Searching for name via LDAP (using active_directory module) for user '%s'..." % sid) """ To fix a bizarro error ultimately caused by the active_directory module's use of pywin32 (and pythoncom via pywin32) the error will be something like "com_error: (-2147221008, 'CoInitialize has not been called.', None, None)" http://mail.python.org/pipermail/python-win32/2006-December/005425.html """ if threading.currentThread().getName() <> 'MainThread': pythoncom.CoInitialize() if not ldap_user: ldap_user = active_directory.find_user(str(sid)) if ldap_user: try: ldap_name = '' ldap_name = str( getattr(ldap_user, get_name_from_ldap_userattribute)).strip() if ldap_name != '': self.env.log.info( "Found name for user via LDAP: %s -> %s" % (str(sid), str(ldap_name))) self['name'] = ldap_name _needsave = True except AttributeError, e: self.env.log.error( "Specified LDAP user attribute does not exist: %s" % get_name_from_ldap_userattribute)
with open('Workspace_Results.csv', 'w', newline='') as output: fieldnames = [ 'Name', 'AD Account', 'Email', 'Laptop', 'Active Token', 'WebEx' ] writer = csv.DictWriter(output, fieldnames=fieldnames) writer.writeheader() queryname = csv.DictReader(original) print("Now running AD scan") for row in queryname: print('.', end="") inst = WriteUser() inst.webex = "No" inst.VPN = "No" inst.ad = "No" inst.token = 0 user = active_directory.find_user(row["username"]) inst.cn = row['username'] if (user is not None): inst.ad = "Yes" user2 = active_directory.find_user(user.sAMAccountName) inst.email = user2.mail inst.username = user.sAMAccountName for group in user2.memberOf: if (group.cn == "WebEx Users"): inst.webex = "Yes" if (group.cn == "VPN-Technical" or group.cn == "VPN-Default" or group.cn == "VPN-Development"): with open('tokens.csv') as token: search = csv.reader(token) for row in search:
def lookup_user(self, username): user=active_directory.find_user(username) return user
import active_directory import win32api user = win32api.GetDomainName() + '\\' + win32api.GetUserName() print('CurUser: '******'Root: ', my_root) user = active_directory.find_user(win32api.GetUserName()) print('User: '******'Success')
def lookup_attr(self, username, attr): user=active_directory.find_user(username) print user.attr return user.attr
def generateReport(options): eventLogStartTime = getStartDate(options) eventLogEndTime = getEndDate(options) subject = 'Print statistics for %s' \ % getTimePeriodAsStr(eventLogStartTime, eventLogEndTime) sections = [makeTitle(subject)] errors = [] eventSource = 'Print' eventID = 10 # Print notification eventLogFlags = win32evtlog.EVENTLOG_BACKWARDS_READ | \ win32evtlog.EVENTLOG_SEQUENTIAL_READ eventLogType = 'System' eventRegEx = re.compile( r'Document (?P<number>\d+), ((?P<application>.+) - )?(?P<name>.+) owned ' \ 'by (?P<user>\w+) was printed on (?P<printer>.+) via port (?P<port>.+)\.' \ ' +Size in bytes: (?P<bytes>\d+); pages printed: (?P<pages>\d+)' ) if options.details: printList = ['Details:\n========\n::\n\n'] totals = Record() userDict = JobDict('User') groupDict = JobDict('Group') printerDict = JobDict('Printer', PrinterRecord) for printServer in options.printServers: eventLogHandle = win32evtlog.OpenEventLog(printServer, eventLogType) eventsRemaining = True eventTime = eventLogEndTime while eventsRemaining: events = win32evtlog.ReadEventLog(eventLogHandle, eventLogFlags, 0) for event in events: eventTime = datetime.strptime(event.TimeGenerated.Format(), '%m/%d/%y %H:%M:%S') if eventTime > eventLogEndTime: continue elif eventTime < eventLogStartTime: eventsRemaining = False break elif winerror.HRESULT_CODE(event.EventID) == eventID and \ event.SourceName == eventSource: eventMessage = win32evtlogutil.SafeFormatMessage(event, eventLogType) match = eventRegEx.match(eventMessage) if match: userName = match.group('user') printerName = match.group('printer') if printerName in options.ignorePrinters: continue bytes = int(match.group('bytes')) pages = int(match.group('pages')) totals.addJob(pages, bytes) if options.printerCounts: printerDict.addJob(printerName, pages, bytes) if options.userCounts: userDict.addJob(userName, pages, bytes) if options.printerCounts: printerDict.dict[printerName].users.addJob(userName, pages, bytes) if options.groupCounts: # FIXME: Need to decide what to do about users not in a group ADUser = active_directory.find_user(userName) or None if ADUser and ADUser.memberOf: for ADGroup in ADUser.memberOf: groupName = ADGroup.cn groupDict.addJob(groupName, pages, bytes) if options.printerCounts: printerDict.dict[printerName].groups.addJob(groupName, pages, bytes) if options.details: number = int(match.group('number')) port = match.group('port') eventMessage = 'Document %d owned by %s was printed on %s ' \ 'via port %s. Size in bytes: %d; pages printed: %d\n' \ % (number, userName, printerName, port, bytes, pages) printList.append(' %s: %s' % (eventTime, eventMessage)) else: errors.append('Error: could not parse event message\n\t%s' \ % eventMessage) if not events: eventsRemaining = False if eventTime > eventLogStartTime: errors.append('No events found on %s prior to %s' % (printServer, dayAsStr(eventTime) + eventTime.strftime(' %B %Y'))) if options.printServers: sections.append('::\n') sections.append(' Print servers queried: ' + ', '.join(options.printServers) + '\n') if len(errors): sections.append('::\n') sections.append(' ' + '\n '.join(errors) + '\n') if totals.jobs: sections.append('Totals:\n=======\n::\n') sections.append(' Page count: %d' % totals.pages) sections.append(' Job count: %d' % totals.jobs) sections.append(' Average pages per job: %.2f' % (float(totals.pages) / totals.jobs)) sections.append(' Total print size: ' + size(totals.bytes)) sections.append(' Average print size: ' + size(float(totals.bytes) / totals.jobs)) sections.append(' Note: Duplexed print jobs are not recorded, so' ' contribute their full page count as if single-sided.\n') if options.userCounts: sections.append(userDict.summarise(True)) if options.groupCounts: sections.append(groupDict.summarise(True)) if options.printerCounts: sections.append(printerDict.summarise(True)) sections.append(printerBreakdown(printerDict)) if options.details: sections.append(''.join(printList)) return '\n'.join(sections), subject
def is_locked(self, acc='', user=None): if user is None: user = active_directory.find_user(acc) return 'ADS_UF_LOCKOUT' in user.userAccountControl
def get_user_info(user_name, domain=None): # TEST """ return ''' dn: whatver l: Fort Worth displayName: cow mail: [email protected] ''' """ user = active_directory.find_user(user_name, domain) if not user: print "WARNING: user [%s] cannot be found" % user_name return '' import types if isinstance(user, types.GeneratorType): try: user = user.next() except StopIteration: user = None return '' else: users = list(user) if users: user = users[0] else: user = None return '' # TODO: need to find a way to get all properties #print "properties: ", user.properties #print "-"*20 #print "xxx: ", user.dump() attrs_map = { 'dn': 'dn', 'displayName': 'display_name', 'name': 'name', 'sn': 'last_name', 'givenName': 'first_name', 'mail': 'email', 'telephoneNumber': 'phone_number', 'department': 'department', 'employeeID': 'employee_id', 'sAMAccountName': 'sAMAccountName', # some extras 'l': 'location', 'title': 'title', } data = [] for key in attrs_map.keys(): try: value = eval("user.%s" % key) data.append("%s: %s" % (key, value)) except AttributeError: #print "Attribute [%s] does not exist" % key pass if hasattr(user, 'memberOf'): for memberOf in user.memberOf: memberOf = str(memberOf).replace("LDAP://", "") data.append("memberOf: %s" % (memberOf)) else: for memberOf in user: memberOf = str(memberOf).replace("LDAP://", "") data.append("memberOf: %s" % (memberOf)) return "\n".join(data)
import active_directory ad_user = ['john', 'mike', 'chad', 'brad'] for username in ad_user: try: user = active_directory.find_user(username) print(user.cn + ':' + str(user.employeenumber) + ':' + str(user.DISPLAYname) + ':' + str( user.EmailAddress) + ':' + str(user.Useraccountcontrol)) print(user.Useraccountcontrol) print(user.name) print(user.lastLogon) except: continue
def show_the_types_of_groups(): me = active_directory.find_user() for group in me.memberOf: print("Group types for", group.cn, ":", ", ".join(group.groupType))
def show_members_of_group(): me = active_directory.find_user() for group in me.memberOf: print("Members of group", group.cn) for group_member in group.member: print(" ", group_member)
def find_a_user(): print("INFO: Looking up user in Active Directory ") user = input("What user are you trying to lookup: ") user_find = active_directory.find_user(user) print(user_find)
def is_disabled(self, acc='', user=None): if user is None: user = active_directory.find_user(acc) return 'ADS_UF_ACCOUNTDISABLE' in user.userAccountControl
import active_directory print(active_directory.find_user("Administrator"))
def get_session(self, sid, authenticated=False): self.env.log.debug('Retrieving session for ID %r', sid) db = self.env.get_db_cnx() cursor = db.cursor() refresh_cookie = False if self.sid and sid != self.sid: refresh_cookie = True self.sid = sid cursor.execute("SELECT last_visit FROM session " "WHERE sid=%s AND authenticated=%s", (sid, int(authenticated))) row = cursor.fetchone() if not row: return self._new = False self.last_visit = int(row[0]) if self.last_visit and time.time() - self.last_visit > UPDATE_INTERVAL: refresh_cookie = True cursor.execute("SELECT name,value FROM session_attribute " "WHERE sid=%s and authenticated=%s", (sid, int(authenticated))) hademail = hadname = False # used by NEW LDAP CODE for name, value in cursor: self[name] = value if name.strip() == 'email': hademail = True # used by NEW LDAP CODE if name.strip() == 'name': hadname = True # used by NEW LDAP CODE self._old.update(self) #### BEGIN NEW LDAP CODE #################################################### if LDAP_AD_LOOKUP_AVAILABLE: _needsave = False ldap_user = None # so that we don't have to hit the ldap server twice if both features are enabled get_email_from_ldap_if_empty = self.env.config.getbool('session', 'get_email_from_ldap_if_empty') get_email_from_ldap_userattribute = self.env.config.get('session','get_email_from_ldap_userattribute','mail') if not hademail and get_email_from_ldap_if_empty: #self.env.log.debug("No email address in session data") self.env.log.info("Searching for email address via LDAP (using active_directory module) for user '%s'..." % sid) """ To fix a bizarro error ultimately caused by the active_directory module's use of pywin32 (and pythoncom via pywin32) the error will be something like "com_error: (-2147221008, 'CoInitialize has not been called.', None, None)" http://mail.python.org/pipermail/python-win32/2006-December/005425.html """ if threading.currentThread().getName() <> 'MainThread': pythoncom.CoInitialize() if not ldap_user: ldap_user = active_directory.find_user(str(sid)) if ldap_user: try: ldap_address = '' ldap_address = str(getattr(ldap_user,get_email_from_ldap_userattribute)).strip().lower() if ldap_address != '': self.env.log.info("Found email address for user via LDAP: %s -> %s" % (str(sid), str(ldap_address))) self['email'] = ldap_address _needsave = True except AttributeError, e: self.env.log.error("Specified LDAP user attribute does not exist: %s" % get_email_from_ldap_userattribute) get_name_from_ldap_if_empty = self.env.config.getbool('session', 'get_name_from_ldap_if_empty') get_name_from_ldap_userattribute = self.env.config.get('session','get_name_from_ldap_userattribute','displayName') if not hadname and get_name_from_ldap_if_empty: self.env.log.info("Searching for name via LDAP (using active_directory module) for user '%s'..." % sid) """ To fix a bizarro error ultimately caused by the active_directory module's use of pywin32 (and pythoncom via pywin32) the error will be something like "com_error: (-2147221008, 'CoInitialize has not been called.', None, None)" http://mail.python.org/pipermail/python-win32/2006-December/005425.html """ if threading.currentThread().getName() <> 'MainThread': pythoncom.CoInitialize() if not ldap_user: ldap_user = active_directory.find_user(str(sid)) if ldap_user: try: ldap_name = '' ldap_name = str(getattr(ldap_user,get_name_from_ldap_userattribute)).strip() if ldap_name != '': self.env.log.info("Found name for user via LDAP: %s -> %s" % (str(sid), str(ldap_name))) self['name'] = ldap_name _needsave = True except AttributeError, e: self.env.log.error("Specified LDAP user attribute does not exist: %s" % get_name_from_ldap_userattribute)