Ejemplo n.º 1
0
    bluepill = usb.core.find(idVendor=USB_VID, idProduct=USB_PID)
    if bluepill is None:
        raise RuntimeError('Device not found')

    if platform.startswith('linux'):
        sensor_handle = []
        for hwmon_entry in HWMON_ROOT.iterdir():
            try:
                hwmon_name = hwmon_entry.joinpath('name').open(
                    mode='r').readline().strip()
            except:
                hwmon_name = ''

            if hwmon_name != 'coretemp':
                continue

            for sensor_entry in hwmon_entry.iterdir():
                if not sensor_entry.name.endswith('input'):
                    continue

                sensor_handle.append(sensor_entry.open(mode='r'))

        if bluepill.is_kernel_driver_active(USB_IF):
            print('detaching kernel driver')
            bluepill.detach_kernel_driver(USB_IF)

    elif platform.startswith('win32'):
        sensor_handle = wmi.WMI(namespace='root\\WMI')

    start_update_loop(bluepill, sensor_handle)
Ejemplo n.º 2
0
 def __init__(self):
     if sys.platform == 'win32':
         self._conn_cimv2 = wmi.WMI(privileges=["Shutdown"])
Ejemplo n.º 3
0
def get_nic_list():
    ''' Obtain network adaptors configurations '''

    configs = wmi.WMI().Win32_NetworkAdapterConfiguration(IPEnabled=True)
    return configs
Ejemplo n.º 4
0
def fix_game_disruption(
        String=None):  #if find_game_reference_point() == None or ...
    #global game_position , my_seat_number , MY_PROFILE_NAME , bot_status , just_do_check_fold

    shout(7 * "-", color='yellow')
    if String == None:
        shout("fix_game_disruption() is running....", color='yellow')
    elif type(String) == str:
        shout("fix_game_disruption() <-- %s is running...." % String,
              color='yellow')

    if is_internet_disconnected():
        shout('Internet is Disconnected, waiting to reconect...')
        while is_internet_disconnected():
            continue
        shout('Internet is Connected Back!')
        time.sleep(15)
        if find_and_click_on_reconnect_button() == None:
            screenshot_error('No reconnect button founded')

    click(
        'exit_probable_advertisement')  # click to Exit probable Advertisement
    shout("Position (0,720) is clicked", color='yellow')
    pyautogui.press('esc')

    config.game_position = pyautogui.locateOnScreen(
        'screen_monitoring/find_game_position/reference image.png')
    if config.game_position == None:
        config.alternative_game_position = pyautogui.locateOnScreen(
            'screen_monitoring/find_game_position/alternative reference image.png'
        )
        if config.alternative_game_position != None:
            config.game_position = (alternative_game_position[0] + 328,
                                    alternative_game_position[1] - 245)
    if config.game_position != None:
        config.game_position = (int(config.game_position[0]),
                                int(config.game_position[1]))
    else:
        for process in wmi.WMI().Win32_Process():
            if process.Name == 'SystemSettings.exe':
                shout("SystemSettings Update is on desktop")
                shout("closing Windows Update program")
                screenshot_error('right before closing windows update program')
                click('close_update_window')
                break

    if config.game_position == None:
        config.game_position = find_game_position.find_game_reference_point()
    if config.game_position != None:
        shout("Game region refounded after fix_game_disruption()",
              color='yellow')

    if config.bot_status != 'OBSERVING':

        if pm.button_pixel(config.game_position, 'i_am_back'):
            click('i_am_back')
            if pm.player_cards_pixel(config.game_position,
                                     config.my_seat_number) == True:
                config.just_do_check_fold = True
                shout(
                    "After fix_game_disruption() --> just_do_check_fold is True.",
                    color='yellow')
            else:
                config.bot_status = 'WAITING_FOR_FIRST_HAND'
                shout(
                    "After fix_game_disruption() --> bot_status is 'WAITING_FOR_FIRST_HAND'.",
                    color='on_yellow')

        if check_i_am_in_or_out() == "Out":
            sit_in("Min buy in")

    shout(7 * "-", color='yellow')
Ejemplo n.º 5
0
 def __init__(self, host='.'):
     self._enabled_states_map = dict((v, k) for k, v in
                                     self._vm_power_states_map.iteritems())
     if sys.platform == 'win32':
         self._init_hyperv_wmi_conn(host)
         self._conn_cimv2 = wmi.WMI(moniker='//%s/root/cimv2' % host)
Ejemplo n.º 6
0
 def _conn(self):
     if self._wmi_conn is None:
         self._wmi_conn = wmi.WMI(moniker=self._wmi_namespace)
     return self._wmi_conn
Ejemplo n.º 7
0
rew = rwe.ReadWriteEverything()


def maxspeed():
    rew.callRWECommand('''>WEC 0xBD 0x4E
    Write EC Byte 0xBD = 0x4E
    >RwExit''')


def autospeed():
    rew.callRWECommand('''>WEC 0xBD 0x52
    Write EC Byte 0xBD = 0x52
    >RwExit''')


w = wmi.WMI(namespace="root\OpenHardwareMonitor")

taskkillcmd = 'taskkill /F /IM OpenHardwareMonitor.exe'
os.system(taskkillcmd)
OHMstartcmd = 'START OpenHardwareMonitor.exe'
os.system(OHMstartcmd)
time.sleep(3)

checkinterval = 1  # every seconds
averagecount = 60  # count average for x count
crittemp = 75
lowtemp = 67
state = 'auto'
autospeed()

cpu1average = []
Ejemplo n.º 8
0
 def test_process_cmdline(self):
     w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0]
     p = psutil.Process(self.pid)
     self.assertEqual(' '.join(p.cmdline()), w.CommandLine.replace('"', ''))
Ejemplo n.º 9
0
 def test_process_username(self):
     w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0]
     p = psutil.Process(self.pid)
     domain, _, username = w.GetOwner()
     username = "******" % (domain, username)
     self.assertEqual(p.username(), username)
Ejemplo n.º 10
0
 def test_process_name(self):
     w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0]
     p = psutil.Process(self.pid)
     self.assertEqual(p.name(), w.Caption)
Ejemplo n.º 11
0
 def test_process_exe(self):
     w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0]
     p = psutil.Process(self.pid)
     # Note: wmi reports the exe as a lower case string.
     # Being Windows paths case-insensitive we ignore that.
     self.assertEqual(p.exe().lower(), w.ExecutablePath.lower())
Ejemplo n.º 12
0
 def _init_cimv2_wmi_conn(self, host):
     self._conn_cimv2 = wmi.WMI(moniker='//%s/root/cimv2' % host)
Ejemplo n.º 13
0
def getWindowsSystemStatus():
    import wmi, win32file
    w = wmi.WMI()

    result = {
        'datetime': time.localtime(),
        'cpus': [],
        'ram': {},
        'disks': [],
    }

    # CPUs
    cpus = {}
    for i in w.Win32_Processor(["SocketDesignation", "LoadPercentage"]):
        if i.SocketDesignation not in cpus:
            cpus[i.SocketDesignation] = {
                'value': str(len(cpus)),
                'cores': [],
            }
            result['cpus'].append(cpus[i.SocketDesignation])

        core = len(cpus[i.SocketDesignation]['cores'])
        cpus[i.SocketDesignation]['cores'].append({
            'value':
            str(core),
            'used':
            str(i.LoadPercentage),
        })

    for cpu in result['cpus']:
        cpu['used'] = str(
            sum(int(c['used']) for c in cpu['cores']) / len(cpu['cores']))

    # RAM
    for i in w.Win32_OperatingSystem(
        ["TotalVisibleMemorySize", "FreePhysicalmemory"]):
        total = int(i.TotalVisibleMemorySize) // 1024
        free = int(i.FreePhysicalmemory) // 1024

        result['ram']['total'] = str(total)
        result['ram']['available'] = str(free)
        result['ram']['used'] = str(total - free)

    # disks
    for i in w.Win32_Volume(["Capacity", "FreeSpace", "Name", "DeviceID"],
                            DriveType=3):
        total = int(i.Capacity) // DISK_MEGABYTE
        free = int(i.FreeSpace) // DISK_MEGABYTE

        # map "\\?\Volume{Guid}\" to "\\.\Volume{Guid}"
        vid = re.sub(r'^\\\\\?\\Volume{(.*)}\\$', r'\\\\.\Volume{\1}',
                     i.DeviceID)
        try:
            h = win32file.CreateFile(
                vid, 0, win32file.FILE_SHARE_WRITE | win32file.FILE_SHARE_READ,
                None, win32file.OPEN_EXISTING, 0, 0)
            buf = win32file.DeviceIoControl(
                h, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, None, 2048, None)
            win32file.CloseHandle(h)

            # returned structure starts with a count and
            # then an array of DISK_EXTENT structures,
            # each starting with a disk id; if there is
            # exactly one extent, return the disk id,
            # otherwise return 'unknown'
            count, diskid = struct.unpack('LL', buf[0:8])
            if count == 1:
                volume = str(diskid)
            else:
                volume = 'unknown'
        except Exception, e:
            volume = 'unknown'

        result['disks'].append({
            'value': i.Name,
            'total': str(total),
            'used': str(total - free),
            'available': str(free),
            'device': volume
        })
Ejemplo n.º 14
0
import wmi
import winsound
import ctypes
import time
t = wmi.WMI(moniker="//./root/wmi")
b = t.ExecQuery('Select * from BatteryFullChargedCapacity')
total = b[0].FullChargedCapacity
while True:
    b = t.ExecQuery('Select * from BatteryStatus where Voltage > 0')
    charge = round((b[0].RemainingCapacity / total) * 100)
    chargerConnected = b[0].PowerOnLine
    if charge <= 40 and not chargerConnected:
        winsound.PlaySound('sound.wav', winsound.SND_FILENAME)
        ctypes.windll.user32.MessageBoxW(0, "Connect charger",
                                         "Battery Health", 1)
    elif charge >= 80 and chargerConnected:
        winsound.PlaySound('sound.wav', winsound.SND_FILENAME)
        ctypes.windll.user32.MessageBoxW(0, "Remove charger", "Battery Health",
                                         1)
    time.sleep(2 * 60)
Ejemplo n.º 15
0
def network():
    c = wmi.WMI()
    for interface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1):
        print "MAC: %s" % interface.MACAddress
        return str(interface.MACAddress).replace(":", "-")
Ejemplo n.º 16
0
 def test_process_rss_memory(self):
     time.sleep(0.1)
     w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0]
     p = psutil.Process(self.pid)
     rss = p.memory_info().rss
     self.assertEqual(rss, int(w.WorkingSetSize))
Ejemplo n.º 17
0
#!/usr/bin/python

import wmi
 
conn = wmi.WMI('192.168.1.106', user='******', password='******')
conn.Win32_Process.Create(CommandLine='cmd.exe /c mkdir teeemp')
Ejemplo n.º 18
0
 def test_total_phymem(self):
     w = wmi.WMI().Win32_ComputerSystem()[0]
     self.assertEqual(int(w.TotalPhysicalMemory),
                      psutil.virtual_memory().total)
Ejemplo n.º 19
0
# http://sawbuck.googlecode.com/svn/trunk/sawbuck/py/etw/generate_descriptor.py
# Generate symbols for the WbemScripting module so that we can have symbols
# for debugging and use constants throughout the file.
# Without this, win32com.client.constants is not available.
win32com.client.gencache.EnsureModule('{565783C6-CB41-11D1-8B02-00600806D9B6}',
                                      0, 1, 1)

# Essayer aussi wmi.ProvideConstants

# get the description from an WMI class using vbscript
# http://stackoverflow.com/questions/3978919/get-the-description-from-an-wmi-class-using-vbscript

# How Do I Display the Descriptions for WMI Class Properties Using Vbscript?
# http://stackoverflow.com/questions/22625818/how-do-i-display-the-descriptions-for-wmi-class-properties-using-vbscript?lq=1

wm = wmi.WMI()
pr = wm.Win32_Process

print("")

import pywintypes


def GetWmiClassDescriptionSlow(classNam):
    clsList = [
        c for c in wm.SubclassesOf(
            "", win32com.client.constants.wbemFlagUseAmendedQualifiers)
        if classNam == c.Path_.Class
    ]
    theCls = clsList[0]
    try:
Ejemplo n.º 20
0
time.sleep(1)

changeVol(volume)
volume.SetMasterVolumeLevel(-10.0, None)
voice('HA')
time.sleep(.05)
volume.SetMasterVolumeLevel(-5.0, None)
voice('HA')
time.sleep(.05)
volume.SetMasterVolumeLevel(0.0, None)
voice('HA')
volume.SetMasterVolumeLevel(-10.0, None)

messagebox.showinfo("01101000 01100001 01100011 01101011","Deleting Files...", icon = 'warning')

c = wmi.WMI(namespace = 'wmi')
methods = c.WmiMonitorBrightnessMethods()[0]
methods.WmiSetBrightness(0, 0)
time.sleep(2)

channel = music.stop()
messagebox.askyesno("01100100 01100101 01100001 01110100 01101000","Goodbye?", icon = "question")
time.sleep(3)

methods.WmiSetBrightness(100, 0)
changeVol(volume)
volume.SetMasterVolumeLevel(-10.0, None)
channel = music2.play(loops = -1, maxtime = 0, fade_ms = 4000)
messagebox.showinfo("Prank!","This was all a prank. No damage was done. Don't mess with unknown programs in the future.", icon = "info")
time.sleep(1)
voice('You just got pranked')
Ejemplo n.º 21
0
 def _get_service(self, service_name):
     conn = wmi.WMI(moniker='//./root/cimv2')
     service_list = conn.Win32_Service(Name=service_name)
     if len(service_list):
         return service_list[0]
Ejemplo n.º 22
0
def main():
    IS_WINDOWS = False
    IS_MAC = False

    if 'Windows' in platform.system():
        import wmi
        IS_WINDOWS = True
        w = wmi.WMI(namespace='root\\wmi')
    elif 'Darwin' in platform.system():
        IS_MAC = True

    if not IS_MAC:
        import serial
        # TODO: Dynamically discover the serial device
        # dev/serial/by-id/usb-Kiibohd_Keyboard_-_MDErgo1_PartialMap_pjrcUSB_full_Clean_master_-_2016-02-11_22:56:25_-0800-if02
        # Change to (Serial port - 1) on Windows.
        ser = serial.Serial(serial_port, 115200, timeout=0.5)
        ser.close()
        ser.open()
    else:
        from libs.MacSerial import MacSerial
        ser = MacSerial()

    dox = ErgodoxInterface(ser)

    # Keeping track of Incoming + outgoing net traffic
    l_net = psutil.net_io_counters().bytes_recv \
        + psutil.net_io_counters().bytes_sent
    l_time = time()

    # Get external IP once (Not ideal....)
    # External IP, This may need to be fixed as website changes
    ip = urlopen('http://whatismyip.org').read()
    p = ip.find("font-weight: 600;".encode("utf-8"))
    ip = ip[p + 19:p + 34].strip('</span'.encode("utf-8"))
    ip = ip.decode("utf-8")
    # hostname = socket.gethostname()

    try:
        while True:
            if IS_WINDOWS:
                # Temp of CPU (WINDOWS ONLY, Linux needs to use sensors)
                try:
                    temp = (w.MSAcpi_ThermalZoneTemperature()
                            [0].CurrentTemperature / 10.0) - 273.15
                except BaseException:
                    print('Could not read temp, skipping')
                    temp = 22.0
            else:
                # TODO: fix temperature for linux
                temp = None

            cpu = psutil.cpu_percent(interval=None)  # CPU Usage
            mem = psutil.virtual_memory().percent  # Memory Usage
            disk = psutil.disk_usage('/').percent
            net = ((psutil.net_io_counters().bytes_recv +
                    psutil.net_io_counters().bytes_sent) - l_net) / (
                        time() - l_time)  # Messy, lousy net estimate
            l_time = time()
            l_net = psutil.net_io_counters().bytes_recv \
                + psutil.net_io_counters().bytes_sent

            dox.lcd_hex_color(0x00000C)

            dox.lcd.clear()

            # Show CPU, MEM, etc loading in bar graphs
            y_t = 24
            dox.lcd.format_string("CPU [", 0, y_t)
            dox.lcd.format_string("]", 76, y_t)
            # Represent bar graph for CPU usage (total)
            dox.lcd.format_string("" * int(round(cpu / 10)), 26, y_t)
            if temp:
                dox.lcd.format_string("{0:.0f}".format(temp) + "*C", 82, y_t)
            y_t -= 8
            dox.lcd.format_string(strftime("%m-%d"), 103,
                                  y_t)  # Print date and time
            dox.lcd.format_string("MEM [", 0, y_t)
            dox.lcd.format_string("]", 76, y_t)
            # Represent bar graph for Mem
            dox.lcd.format_string("" * int(round(mem / 10)), 26, y_t)
            y_t -= 8
            dox.lcd.format_string(strftime("%H:%M"), 103,
                                  y_t)  # Print date and time
            dox.lcd.format_string("DSK [", 0, y_t)
            dox.lcd.format_string("]", 76, y_t)
            # Represent bar graph for Disk usage
            dox.lcd.format_string("" * int(round(disk / 10)), 26, y_t)
            y_t -= 8
            dox.lcd.format_string("NET ", 0, y_t)
            dox.lcd.format_string("{0:.1f}".format(net / 1048576) + "M", 24,
                                  y_t)
            dox.lcd.format_string(ip.rjust(15), 53, y_t)

            dox.send()  # Update LCD all at once

    except KeyboardInterrupt:  # Press Ctrl + C to exit
        print('Exit')

    ser.close()
Ejemplo n.º 23
0
 def _get_wmi_obj(self, path):
     return wmi.WMI(moniker=path.replace('\\', '/'))
Ejemplo n.º 24
0
"""
Works from: Windows 10 TH1 (10240)
Fixed in: Windows 10 RS4 (17025)
"""
import os
import wmi
import time
import _winreg
import win32con
from colorama import init, Fore
init(convert=True)

wmi = wmi.WMI()

payload = "c:\\windows\\system32\\cmd.exe"

def successBox():
	return (Fore.GREEN + '[+]' + Fore.RESET)
	
def errorBox():
	return (Fore.RED + '[-]' + Fore.RESET)

def infoBox():
	return (Fore.CYAN + '[!]' + Fore.RESET)	
	
def warningBox():
	return (Fore.YELLOW + '[!]' + Fore.RESET)

def sdclt_isolatedcommand():
	print " {} sdclt_isolatedcommand: Attempting to create registry key".format(infoBox())
	try:
Ejemplo n.º 25
0
 def _init_hyperv_wmi_conn(self, host):
     self._conn = wmi.WMI(moniker='//%s/root/virtualization' % host)
Ejemplo n.º 26
0
class register:
    def __init__(self):
        self.Des_Key = "GBH77522" # Key,长度必须为8位
        self.Des_IV = "\x15\6\x2a\3\1\x23\2\0" # 自定IV向量

        
############ 1. 获取硬件信息,输出 macode
#   1.CPU序列号(ID) 2.本地连接 无线局域网 以太网的MAC 3.硬盘序列号(唯一) 4.主板序列号(唯一)

    global s
    s = wmi.WMI()
#cpu 序列号
    def get_CPU_info(self):
        cpu = []
        cp = s.Win32_Processor()
        for u in cp:
            cpu.append(
                {
                    "Name": u.Name,
                    "Serial Number": u.ProcessorId,
                    "CoreNum": u.NumberOfCores
                }
            )
        print(":::CPU info:", json.dumps(cpu))
        return cpu
#硬盘序列号  
    def get_disk_info(self):
        disk = []
        for pd in s.Win32_DiskDrive():
            disk.append(
                { 
                    "Serial": s.Win32_PhysicalMedia()[0].SerialNumber.lstrip().rstrip(), # 获取硬盘序列号,调用另外一个win32 API
                    "ID": pd.deviceid,
                    "Caption": pd.Caption,
                    "size": str(int(float(pd.Size)/1024/1024/1024))+"G"
                }
            )
        print(":::Disk info:", json.dumps(disk))
        return disk
#mac 地址(包括虚拟机的)
    def get_network_info(self):
        network = []
        for nw in s.Win32_NetworkAdapterConfiguration ():  # IPEnabled=0
            if nw.MACAddress != None:
                network.append(
                    {
                        "MAC": nw.MACAddress,  # 无线局域网适配器 WLAN 物理地址
                        "ip": nw.IPAddress
                    }
                )
        print(":::Network info:", json.dumps(network))
        return network
#主板序列号
    def get_mainboard_info(self):
        mainboard=[]
        for board_id in s.Win32_BaseBoard ():
            mainboard.append(board_id.SerialNumber.strip().strip('.'))
        return mainboard    
    
    #  由于机器码太长,故选取机器码字符串部分字符   
#  E0:DB:55:B5:9C:16BFEBFBFF00040651W3P0VKEL6W8T1Z1.CN762063BN00A8
#  1 61 k 8Z   
#     machinecode_str = ""
#     machinecode_str = machinecode_str+a[0]['MAC']+b[0]['Serial Number']+c[0]['Serial']+d[0]
    def getCombinNumber(self):
        a=self.get_network_info()
        b=self.get_CPU_info()
        c=self.get_disk_info()
        d=self.get_mainboard_info()
        machinecode_str = ""
        machinecode_str = machinecode_str+a[0]['MAC']+b[0]['Serial Number']+c[0]['Serial']+d[0]
        selectindex=[1,4,7,10,12,13,15,17,18,30,32,36,38,43,44,46]
        macode=""
        for i in selectindex:
            macode=macode+machinecode_str[i]
        print(macode)
        return macode


############ 2. 注册登录    
    
#DES+base64加密
    def Encrypted(self,tr):
        k = des(self.Des_Key, CBC, self.Des_IV, pad=None, padmode=PAD_PKCS5)
        EncryptStr = k.encrypt(tr)
        #EncryptStr = binascii.unhexlify(k.encrypt(str))
        print('注册码:',base64.b64encode(EncryptStr))
        return base64.b64encode(EncryptStr) #转base64编码返回
    
#des+base64解码
    def DesDecrypt(self,tr):
        k = des(self.Des_Key, CBC, self.Des_IV, pad=None, padmode=PAD_PKCS5)
        DecryptStr = k.decrypt(tr)
        return base64.b64decode(DecryptStr) #转base64解码返回
    
#获取注册码,验证成功后生成注册文件
    def regist(self):
        key = input('please input your register code: ')
        #由于输入类似“12”这种不符合base64规则的字符串会引起异常,所以需要增加输入判断
        if key:
            ontent = self.getCombinNumber() 
            tent=bytes(ontent, encoding='utf-8')
            content=self.Encrypted(tent)
###            print('content :',content)
###            print(type(content)) 
            key_decrypted=bytes(key, encoding='utf-8')
            if content!=0 and key_decrypted!=0:
                if content != key_decrypted:
                    print("wrong register code, please check and input your register code again:") 
                    self.regist()
                elif content==key_decrypted:
                    print("register succeed.") 
                    #读写文件要加判断
                    with open('register.txt','w') as f:
                        f.write(key)
                        f.close()
                    return True
                else:
                    return False
            else:
                return False
        else:
            self.regist()
            return False
# 打开程序先调用注册文件,比较注册文件中注册码与此时获取的硬件信息编码后是否一致
    def checkAuthored(self):
        ontent = self.getCombinNumber() 
        tent=bytes(ontent, encoding='utf-8')
        content=self.Encrypted(tent)
        #读写文件要加判断
        try:
            f=open('register.txt','r')
            if f:
                    key=f.read()
                    if key:
                        key_decrypted=bytes(key, encoding='utf-8')   # 注册文件中注册码
          ###              print('key_decrypted:',key_decrypted)
          ###              print('content:',content)
                        if key_decrypted:
                            if key_decrypted == content:
                                print("register succeed.") 
                          ##      checkAuthoredResult = 1  # 注册文件与机器码一致
                            else:
                        ##        checkAuthoredResult = -1 # 注册文件与机器码不一致
                                print('未找到注册文件,','请重新输入注册码,','或发送',ontent,'至17695797270','重新获取注册码')
                                self.regist()
                        else:
                     ##       checkAuthoredResult = -2     # 注册文件的注册码不能被解析
                            self.regist()
                            print('未找到注册文件,','请重新输入注册码,','或发送',ontent,'至17695797270','重新获取注册码')
                    else:
               ##         checkAuthoredResult = -3         # 注册文件中不能被读取
                        self.regist()
                        print('未找到注册文件,','请重新输入注册码,','或发送',ontent,'至17695797270','重新获取注册码')
            else:
                self.regist()                            
        except:
            print('请发送',ontent,'至17695797270','获取注册码')
          ##  checkAuthoredResult = 0                      # 未找到注册文件,请重新输入注册码登录
            self.regist()
Ejemplo n.º 27
0
def Main():
    cgiEnv = lib_common.CgiEnv(can_process_remote=True)
    machineName = cgiEnv.GetId()

    grph = cgiEnv.GetGraph()

    if lib_util.IsLocalAddress(machineName):
        machName_or_None = None
        serverBox = lib_common.gUriGen
    else:
        machName_or_None = machineName
        serverBox = lib_common.RemoteBox(machineName)

    try:
        loginImplicit = False  # IF FACT, WHY SHOULD IT BE SET ????????
        if loginImplicit or machName_or_None is None:
            # ESSAYER D UTILISER UNE EVENTUELLE CONNECTION PERSISTENTE ?? Non ca ne marche pas !!!!!
            cnnct = wmi.WMI(machineName)
        else:
            # persistent net connection
            # On a le probleme "access denied" avec tous les acces remote windows.
            # Meme probleme ausis avec WMI alors que ca marchait avant.
            # Comme s'il y avait une connection implicite de rchateau, quand ca marchait, et qu'elle ait disparu maintenant.
            # Toutefois, ceci fonctionne.
            # >>> c = wmi.WMI(wmi=wmi.connect_server(server='Titi', namespace="/root/cimv2", user='******', password='******'))

            sys.stderr.write("Explicit WMI connection machineName=%s\n" %
                             (machineName))

            cnnct = lib_wmi.WmiConnect(machineName, "/root/cimv2")

            #(wmiUser,wmiPass) = lib_credentials.GetCredentials("WMI",machineName)
            #sys.stderr.write("machineName= %wmiUser=%s\n" % ( machineName, wmiUser ) )
            #cnnct = wmi.WMI(wmi=wmi.connect_server(server=machineName, namespace="/root/cimv2", user=wmiUser, password=wmiPass))

    except Exception:
        exc = sys.exc_info()[1]
        lib_common.ErrorMessageHtml("WMI " + machineName + " partitions:" +
                                    str(exc))

    for physical_disk in cnnct.Win32_DiskDrive():
        node_disk = serverBox.DiskUri(physical_disk.Name.replace('\\', '/'))
        grph.add((node_disk, pc.property_information,
                  lib_common.NodeLiteral(physical_disk.MediaType)))

        for partition in physical_disk.associators(
                "Win32_DiskDriveToDiskPartition"):
            for logical_disk in partition.associators(
                    "Win32_LogicalDiskToPartition"):
                # BEWARE: What we call parition is in fact a logical disk.
                # This is not really important for this application,
                # as long as there are two levels in a disk description.
                node_partition = serverBox.DiskPartitionUri(logical_disk.Name)
                grph.add((node_partition, pc.property_information,
                          lib_common.NodeLiteral(logical_disk.Description)))

                grph.add((node_partition, pc.property_file_system_type,
                          lib_common.NodeLiteral(logical_disk.FileSystem)))

                # The logical disk name is the same as the mount point.
                grph.add((node_partition, pc.property_partition, node_disk))
                grph.add((serverBox.DirectoryUri(logical_disk.Name),
                          pc.property_mount, node_partition))

    cgiEnv.OutCgiRdf()
import wmi

c = wmi.WMI()
systeminfo = c.Win32_ComputerSystem()[0]

Manufacturer = systeminfo.Manufacturer
Model = systeminfo.Model
Ejemplo n.º 29
0
def init_wmi(config: Config) -> wmi.WMI:
    privileges = ["Shutdown", "RemoteShutdown"
                  ] if config.allow_shutdown else []
    return wmi.WMI(privileges=privileges)
Ejemplo n.º 30
0
 def test_cpu_count_phys_vs_wmi(self):
     w = wmi.WMI()
     proc = w.Win32_Processor()[0]
     self.assertEqual(psutil.cpu_count(logical=False), proc.NumberOfCores)