def __enter__(self): d = self.__d if not d.privileges: dwarn( "failed to elevate privilege. This is might be a Windows XP machine" ) return # See: http://msdn.microsoft.com/ja-jp/library/windows/desktop/ms724944%28v=vs.85%29.aspx # See: http://nullege.com/codes/search/win32security.AdjustTokenPrivileges # See: http://www.oschina.net/code/explore/chromium.r67069/third_party/python_24/Lib/site-packages/win32/Demos/security/setkernelobjectsecurity.py #pid = win32api.GetCurrentProcessId() #ph = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, 0, pid) ph = win32api.GetCurrentProcess() #d.token = win32security.OpenProcessToken(ph, win32con.TOKEN_ALL_ACCESS) d.token = win32security.OpenProcessToken( ph, win32con.TOKEN_ADJUST_PRIVILEGES | win32con.TOKEN_QUERY) d.privileges = win32security.AdjustTokenPrivileges( d.token, 0, d.privileges) if win32api.GetLastError(): dwarn("failed to elevate process privilege") else: dprint("process privileges elevated") return self
def settext(text): """ @param text unicode or str @return bool """ # FIXME: Need to set clipboard format to UTF8 #text = text.encode('sjis', errors='ignore') u16 = isinstance(text, unicode) ret = True if skwinapi.OpenClipboard(0): # hwnd = 0 if skwinapi.EmptyClipboard(): # clipboard must be emptied first size = len(text) size1 = size + 1 if u16: size *= 2 size1 *= 2 data = text if u16 else text hCd = skwinapi.GlobalAlloc( win32con.GMEM_DDESHARE | win32con.GMEM_ZEROINIT, size1) pchData = skwinapi.GlobalLock(hCd) if pchData: #msvcrt.strcpy(ctypes.c_char_p(pchData), bytes(data)) msvcrt.memcpy(pchData, data, size) # http://www.codeexperts.com/showthread.php?1420-crash-while-writing-unicode-data-to-clipboard-using-SetClipboardData skwinapi.GlobalUnlock(hCd) fmt = win32con.CF_UNICODETEXT if u16 else win32con.CF_TEXT ret = bool(skwinapi.SetClipboardData(fmt, hCd)) skwinapi.CloseClipboard() if not ret: dwarn("clipboard busy") return ret
def enable_drop_event(hwnd=None): """ @return bool Always return true on Windows XP. See: http://helgeklein.com/blog/2010/03/how-to-enable-drag-and-drop-for-an-elevated-mfc-application-on-vistawindows-7/ // ChangeWindowMessageFilter typedef BOOL (WINAPI *PFN_CHANGEWINDOWMESSAGEFILTER) (UINT, DWORD); HMODULE hModule = GetModuleHandle (TEXT(“user32.dll”)); PFN_CHANGEWINDOWMESSAGEFILTER pfnChangeWindowMessageFilter = (PFN_CHANGEWINDOWMESSAGEFILTER) GetProcAddress (hModule, “ChangeWindowMessageFilter”); Then you can use it like this: (*pfnChangeWindowMessageFilter) (WM_DROPFILES, MSGFLT_ADD); """ ret = False wms = win32con.WM_DROPFILES, win32con.WM_COPYDATA, skwinapi.WM_COPYGLOBALDATA try: if hwnd: # http://answers.microsoft.com/en-us/windows/forum/windows_7-files/file-drag-n-drop-via-wmdropfiles-doesnt-work-in/d172ed8c-1a5b-e011-8dfc-68b599b31bf5?msgId=2e77dbec-495b-e011-8dfc-68b599b31bf5 ret = not skwinapi.ChangeWindowMessageFilterEx or all( skwinapi.ChangeWindowMessageFilterEx( hwnd, it, skwinapi.MSGFLT_ALLOW, 0) for it in wms) else: # http://answers.microsoft.com/en-us/windows/forum/windows_7-files/file-drag-n-drop-via-wmdropfiles-doesnt-work-in/d172ed8c-1a5b-e011-8dfc-68b599b31bf5?msgId=2e77dbec-495b-e011-8dfc-68b599b31bf5 ret = not skwinapi.ChangeWindowMessageFilter or all( skwinapi.ChangeWindowMessageFilter(it, skwinapi.MSGFLT_ADD) for it in wms) except Exception, e: dwarn(e)
def injectfunc1(addr, arg, argsize, pid=0, handle=None, timeout=INJECT_TIMEOUT): """Inject function with 1 argument Either pid or the process handle should be specified @param addr LONG function memory address @param arg LPVOID @param argsize int @param pid LONG @param handle HANDLE @param timeout int msecs @return bool """ dprint("enter: pid = %s" % pid) isLocalHandle = False # bool if not handle and pid: isLocalHandle = True try: handle = win32api.OpenProcess(PROCESS_INJECT_ACCESS, 0, pid) if not handle: with SkProcessElevator(SE_DEBUG_PRIVILEGE) as priv: if priv.isElevated(): handle = win32api.OpenProcess( PROCESS_INJECT_ACCESS, 0, pid) except Exception, e: dwarn("windows error:", e)
def install_msi_normal(path): # unicode -> bool try: import skproc return bool(skproc.detachgui(['msiexec.exe', '/i', path])) except Exception, e: dwarn(e) return False
def injectdll(dllpath, pid=0, handle=None, timeout=INJECT_TIMEOUT): """Either pid or the process handle should be specified @param dllpath unicode ABSOLUTE path to dll @param pid LONG @param handle HANDLE @param timeout int msecs @return bool """ #if not dllpath or not os.path.exists(dllpath): # dwarn("error: dll does not exist") # return False dprint("enter: pid = %s" % pid) try: dllpath = dllpath.decode('utf8') except UnicodeDecodeError: dwarn("exit: error: failed to decode dll path to utf8") return False LOADLIBRARYW = getModuleFunctionAddress('LoadLibraryW', 'kernel32.dll') if not LOADLIBRARYW: dprint("exit error: cannot find LoadLibraryW from kernel32") return False data = dllpath dataSize = len(dllpath) * 2 + 2 # L'\0' ok = injectfunc1(LOADLIBRARYW, data, dataSize, pid=pid, handle=handle, timeout=timeout) dprint("exit: ret = ok") return ok
def create_process(path, params=None, environ=None, unicode_environ=True, suspended=False, complete=False): """ @param path unicode path to executable @param* params [unicode param] or None @param* environ A dictionary/tuple of string/unicode or None to inherit the current environment. @param* unicode_environ bool if env contains unicode string @param* suspended bool whether CREATE_SUSPENDED @param* complete bool whether return everything @return long pid if not complete else (hProcess, hThread, dwProcessId, dwThreadId) """ assert path, "path does not exist" path = path.replace('/', '\\') # to native path exe = path cmdline = None pwd = os.path.dirname(path) or None if environ: e = os.environ.copy() e.update(environ) if not unicode_environ: environ = e else: try: environ = { unicode(k): unicode(v) for k, v in e.iteritems() } except UnicodeDecodeError, e: dwarn(e) environ = None
def elevate(path, args): # str, str try: quoted = ' '.join(("%s" % it for it in args)) shell().ShellExecute(path, quoted, '', 'runas') return True except Exception, e: dwarn(e) return False
def open_cpl(path): # unicode -> bool # http://stackoverflow.com/questions/19508268/how-to-open-control-panel-in-python-using-win32-extension try: import skproc return bool(skproc.detachgui(['control.exe', path])) except Exception, e: dwarn(e) return False
def isascii(s): try: s.decode('ascii') return True except UnicodeDecodeError: return False except Exception, e: dwarn(e) return False
def makedirs(path): try: if not os.path.exists(path): os.makedirs(path) return True #except OSError: except Exception: dwarn("failed to create directory: %s" % path) return False
def bind(self): for obj, pty in self.__d.properties: try: val = getattr(obj, pty) valChanged = getattr(obj, pty + 'Changed') obj.destroyed.connect(partial(self.removeObject, obj)) valChanged.connect(self.__d.setValue) except AttributeError: dwarn("failed to bind properties", obj, val)
def set_app_id(name): """ @param unicode @return bool """ try: return 0 == skwinapi.SetCurrentProcessExplicitAppUserModelID(name) except Exception, e: dwarn(e) return False
def to_short_path(path): """ @param path unicode @return unicode or "" if not exists """ try: return win32api.GetShortPathName(path) except Exception, e: dwarn(e) return ""
def is_process_active(pid): """ @param pid ulong @return bool """ if skos.WIN: # on mac, pid can be zero import skwin return bool(pid) and skwin.is_process_active(pid) else: dwarn("unimplemented") return False
def getdata(url, **kwargs): """ @param url str @return str data or None """ try: res = _getres(url, **kwargs) if res: return res.content except Exception, e: derror(e) dwarn("failed URL: %s" % url)
def get_display_resolution(display=None): """ @return (int w, int h) not None """ try: if not display: display = get_display() return display.PelsWidth, display.PelsHeight except Exception, e: dwarn(e) return 0, 0
def __exit__(self, *err): d = self.__d if d.token: if d.privileges is not None: win32security.AdjustTokenPrivileges( d.token, 0, d.privileges) try: win32api.CloseHandle(d.token) except Exception, e: dwarn("windows error:", e) d.token = None
def resume_thread(hThread): """ @param hThread HANDLE @return bool """ try: return win32process.ResumeThread(hThread) >= 0 #except pywintypes.error, e: except Exception, e: dwarn(e) return False
def get_display(id=0): """ @param* id int @return DisplaySettings or None """ try: dev = win32api.EnumDisplayDevices(DevNum=id) return win32api.EnumDisplaySettings(dev.DeviceName, win32con.ENUM_CURRENT_SETTINGS) except Exception, e: dwarn(e)
def get_link_target_wsh(path): """ @param path unicode shortcut file location Wreturn unicode or None Note: though returning unicode, the characters are illegal. """ try: return wsh().CreateShortcut(path).Targetpath #except Exception, e: dwarn(e) except Exception, e: dwarn(e)
def extractzip(path, location): # unicode, unicode -> bool """ @param path unicode @param location unicode @return bool """ import zipfile try: with zipfile.ZipFile(path, 'r') as z: z.extractall(location) return True except Exception, e: dwarn(e)
def readfile(path, mode='r'): """ @param path str @param mode str 'r' or 'rb' @return unicode or "" """ try: with open(path, mode) as f: return f.read() except IOError: pass except UnicodeDecodeError, e: dwarn(e) except Exception, e: dwarn(e) return ""
def itergetdata(url, chunksize=1024, **kwargs): """ @param url str @param path str @param mode str 'w' or 'wb' @return iter(str) or None """ try: res = _getres(url, stream=True, **kwargs) if res: return res.iter_content(chunk_size=chunksize) except Exception, e: derror(e) dwarn("failed URL: %s" % url)
def extract7z(path, location): # unicode, unicode -> bool """ @param path unicode @param location unicode @return bool """ import py7zlib # could be found in pylzma from pip try: with open(path, 'rb') as fp: z = py7zlib.Archive7z(fp) extract7zarchive(z, location) return True except Exception, e: dwarn(e)
def is_taskbar_autohide(align='b'): """ @param align 'l', 'r', 't', or 'b' """ abd = skwinapi.APPBARDATA( uEdge=TASKBAR_EDGES.get(align) or shellcon.ABE_BOTTOM) abd.cbSize = ctypes.sizeof(abd) try: return bool( skwinapi.SHAppBarMessage(shellcon.ABM_GETAUTOHIDEBAR, ctypes.byref(abd))) except Exception, e: dwarn(e) return False
def kill_process(pid, ret=0): """ @param pid long @return bool """ ret = False try: # http://snipplr.com/view/60057/ h = win32api.OpenProcess(win32con.PROCESS_TERMINATE, False, pid) if h: ret = win32api.TerminateProcess(h, ret) win32api.CloseHandle(h) except Exception, e: dwarn(e)
def extracttar(path, location, mode='r'): # unicode, unicode -> bool """ @param path unicode @param location unicode @param* mode str @return bool """ import tarfile try: #with tarfile.TarFile(path) as z: # without extraction with tarfile.open(path, mode) as z: z.extractall(location) return True except Exception, e: dwarn(e)
def get_taskbar_rect(hwnd=None): """ @param hwnd HWND @return (left, top, right, bottom) not None """ abd = skwinapi.APPBARDATA(hWnd=hwnd or get_taskbar_window()) abd.cbSize = ctypes.sizeof(abd) try: ok = skwinapi.SHAppBarMessage(shellcon.ABM_GETTASKBARPOS, ctypes.byref(abd)) if ok: r = abd.rc return r.left, r.top, r.right, r.bottom except Exception, e: dwarn(e)
def writefile(path, data, mode='w'): """ @param path str @param data str @param mode str 'w' or 'wb' @return bool """ try: with open(path, mode) as f: f.write(data) return True except IOError: pass except UnicodeEncodeError, e: dwarn(e) except Exception, e: dwarn(e) return False