Exemplo n.º 1
0
def FindAdPrincipal(domain, account):
    import win32com.client as wc
    rootDse = wc.GetObject('LDAP://%s/RootDSE' % domain)

    namingContextStr = rootDse.get('defaultNamingContext')
    namingContext = wc.GetObject('LDAP://%s/%s' % (domain, namingContextStr))

    adsPath = namingContext.AdsPath

    adoConnection = wc.Dispatch('ADODB.Connection')
    adoConnection.Provider = 'ADsDSOObject'
    adoConnection.Open('Active Directory Provider')

    adoCommand = wc.Dispatch('ADODB.Command')
    adoCommand.ActiveConnection = adoConnection
    adoQuery = "SELECT * FROM '%(adsPath)s' WHERE cn = '%(account)s'"
    adoCommand.CommandText = adoQuery % {
        'adsPath': adsPath,
        'account': account
    }
    log.Debug('adoCommand.CommandText = %s' % adoCommand.CommandText)

    recordSet, rowsAffected = adoCommand.Execute()
    userObj = None
    if not recordSet.EOF:
        userStr = recordSet.Fields.Item(0).value
        userObj = wc.GetObject(userStr)
        log.Debug('Ad object %s\%s found' % (domain, account))
    else:
        log.Debug('Ad object %s\%s not found' % (domain, account))

    return userObj
Exemplo n.º 2
0
def getObject(dn, autoFindRootDSE):
    if not autoFindRootDSE:
        return com_client.GetObject(dn)
    ldap_loc = com_client.GetObject('LDAP://rootDSE').Get(
        "defaultNamingContext")
    ldap_obj_loc = dn + ldap_loc
    print ldap_obj_loc
    return com_client.GetObject("LDAP://" + ldap_obj_loc)
Exemplo n.º 3
0
def AddUserToGroup(server_u, user, server_g, group):
    g = com_client.GetObject("LDAP://CN=%s,CN=Users,%s" %
                             (group, GetDomainDN(server_g)))
    u = com_client.GetObject("LDAP://CN=%s,CN=Users,%s" %
                             (user, GetDomainDN(server_u)))
    u_sid = win32security.SID(u.objectSid)
    try:
        g.Add("LDAP://%s/<SID=%s>" % (server_u, str(u_sid)[6:]))
        g.SetInfo()
    except:
        pass
Exemplo n.º 4
0
def InitAdPrincipal(domain,
                    accountName,
                    principalType='User',
                    containerName='users'):
    import win32com.client as wc
    rootDse = wc.GetObject('LDAP://%(domain)s/RootDSE' % {'domain': domain})
    namingContextStr = rootDse.get('defaultNamingContext')
    container = wc.GetObject(
        'LDAP://%(domain)s/CN=%(containerName)s,%(namingContextStr)s' % {
            'domain': domain,
            'containerName': containerName,
            'namingContextStr': namingContextStr
        })
    principalObj = container.Create(
        principalType, 'CN=%(account)s' % {'account': accountName})
    return principalObj
Exemplo n.º 5
0
def IsItemExist(server, name):
    try:
        com_client.GetObject("LDAP://CN=%s,CN=Users,%s" %
                             (name, GetDomainDN(server)))
        return True
    except:
        return False
Exemplo n.º 6
0
 def reboot(self):
     updclient = jsonrpc_http.HttpServiceProxy(
         'http://localhost:8008', bus.cnf.key_path(bus.cnf.DEFAULT_KEY))
     try:
         dont_do_it = updclient.status()['state'].startswith(
             'in-progress')
     except:
         pass
     else:
         if dont_do_it:
             raise Exception(
                 'Reboot not allowed, cause Scalarizr update is in-progress'
             )
     wmi = client.GetObject('winmgmts:')
     for wos in wmi.InstancesOf('Win32_OperatingSystem'):
         if wos.Primary:
             # SCALARIZR-1609
             # XXX: Function call happens without () here for some reason,
             # as just `wos.Reboot`. Then it returns 0 and we try to call it.
             # Check if this strange behavior persists when we upgrade
             # to the latest pywin32 version (219).
             try:
                 wos.Reboot()
             except TypeError:
                 pass
Exemplo n.º 7
0
 def get_hostname(self):
     try:
         wmi = client.GetObject('winmgmts:')
         for computer in wmi.InstancesOf('Win32_ComputerSystem'):
             return computer.Name
     except:
         return ''
Exemplo n.º 8
0
def vba_email(recipients, subject, message, cc=[], attachments=[]):
    """ list of str, str, str, list of str, list of str -> None
    Sends an email using the existing oulook profile with the following params
    > Email is sent to the list of recipeints
    > Subject is the subject line of the message
    > Message is the HTML formatted body of the message
    > CC is the list of emails to include on the CC line
    > Attachments are the file paths to the attchments for the message
    """
    # Initialize the outlook object within python
    outlook = win32.GetObject(Class="Outlook.Application")
    # Create the mail, populate the mail item
    mailer = outlook.CreateItem(0)
    mailer.To = ";".join(recipients)
    if cc:
        mailer.CC = ";".join(cc)
    mailer.Subject = subject
    mailer.HTMLBody = message
    # Add attachments if they exist, exit if attachment can't be found
    for item in attachments:
        if os.path.exists(item):
            mailer.Attachments.Add(item)
        else:
            raise FileNotFoundError(
                "The following attachment could not be found: {}".format(item))
    # Send and collect garbage
    mailer.Send()
    del mailer
    del outlook
Exemplo n.º 9
0
def add_account_to_group(account, group, domain_name):

    disting = domain_name_to_disting(domain_name)
    ad_account = find(account, disting)

    groupDomain = disting
    groupDomainDist = disting
    ad_group = None
    if (group.find("\\") != -1):
        groupDomain, group = group.split("\\")
        gd = groupDomain.upper()
        if gd == 'NT AUTHORITY' or gd == 'BUILTIN':
            ad_group = com_client.GetObject("LDAP://CN=%s,CN=Builtin,%s" %
                                            (group, disting))
        else:
            groupDomainDist = domain_name_to_disting(groupDomain)

    if not ad_group: ad_group = find(group, groupDomainDist)

    if (not ad_group.IsMember(ad_account.ADsPath)):
        try:
            ad_group.Add(ad_account.ADsPath)
        except:
            u_sid = win32security.SID(ad_account.objectSid)
            ad_group.Add("LDAP://%s/<SID=%s>" % (groupDomain, str(u_sid)[6:]))

    ad_group.SetInfo()
Exemplo n.º 10
0
def getProcess(pid=None, caption=None):
    #获得当前后台所有程序,或给定pid的程序
    #取进程 id,失败返回 None
    global cfg
    pythoncom.CoInitialize(
    )  #默认win32com是非线程安全的,要在线程中安全使用,要在开始时CoInitialize,在结束时CoUninitialize
    if cfg['debug']:
        mylog("in getProcess(),pid=%s" % str(pid))
    wmi = win32com.GetObject('winmgmts:')
    if not pid == None:
        wql = "SELECT * FROM Win32_Process where ProcessId=%s" % str(pid)
    elif not caption == None:  #WQL是忽略大小写的,可以不用再转小写了
        wql = "SELECT * FROM Win32_Process where Caption='%s'" % caption
    else:
        wql = "SELECT * FROM Win32_Process "
    procs = wmi.ExecQuery(wql)
    if cfg['debug']:
        mylog("wql=%s" % wql)
        mylog('proc=' + str(procs))
    procs_dict = []
    for p in procs:
        procs_dict.append({
            'cmd': p.CommandLine,
            'name': p.name,
            'caption': p.caption,
            'pid': p.ProcessId
        })
    pythoncom.CoUninitialize()
    return procs_dict
Exemplo n.º 11
0
 def _GetPidFromProcessName(self, process_name):
     """取进程 id,失败返回 None"""
     wmi = win32com.GetObject('winmgmts:')
     pid_list = wmi.ExecQuery(
         "SELECT * FROM Win32_Process where name = '{process_name}'".format(
             process_name=process_name.replace("'", "")))
     if len(pid_list):
         return int(pid_list[0].handle)
Exemplo n.º 12
0
    def CheckProcExistByPN(self, process_name):
        print "in CheckProcExistByPN step"
        try:

            WMI = client.GetObject('winmgmts:')
            processCodeCov = WMI.ExecQuery('select * from Win32_Process where Name="%s"' % process_name)
        except Exception, e:
            print process_name + "error : ", e
Exemplo n.º 13
0
 def __init__(self):
     self._c = wmi.WMI()
     self._com = client.Dispatch("WbemScripting.SWbemRefresher")
     self._obj = client.GetObject("winmgmts:\\root\cimv2")
     self._cs = self._c.Win32_ComputerSystem()
     self._os = self._c.Win32_OperatingSystem()
     self._pfu = self._c.Win32_PageFileUsage()
     self.hostname = self._os[0].CSName
Exemplo n.º 14
0
        def net_stats(self):
            class MIB_IFROW(ctypes.Structure):
                _fields_ = [
                    ('wszName', wintypes.WCHAR * 256),
                    ('dwIndex', wintypes.DWORD),
                    ('dwType', wintypes.DWORD),
                    ('dwMtu', wintypes.DWORD),
                    ('dwSpeed', wintypes.DWORD),
                    ('dwPhysAddrLen', wintypes.DWORD),
                    ('bPhysAddr', wintypes.BYTE * 8),
                    ('dwAdminStatus', wintypes.DWORD),
                    ('dwOperStatus', wintypes.DWORD),
                    ('dwLastChange', wintypes.DWORD),
                    ('dwInOctets', wintypes.DWORD),
                    ('dwInUcastPkts', wintypes.DWORD),
                    ('dwInNUcastPkts', wintypes.DWORD),
                    ('dwInDiscards', wintypes.DWORD),
                    ('dwInErrors', wintypes.DWORD),
                    ('dwInUnknownProtos', wintypes.DWORD),
                    ('dwOutOctets', wintypes.DWORD),
                    ('dwOutUcastPkts', wintypes.DWORD),
                    ('dwOutNUcastPkts', wintypes.DWORD),
                    ('dwOutDiscards', wintypes.DWORD),
                    ('dwOutErrors', wintypes.DWORD),
                    ('dwOutQlen', wintypes.DWORD),
                    ('dwDescrlen', wintypes.DWORD),
                    ('bDescr', wintypes.BYTE * 256),
                ]

            wmi = client.GetObject('winmgmts:')

            adapters = [
                adapter for adapter in wmi.InstancesOf('win32_networkadapter')
                if adapter.PhysicalAdapter is True
            ]

            iphlpapi = ctypes.windll.LoadLibrary('iphlpapi')

            res = dict()
            for adapter in adapters:
                if_entry = MIB_IFROW()
                if_entry.dwIndex = adapter.InterfaceIndex
                iphlpapi.GetIfEntry(ctypes.pointer(if_entry))

                res[adapter.Name] = {
                    'receive': {
                        'bytes': int(if_entry.dwInOctets),
                        'packets': int(if_entry.dwInUcastPkts),
                        'errors': int(if_entry.dwInErrors),
                    },
                    'transmit': {
                        'bytes': int(if_entry.dwOutOctets),
                        'packets': int(if_entry.dwOutUcastPkts),
                        'errors': int(if_entry.dwOutErrors),
                    },
                }
            return res
Exemplo n.º 15
0
    def network(self):
        con = wmi.WMI(moniker="//./root/cimv2")
        com = client.Dispatch("WbemScripting.SWbemRefresher")
        obj = client.GetObject("winmgmts:\\root\cimv2")
        items = com.AddEnum(
            obj, "Win32_PerfRawData_Tcpip_NetworkInterface").objectSet
        net_info = []
        net_dict = {}
        net_id_disk = {}
        for i, interface in enumerate(
                con.Win32_NetworkAdapterConfiguration(IPEnabled=1)):
            index = 'Network_Adapter' + str(i)
            info_dict = {}
            info_dict['net_MACAddress'] = interface.MACAddress
            info_dict['net_IPSubnet'] = interface.IPSubnet
            info_dict['net_DefaultIPGateway'] = interface.DefaultIPGateway
            info_dict['net_ip_address'] = []
            info_dict['Caption'] = interface.Description
            if not interface.IPAddress is None:
                for ip_address in interface.IPAddress:
                    info_dict['net_ip_address'].append(ip_address)
            net_id_disk[interface.Description] = index
            net_dict[index] = info_dict

        com.Refresh()
        for item in items:
            if net_id_disk.has_key(item.Name):
                net_bytes_in = long(item.BytesReceivedPerSec)
                net_bytes_out = long(item.BytesSentPerSec)
                time.sleep(1)
                com.Refresh()
                net_dict[net_id_disk[item.Name]]['net_bytes_in'] = {
                    'volume':
                    (long(item.BytesReceivedPerSec) - net_bytes_in) * 8 / 1024,
                    'unit':
                    'Kbps'
                }
                net_dict[net_id_disk[item.Name]]['net_bytes_out'] = {
                    'volume':
                    (long(item.BytesSentPerSec) - net_bytes_out) * 8 / 1024,
                    'unit': 'Kbps'
                }
                net_dict[net_id_disk[item.Name]]['net_bytes_in_cur'] = {
                    'volume': long(item.BytesReceivedPerSec),
                    'unit': 'B'
                }
                net_dict[net_id_disk[item.Name]]['net_bytes_in_cur'] = {
                    'volume': long(item.BytesReceivedPerSec),
                    'unit': 'B'
                }
                net_dict[net_id_disk[item.Name]]['net_pkts_in_cur'] = long(
                    item.PacketsReceivedPerSec)
                net_dict[net_id_disk[item.Name]]['net_pkts_out_cur'] = long(
                    item.PacketsSentPerSec)
            net_info.append(net_dict)
        return net_info
Exemplo n.º 16
0
    def get_net(self):
        c = wmi.WMI()
        com = client.Dispatch("WbemScripting.SWbemRefresher")
        obj = client.GetObject("winmgmts:\\root\cimv2")
        items = com.AddEnum(
            obj, "Win32_PerfRawData_Tcpip_NetworkInterface").objectSet

        data_dict = {}
        interfaces = []
        for interface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1):
            print interface.IPAddress[0]
            interfaces.append(interface.Description)

        net_bytes_in = 0
        net_bytes_out = 0
        net_pkts_in = 0
        net_pkts_out = 0

        com.Refresh()
        for item in items:
            if item.Name in interfaces:
                #print 'Name:%s -> B_in:%s, B_out:%s, P_in:%s, P_out:%s' %(item.Name, item.BytesReceivedPerSec, item.BytesSentPerSec, item.PacketsReceivedPerSec, item.PacketsSentPerSec)
                net_bytes_in += long(item.BytesReceivedPerSec)
                net_bytes_out += long(item.BytesSentPerSec)
                net_pkts_in += long(item.PacketsReceivedPerSec)
                net_pkts_out += long(item.PacketsSentPerSec)

        time.sleep(1)

        net_bytes_in_cur = 0
        net_bytes_out_cur = 0

        com.Refresh()
        for item in items:
            if item.Name in interfaces:
                net_bytes_in = long(item.BytesReceivedPerSec) - net_bytes_in
                net_bytes_in_cur += long(item.BytesReceivedPerSec)
                net_bytes_out = long(item.BytesSentPerSec) - net_bytes_out
                net_bytes_out_cur += long(item.BytesSentPerSec)
                net_pkts_in = long(item.PacketsReceivedPerSec) - net_pkts_in
                net_pkts_out = long(item.PacketsSentPerSec) - net_pkts_out

        data_dict['net_bytes_in'] = {'volume': net_bytes_in, 'unit': 'B/s'}
        data_dict['net_bytes_in_sum'] = {
            'volume': net_bytes_in_cur,
            'unit': 'B'
        }
        data_dict['net_bytes_out'] = {'volume': net_bytes_out, 'unit': 'B/s'}
        data_dict['net_bytes_out_sum'] = {
            'volume': net_bytes_out_cur,
            'unit': 'B'
        }
        data_dict['net_pkts_in'] = {'volume': net_pkts_in, 'unit': 'p/s'}
        data_dict['net_pkts_out'] = {'volume': net_pkts_out, 'unit': 'p/s'}

        return {'data': data_dict, 'timestamp': time.asctime(time.localtime())}
Exemplo n.º 17
0
        def block_devices(self):
            wmi = client.GetObject('winmgmts:')

            res = list()
            for disk in wmi.InstancesOf(
                    'Win32_PerfRawData_PerfDisk_LogicalDisk'):
                if disk.Name == '_Total':
                    continue
                res.append(disk.Name)
            return res
Exemplo n.º 18
0
        def mounts(self):
            wmi = client.GetObject('winmgmts:')

            ret = {}
            for disk in wmi.InstancesOf('Win32_LogicalDisk'):
                letter = disk.DeviceId[0].lower()
                entry = {'device': letter, 'mpoint': letter}
                entry.update(self._format_statvfs(disk))
                ret[letter] = entry
            return ret
Exemplo n.º 19
0
 def current_process(self):
     com = client.Dispatch("WbemScripting.SWbemRefresher")
     obj = client.GetObject("winmgmts:\\root\cimv2")
     items = com.AddEnum(
         obj, "Win32_PerfFormattedData_PerfProc_Process").objectSet
     com.Refresh()
     for item in items:
         timestamp = time.strftime('%a, %d %b %Y %H:%M:%S',
                                   time.localtime())
         print item.IDProcess, item.Name, item.PriorityBase, item.VirtualBytes, item.PoolNonpagedBytes, item.PoolPagedBytes, item.PercentProcessorTime, item.WorkingSet, timestamp
Exemplo n.º 20
0
 def __init__(self):
     self._c = wmi.WMI()
     # conn = wmi.connect_server(server="172.30.126.224", user="******", password="******")
     # self._c = wmi.WMI(wmi=conn)
     self._com = client.Dispatch("WbemScripting.SWbemRefresher")
     self._obj = client.GetObject("winmgmts:\\root\cimv2")
     self._cs = self._c.Win32_ComputerSystem()
     self._os = self._c.Win32_OperatingSystem()
     self._pfu = self._c.Win32_PageFileUsage()
     self.hostname = self._os[0].CSName
Exemplo n.º 21
0
    def __init__(self):

        self.com = client.Dispatch("WbemScripting.SWbemRefresher")
        obj = client.GetObject("winmgmts:\\root\cimv2")
        #diskitems = com.AddEnum(obj, "Win32_PerfFormattedData_PerfDisk_LogicalDisk").objectSet
        #time.sleep(1)

        self.diskitems = self.com.AddEnum(
            obj, "Win32_PerfRawData_PerfDisk_PhysicalDisk").objectSet

        self.com.Refresh()
Exemplo n.º 22
0
def abreWorkbook(xlArquivo):
	global excel
	global win32
	try:        
	    xlwb = win32.GetObject(xlArquivo)            
	except Exception as e:
	    try:
	        xlwb = excel.Workbooks.Open(xlArquivo)
	    except Exception as e:
	        print(e)
	        xlwb = None                    
	return(xlwb)   
Exemplo n.º 23
0
    def get_fs_info(self):
        con = wmi.WMI(moniker="//./root/cimv2")
        disk_info = []
        disk_dict = {}
        disk_id_disk = {}
        info_dict = {}
        #  DriveType=3 : "Local Disk",
        for i, disk in enumerate(con.Win32_LogicalDisk(DriveType=3)):
            index = 'Partition' + str(i)
            info_dict = {}
            info_dict['disk_FreeSpace'] = {
                'volume':
                round(float(disk.FreeSpace) / (1024 * 1024 * 1024), 2),
                'unit': 'GB'
            }
            info_dict['disk_capacity'] = {
                'volume': round(float(disk.Size) / (1024 * 1024 * 1024), 2),
                'unit': 'GB'
            }
            info_dict['disk_Used'] = {
                'volume':
                round((float(disk.Size) - float(disk.FreeSpace)) /
                      (1024 * 1024 * 1024), 2),
                'unit':
                'GB'
            }
            info_dict['fstype'] = disk.FileSystem
            info_dict['mnt'] = ''
            info_dict['Caption'] = disk.DeviceID
            #print disk.DeviceID
            disk_id_disk[disk.DeviceID] = index
            disk_dict[index] = info_dict

        com = client.Dispatch("WbemScripting.SWbemRefresher")
        obj = client.GetObject("winmgmts:\\root\cimv2")
        diskitems = com.AddEnum(
            obj, "Win32_PerfFormattedData_PerfDisk_LogicalDisk").objectSet

        com.Refresh()
        for item in diskitems:
            try:
                disk_dict[disk_id_disk[item.Name]]['io_stat_read'] = {
                    'volume': (float(item.DiskReadBytesPerSec) / 1024),
                    'unit': 'KB/s'
                }
                disk_dict[disk_id_disk[item.Name]]['io_stat_write'] = {
                    'volume': (float(item.DiskWriteBytesPerSec) / 1024),
                    'unit': 'KB/s'
                }
            except:
                pass
            disk_info.append(disk_dict)
        return disk_info
Exemplo n.º 24
0
 def do_work(self):
     self.pri_session = client.GetObject(
         "SAPGUI").GetScriptingEngine.Children(0)
     self.create_sessions()
     if self.action == 'query':
         self.submit_query()
     elif self.action == 'download':
         self.download_spools()
     elif self.action == 'clear':
         self.clear_spools()
     self.close_session()
     return True
Exemplo n.º 25
0
def check_exsit(path, process_name):
    WMI = client.GetObject('winmgmts:')
    processCodeCov = WMI.ExecQuery(
        'select * from Win32_Process where Name="%s"' % process_name)
    if len(processCodeCov) > 0:
        print '%s is exists' % process_name
    else:
        print '%s is not exists' % process_name
        os.chdir(path)
        # win32api.ShellExecute(0, 'open', process_name, '', '', 0)  # 后台执行
        print os.path.join(path, "services", process_name)
        os.system(os.path.join(path, "services", process_name))
Exemplo n.º 26
0
 def uptime(self):
     # pylint: disable=W0603
     wmi = client.GetObject('winmgmts:')
     win_os = next(iter(wmi.InstancesOf('Win32_OperatingSystem')))
     local_time, tz_op, tz_hh60mm = re.split(r'(\+|\-)',
                                             win_os.LastBootUpTime)
     local_time = local_time.split('.')[0]
     local_time = time.mktime(time.strptime(local_time, '%Y%m%d%H%M%S'))
     tz_seconds = int(tz_hh60mm) * 60
     if tz_op == '+':
         return time.time() - local_time + tz_seconds
     else:
         return time.time() - local_time - tz_seconds
Exemplo n.º 27
0
        def disk_stats(self):
            wmi = client.GetObject('winmgmts:')

            res = dict()
            for disk in wmi.InstancesOf(
                    'Win32_PerfRawData_PerfDisk_LogicalDisk'):
                # Skip Total
                if disk.Name == '_Total':
                    continue

                res[disk.Name] = dict(
                    read=dict(bytes=int(disk.AvgDiskBytesPerRead)),
                    write=dict(bytes=int(disk.AvgDiskBytesPerWrite)))
            return res
Exemplo n.º 28
0
        def cpu_stat(self):
            wmi = client.GetObject('winmgmts:')

            processors = wmi.InstancesOf('Win32_Processor')
            avg_percentage = float(
                sum([cpu.LoadPercentage
                     for cpu in processors])) / len(processors)

            return {
                'user': avg_percentage,
                'system': 0,
                'idle': 100 - avg_percentage,
                'nice': 0
            }
Exemplo n.º 29
0
        def statvfs(self, mpoints=None):
            wmi = client.GetObject('winmgmts:')

            # mpoints == disks letters on Windows
            mpoints = map(lambda s: s[0].lower(), mpoints)
            if not isinstance(mpoints, list):
                raise Exception(
                    'Argument "mpoints" should be a list of strings, '
                    'not %s' % type(mpoints))
            ret = {}
            for disk in wmi.InstancesOf('Win32_LogicalDisk'):
                letter = disk.DeviceId[0].lower()
                if letter in mpoints:
                    ret[letter] = self._format_statvfs(disk)
            return ret
def close_app():
    wmi = win32.GetObject('winmgmts:')
    process_desktop = wmi.ExecQuery(
        'select * from Win32_Process where Name="%s"' % "desktop.exe")
    if len(process_desktop) > 0:
        subprocess.call("taskkill /f /im desktop.exe")
        time.sleep(2)
    process_outlook = wmi.ExecQuery(
        'select * from Win32_Process where Name="%s"' % "outlook.exe")
    if len(process_outlook) > 0:
        pass
    else:
        subprocess.Popen(
            r'C:\Program Files (x86)\Microsoft Office\Office16\outlook.exe')
        time.sleep(20)