Ejemplo n.º 1
0
def runas_shell_user(cmd,
                     executable=None,
                     creationflags=0,
                     cwd=None,
                     startupinfo=None,
                     return_handles=False):
    if not creationflags & win32con.DETACHED_PROCESS:
        creationflags |= win32con.CREATE_NEW_CONSOLE
    if cwd is None:
        cwd = os.getcwd()
    si = _STARTUPINFO()
    if startupinfo:
        startupinfo_update(startupinfo, si)
    pi = PROCESS_INFORMATION()
    try:
        htoken = duplicate_shell_token()
    except pywintypes.error as e:
        if e.winerror != winerror.ERROR_FILE_NOT_FOUND:
            raise
        return runas_session_user(cmd, executable, creationflags, cwd,
                                  startupinfo, return_handles)
    with enable_privileges(win32security.SE_IMPERSONATE_NAME):
        if not advapi32.CreateProcessWithTokenW(
                int(htoken), 0, executable, cmd, creationflags, None, cwd,
                ctypes.byref(si), ctypes.byref(pi)):
            error = ctypes.get_last_error()
            raise pywintypes.error(error, 'CreateProcessWithTokenW',
                                   win32api.FormatMessageW(error))
    hProcess = pywintypes.HANDLE(pi.hProcess)
    hThread = pywintypes.HANDLE(pi.hThread)
    if return_handles:
        return hProcess, hThread
    return pi.dwProcessId, pi.dwThreadId
Ejemplo n.º 2
0
 def testTypes(self):
     with pytest.raises(TypeError):
         pywintypes.HANDLE("foo")
     with pytest.raises(TypeError):
         pywintypes.HANDLE(())
     # should be able to get a long!
     pywintypes.HANDLE(int2long(0))
Ejemplo n.º 3
0
 def testOtherHandle(self):
     h = pywintypes.HANDLE(1)
     h2 = pywintypes.HANDLE(h)
     self.assertEqual(h, h2)
     # but the above doesn't really test everything - we want a way to
     # pass the handle directly into PyWinLong_AsVoidPtr.  One way to
     # to that is to abuse win32api.GetProcAddress() - the 2nd param
     # is passed to PyWinLong_AsVoidPtr() if its not a string.
     # passing a handle value of '1' should work - there is something
     # at that ordinal
     win32api.GetProcAddress(sys.dllhandle, h)
Ejemplo n.º 4
0
 def testHandleCompareNone(self):
     h = pywintypes.HANDLE(1)
     self.assertNotEqual(h, None)
     self.assertNotEqual(None, h)
     # ensure we use both __eq__ and __ne__ ops
     self.assertFalse(h is None)
     self.assertTrue(h is not None)
Ejemplo n.º 5
0
    def pre_spawn_start(self, user, spawner):
        """Load profile for user if so configured"""

        token = None
        profilepath = None

        if not self.open_sessions:
            return
        try:
            loop = asyncio.new_event_loop()
            auth_state = loop.run_until_complete(user.get_auth_state())
            token = pywintypes.HANDLE(auth_state['auth_token'])

            if '@' not in user.name:
                # Check if user has a roaming Profile
                user_info = win32net.NetUserGetInfo(None, user.name, 4)
                profilepath = user_info['profile']

            # Loading the profile will create the USERPROFILE and APPDATA folders,
            # if not present. To load the profile, the running process needs to have
            # the SE_RESTORE_NAME and SE_BACKUP_NAME privileges.
            self._hreg = win32profile.LoadUserProfile(
                token, {'UserName': user.name, 'ProfilePath': profilepath}
            )
        except Exception as exc:
            self.log.warning("Failed to load user profile for %s: %s\n%s", user.name, exc, traceback.format_exc())
        finally:
            if token:
                # Detach so the underlying winhandle stays alive
                token.Detach()
Ejemplo n.º 6
0
def handle(handle):
    if handle is None:
        return None
    elif isinstance(handle, int):
        return Handle(pywintypes.HANDLE(handle))
    else:
        return Handle(handle)
Ejemplo n.º 7
0
 def testHandleCompareNone(self):
     h = pywintypes.HANDLE(1)
     assert h != None
     assert None != h
     # ensure we use both __eq__ and __ne__ ops
     assert not (h is None)
     assert h is not None
Ejemplo n.º 8
0
    def __init__(self, master, canvas_elements, reload_fcn):
        self.master = master
        self.canvas_elements = canvas_elements
        self.reload_fcn = reload_fcn
        self.toplevel = tk.Toplevel(self.master)
        self.label = tk.Label(self.toplevel,
                              text='Climb Rate',
                              font=('Courier New', '14', 'bold'),
                              fg='white',
                              bg='black',
                              justify=tk.LEFT)

        # make HUD transparent, non clickable and always-on-top
        self.toplevel.overrideredirect(True)
        self.toplevel.geometry('+25+500')
        self.toplevel.lift()
        self.toplevel.wm_attributes('-topmost', True)
        self.toplevel.wm_attributes('-disabled', True)
        self.toplevel.wm_attributes('-transparentcolor', 'black')

        self.data_valid = False
        self.was_valid = False

        hWindow = pywintypes.HANDLE(int(self.toplevel.frame(), 16))
        # http://msdn.microsoft.com/en-us/library/windows/desktop/ff700543(v=vs.85).aspx
        # The WS_EX_TRANSPARENT flag makes events (like mouse clicks) fall through the window.
        exStyle = win32con.WS_EX_COMPOSITED | win32con.WS_EX_LAYERED | win32con.WS_EX_NOACTIVATE | win32con.WS_EX_TOPMOST | win32con.WS_EX_TRANSPARENT
        win32api.SetWindowLong(hWindow, win32con.GWL_EXSTYLE, exStyle)

        self.label.pack()
Ejemplo n.º 9
0
    def run(self):
        self.root = Tk()
        self.root.geometry("%dx%d+%d+%d" %
                           (self.width, self.height, self.xpos, self.ypos))
        self.root.protocol('WM_DELETE_WINDOW', self.die)
        self.root.resizable(width=False, height=False)
        self.root.overrideredirect(1)
        self.root.minsize(width=self.width, height=self.height)
        self.root.maxsize(width=self.width, height=self.height)
        self.root.attributes(
            '-alpha',
            0.6,
            '-topmost',
            True,
            '-disabled',
            True,
        )

        self.text = Text(self.root, bg='black', fg='white', state='disabled')
        self.text.configure(font=('Helvetica', 10, 'bold'))
        self.text.pack()
        self.root.lift()

        # tell Windows(tm) to allow clicks to pass through our overlay.
        hWindow = pywintypes.HANDLE(int(self.root.frame(), 16))
        exStyle = win32con.WS_EX_LAYERED | win32con.WS_EX_TRANSPARENT | win32con.WS_EX_NOACTIVATE
        win32api.SetWindowLong(hWindow, win32con.GWL_EXSTYLE, exStyle)

        self.root.mainloop()
def overlay():
    label = tkinter.Label(text="",
                          font=('Times New Roman', f'{tamanhoFonte}'),
                          fg='red',
                          bg='white')
    label.master.overrideredirect(True)

    #change the text position (x and y)
    label.master.geometry("+1875+0")
    label.master.lift()
    label.master.wm_attributes("-topmost", True)
    label.master.wm_attributes("-disabled", True)
    label.master.wm_attributes("-transparentcolor", "white")

    def on_after():
        res = reques()
        label.configure(text=f"{res}")
        label.after(qtd, on_after)

    hWindow = pywintypes.HANDLE(int(label.master.frame(), 16))
    exStyle = win32con.WS_EX_COMPOSITED | win32con.WS_EX_LAYERED | win32con.WS_EX_NOACTIVATE | win32con.WS_EX_TOPMOST | win32con.WS_EX_TRANSPARENT
    win32api.SetWindowLong(hWindow, win32con.GWL_EXSTYLE, exStyle)

    label.pack()
    on_after()
    label.mainloop()
Ejemplo n.º 11
0
    def OpenDynamicChannel(self, channelname, priority):
        # C+Python = OMG...
        global pywintypes
        import ctypes.wintypes
        import ctypes
        import pywintypes
        import win32api

        wts = ctypes.windll.LoadLibrary("Wtsapi32.dll")

        hWTSHandle = wts.WTSVirtualChannelOpenEx(0xFFFFFFFF, channelname,
                                                 0x00000001 | priority)
        if not hWTSHandle:
            common.internal_print(
                "Opening channel failed: {0}".format(win32api.GetLastError()),
                -1)
            return None

        WTSVirtualFileHandle = 1
        vcFileHandlePtr = ctypes.pointer(ctypes.c_int())
        length = ctypes.c_ulong(0)

        if not wts.WTSVirtualChannelQuery(hWTSHandle, WTSVirtualFileHandle,
                                          ctypes.byref(vcFileHandlePtr),
                                          ctypes.byref(length)):
            wts.WTSVirtualChannelClose(hWTSHandle)
            common.internal_print(
                "Channel query: {0}".format(win32api.GetLastError()), -1)
            return None

        common.internal_print("Connected to channel: {0}".format(channelname))

        return pywintypes.HANDLE(vcFileHandlePtr.contents.value)
Ejemplo n.º 12
0
def display_lockscreen_text():
	root = tkinter.Tk()
	root.protocol("WM_DELETE_WINDOW", root.quit)
	label = tkinter.Label(root, text='Computer is Locked', font=('Times New Roman','80'), fg='green', bg='white')
	label.master.overrideredirect(True)
	label.master.geometry("+250+250")
	label.master.lift()
	label.master.wm_attributes("-topmost", True)
	label.master.wm_attributes("-disabled", True)
	label.master.wm_attributes("-transparentcolor", "white")
	hWindow = pywintypes.HANDLE(int(label.master.frame(), 16))
	exStyle = win32con.WS_EX_COMPOSITED | win32con.WS_EX_LAYERED | win32con.WS_EX_NOACTIVATE | win32con.WS_EX_TOPMOST | win32con.WS_EX_TRANSPARENT
	win32api.SetWindowLong(hWindow, win32con.GWL_EXSTYLE, exStyle)
	label.pack()
	while True:
		root.update()
		try:
			with open("match_face_result2", 'rb') as f:
				matched = f.read()
			if matched:
				os.remove('match_face_result2')
				break
		except:
			continue
		if matched:
			break
	root.quit()
Ejemplo n.º 13
0
 def testHandleCompareNone(self):
     h = pywintypes.HANDLE(1)
     self.failIfEqual(h, None)
     self.failIfEqual(None, h)
     # ensure we use both __eq__ and __ne__ ops
     self.failIf(h == None)
     self.failUnless(h != None)
Ejemplo n.º 14
0
    def __init__(self):
        self.win = tkinter.Tk()
        self.var = tkinter.StringVar()
        self.ctr = []
        self.var.set("Fetching data...")

        # change your color here
        self.label = tkinter.Label(self.win,
                                   textvariable=self.var,
                                   font=('Consolas', '11'),
                                   fg='white',
                                   bg='black')
        self.label.master.wm_attributes("-transparentcolor", "black")

        self.label.master.overrideredirect(True)
        self.label.master.lift()
        self.label.master.wm_attributes("-disabled", True)
        res = "+" + str(width) + "+" + str(0)
        self.label.master.geometry(res)

        # if you want always on top, uncomment this line
        # self.label.master.wm_attributes("-topmost", True)

        hWindow = pywintypes.HANDLE(int(self.label.master.frame(), 16))
        exStyle = win32con.WS_EX_COMPOSITED | win32con.WS_EX_LAYERED | win32con.WS_EX_NOACTIVATE | win32con.WS_EX_TOPMOST | win32con.WS_EX_TRANSPARENT
        win32api.SetWindowLong(hWindow, win32con.GWL_EXSTYLE, exStyle)

        self.label.pack()
        self.updater()
        self.label.mainloop()
Ejemplo n.º 15
0
 def run(self):
     #actually this can put in def refresh,to get the remote desktop size
     #and i just set to 4000
     #what? you have a 8k screen,nevermind
     width = 4000  #win32api.GetSystemMetrics(0)
     height = 4000  #win32api.GetSystemMetrics(1)
     self.overrideredirect(True)  #hide the window bounding box
     self.geometry("+0+0")  #set window position or size
     self.lift()  #set window on top
     self.attributes("-alpha", 0.6)  #make watermark transparent
     self.wm_attributes("-topmost", True)  #always set window on top
     self.wm_attributes("-disabled",
                        True)  #disable window,so mouse can not click
     self.wm_attributes(
         "-transparentcolor",
         "white")  #window background set white and transparent
     hwindow = pywintypes.HANDLE(int(self.frame(), 16))
     exStyle = win32con.WS_EX_COMPOSITED | win32con.WS_EX_LAYERED | win32con.WS_EX_NOACTIVATE | win32con.WS_EX_TOPMOST | win32con.WS_EX_TRANSPARENT
     win32api.SetWindowLong(hwindow, win32con.GWL_EXSTYLE, exStyle)
     #set text / font / text color / background color
     label = tkinter.Label(textvariable=self.text,
                           font=("Times New Roman", "40"),
                           fg="#d5d5d5",
                           bg="white")
     label.pack()
     self.withdraw()
     self.procHide = True
     self.refresh()
     self.mainloop()
Ejemplo n.º 16
0
 def testLong(self):
     # sys.maxint+1 should always be a 'valid' handle, treated as an
     # unsigned int, even though it is a long. Although pywin32 should not
     # directly create such longs, using struct.unpack() with a P format
     # may well return them. eg:
     # >>> struct.unpack("P", struct.pack("P", -1))
     # (4294967295L,)
     pywintypes.HANDLE(sys.maxint + 1)
Ejemplo n.º 17
0
def run_win32(app: object) -> object:
    app.lift()

    h_window = pywintypes.HANDLE(int(app.frame(), 16))
    ex_style = win32con.WS_EX_COMPOSITED | win32con.WS_EX_LAYERED | win32con.WS_EX_NOACTIVATE
    win32api.SetWindowLong(h_window, win32con.GWL_EXSTYLE, ex_style)

    return app.mainloop()
Ejemplo n.º 18
0
def isWin64():
    myhandle = pywintypes.HANDLE(win32api.GetCurrentProcess())
    ret = win32process.IsWow64Process(myhandle)
    if ret:
        return True
    else:
        sysInfo = win32api.GetNativeSystemInfo()
    if sysInfo and (sysInfo[0] == 9 or sysInfo[0] == 6):
        return True
    return False
Ejemplo n.º 19
0
 def allocateBuffer(self, xres, yres, buffer_number, num_images=1):
     sBufNum = wintypes.SHORT(buffer_number)
     dwSize = wintypes.DWORD(2 * xres * yres * num_images)
     wBuffer = np.zeros((xres * yres * num_images), dtype=np.uint16)
     hEvent1 = wintypes.HANDLE()
     hEvent2 = pywintypes.HANDLE()  #
     err = self.f_allocate(self.hcam, byref(sBufNum), dwSize,
                           addressof(c_void_p(wBuffer.ctypes.data)),
                           byref(hEvent1))
     return (err, hEvent1, wBuffer)
Ejemplo n.º 20
0
 def testHandleCompareInt(self):
     h = pywintypes.HANDLE(1)
     assert h != 0
     assert h == 1
     # ensure we use both __eq__ and __ne__ ops
     assert h == 1
     assert 1 == h
     assert not (h != 1)
     assert not (1 != h)
     assert not (h == 0)
     assert not (0 == h)
     assert h != 0
     assert 0 != h
Ejemplo n.º 21
0
 def testInvalid(self):
     h = pywintypes.HANDLE(-2)
     try:
         h.Close()
         # Ideally, we'd:
         #     self.assertRaises(win32api.error, h.Close)
         # and everywhere markh has tried, that would pass - but not on
         # github automation, where the .Close apparently works fine.
         # (same for -1. Using 0 appears to work fine everywhere)
         # There still seems value in testing it though, so we just accept
         # either working or failing.
     except win32api.error:
         pass
Ejemplo n.º 22
0
    def test_should_return_not_running_if_failed_to_open_process(
            self, func_open_process):
        """Tests error handling wehn OpenProcess return 0 handle

        Checks is_process_running and wait_for_process_exit works
        even if OpenProcess returns 0 handle without exception
        """
        func_open_process.return_value = pywintypes.HANDLE(0)
        app = Application()
        app.start(_notepad_exe())
        app.wait_for_process_exit(timeout=10, retry_interval=1)
        self.assertFalse(app.is_process_running())
        app.kill()
Ejemplo n.º 23
0
 def testHandleCompareInt(self):
     h = pywintypes.HANDLE(1)
     self.failIfEqual(h, 0)
     self.failUnlessEqual(h, 1)
     # ensure we use both __eq__ and __ne__ ops
     self.failUnless(h == 1)
     self.failUnless(1 == h)
     self.failIf(h != 1)
     self.failIf(1 != h)
     self.failIf(h == 0)
     self.failIf(0 == h)
     self.failUnless(h != 0)
     self.failUnless(0 != h)
Ejemplo n.º 24
0
 def testHandleCompareInt(self):
     h = pywintypes.HANDLE(1)
     self.assertNotEqual(h, 0)
     self.assertEqual(h, 1)
     # ensure we use both __eq__ and __ne__ ops
     self.assertTrue(h == 1)
     self.assertTrue(1 == h)
     self.assertFalse(h != 1)
     self.assertFalse(1 != h)
     self.assertFalse(h == 0)
     self.assertFalse(0 == h)
     self.assertTrue(h != 0)
     self.assertTrue(0 != h)
Ejemplo n.º 25
0
def run_win32(app: object) -> object:
    """
    set window to no having focus for this window.
    if this window get focus, cannot use WM_QUIT to target foreground window

    :param app:
    :return: None
    """
    app.lift()

    app.h_wnd = pywintypes.HANDLE(int(app.frame(), 16))
    ex_style = win32con.WS_EX_COMPOSITED | win32con.WS_EX_LAYERED | win32con.WS_EX_NOACTIVATE
    win32api.SetWindowLong(app.h_wnd, win32con.GWL_EXSTYLE, ex_style)

    return app.mainloop()
Ejemplo n.º 26
0
def aimactivate():
    label = Tkinter.Label(text='Aimbot Activated', font=('Times New Roman','20'), fg='Blue', bg='white')
    label.master.overrideredirect(True)
    label.master.geometry("+20+50")
    label.master.lift()
    label.master.wm_attributes("-topmost", True)
    label.master.wm_attributes("-disabled", True)
    label.master.wm_attributes("-transparentcolor", "white")

    hWindow = pywintypes.HANDLE(int(label.master.frame(), 16))
    # http://msdn.microsoft.com/en-us/library/windows/desktop/ff700543(v=vs.85).aspx
    # The WS_EX_TRANSPARENT flag makes events (like mouse clicks) fall through the window.
    exStyle = win32con.WS_EX_COMPOSITED | win32con.WS_EX_LAYERED | win32con.WS_EX_NOACTIVATE | win32con.WS_EX_TOPMOST | win32con.WS_EX_TRANSPARENT
    win32api.SetWindowLong(hWindow, win32con.GWL_EXSTYLE, exStyle)

    label.pack()
    label.mainloop()
Ejemplo n.º 27
0
def createOverlay(in_q):
    root = tkinter.Tk()

    screen_width = root.winfo_screenwidth()

    def update_label():
        if len(list(in_q.queue)):
            retCode = in_q.get()
            if retCode[1]:
                if retCode[0]:
                    text = "Bot: Active"
                else:
                    text = "Bot: Disabled"
                #print(text)
            else:
                text = ''
            overlay_text.set(text)
            label.update_idletasks()
            top = 0
            left = str(screen_width - label.winfo_reqwidth())
            label.master.geometry("+%s+%s" % (left, top))
        root.after(500, update_label)

    overlay_text = tkinter.StringVar()
    overlay_text.set("Bot: Disabled")
    label = tkinter.Label(textvariable=overlay_text,
                          font=('Arial', '12'),
                          fg='white',
                          bg='black')
    top = 0
    left = str(screen_width - label.winfo_reqwidth())
    label.master.geometry("+%s+%s" % (left, top))
    label.master.overrideredirect(True)
    label.master.lift()
    label.master.wm_attributes('-transparentcolor', 'black')
    label.master.wm_attributes("-topmost", True)
    label.master.wm_attributes("-disabled", True)
    hWindow = pywintypes.HANDLE(int(label.master.frame(), 16))
    # The WS_EX_TRANSPARENT flag makes events (like mouse clicks) fall through the window.
    exStyle = win32con.WS_EX_COMPOSITED | win32con.WS_EX_LAYERED | win32con.WS_EX_NOACTIVATE | win32con.WS_EX_TOPMOST | win32con.WS_EX_TRANSPARENT
    win32api.SetWindowLong(hWindow, win32con.GWL_EXSTYLE, exStyle)
    label.pack()

    update_label()
    root.mainloop()
Ejemplo n.º 28
0
    def post_spawn_stop(self, user, spawner):
        """Unload profile for user if we were configured to opened one"""

        token = None

        if not self.open_sessions:
            return
        try:
            loop = asyncio.new_event_loop()
            auth_state = loop.run_until_complete(user.get_auth_state())
            token = pywintypes.HANDLE(auth_state['auth_token'])
            win32profile.UnloadUserProfile(token, self._hreg)
        except Exception as exc:
            self.log.warning("Failed to unload user profile for %s: %s", user.name, exc)
        finally:
            if token:
                # Detach so token stays valid
                token.Detach()
Ejemplo n.º 29
0
    async def refresh_user(self, user, handler=None):
        """Refresh auth data for a given user
        Allows refreshing or invalidating auth data.

        Args:
            user (User): the user to refresh
            handler (tornado.web.RequestHandler or None): the current request handler
        Returns:
            auth_data (bool):
                Return **True** if auth data for the user is up-to-date
                and no updates are required.
                Return **False** if the user's auth data has expired,
                and they should be required to login again.
                WinAuthenticator's implementation never returns a dict.
        """

        token = None

        if not self.open_sessions:
            return True
        try:
            auth_state = await user.get_auth_state()
            if not auth_state:
                return False  # Stale auth state, will ask user to re-login
            token = pywintypes.HANDLE(auth_state['auth_token'])

            # Check token validity
            _ = win32security.GetTokenInformation(
                token, win32security.TokenType
            )
            # If we're here, the token is valid and we just go to the finally clause
        except pywintypes.error as err:
            # If it's an expired user token, no warning.
            if err.winerror != winerror.ERROR_INVALID_HANDLE:
                self.log.warning("Failed to check auth state and token for %s: %s\n%s", user.name, exc, traceback.format_exc())
            if token:
                # Detach so the underlying winhandle stays alive
                token.Detach()
            return False
        finally:
            if token:
                # Detach so the underlying winhandle stays alive
                token.Detach()
        return True
Ejemplo n.º 30
0
def ttsx(param, fontx, fgx, bgx):
    global status
    status = False
    label = tkinter.Label(text=param,
                          font=('Times New Roman', str(fontx)),
                          fg=fgx,
                          bg=bgx)
    label.master.overrideredirect(True)
    label.master.geometry("+250+250")
    label.master.lift()
    label.master.wm_attributes("-topmost", True)
    label.master.wm_attributes("-disabled", True)
    label.master.wm_attributes("-transparentcolor", "white")
    hWindow = pywintypes.HANDLE(int(label.master.frame(), 16))
    # http://msdn.microsoft.com/en-us/library/windows/desktop/ff700543(v=vs.85).aspx
    # The WS_EX_TRANSPARENT flag makes events (like mouse clicks) fall through the window.
    exStyle = win32con.WS_EX_COMPOSITED | win32con.WS_EX_LAYERED | win32con.WS_EX_NOACTIVATE | win32con.WS_EX_TOPMOST | win32con.WS_EX_TRANSPARENT
    win32api.SetWindowLong(hWindow, win32con.GWL_EXSTYLE, exStyle)
    label.pack()
    label.mainloop()
    time.sleep(2)
    label.quit()