Esempio n. 1
0
File: test.py Progetto: zhichaoh/ope
def getDesktopWindow():
    console_id = win32ts.WTSGetActiveConsoleSessionId()
    if console_id == 0xffffffff:
        # User not logged in right now?
        logging.info("No console user")
        return None

    hwnd = None

    # Get processes running on this console
    svr = win32ts.WTSOpenServer(".")
    ps_list = win32ts.WTSEnumerateProcesses(svr, 1, 0)
    for ps in ps_list:
        logging.info("PS " + str(ps))
    win32ts.WTSCloseServer(svr)
    # sessions = win32ts.WTSEnumerateSessions(None, 1, 0)
    # for session in win32ts.WTSEnumerateSessions(win32ts.WTS_CURRENT_SERVER_HANDLE, 1, 0):
    #         print "SessionId: %s" % session['SessionId']
    #         print "\tWinStationName: %s" % session['WinStationName']
    #         print "\tState: %s" % session['State']
    #         print
    #         if session["WinStationName"] == "Console":
    #             cs = session

    #if cs is not None:
    #    # Get process list for this session
    return hwnd
Esempio n. 2
0
def reListSessions(outFh):
    protocols = {
        ts.WTS_PROTOCOL_TYPE_CONSOLE: "console",
        ts.WTS_PROTOCOL_TYPE_ICA: "citrix",
        ts.WTS_PROTOCOL_TYPE_RDP: "rdp",
    }

    #hostname = api.GetComputerName()
    hserver = ts.WTS_CURRENT_SERVER_HANDLE

    currentSessId = ts.WTSGetActiveConsoleSessionId()

    format = "%(user)-16s %(active)1s%(session)-7s %(id)-7s %(protocol)-8s"
    print >> outFh, format % dict(
        user="******",
        active="",
        session="SESSION",
        id="ID",
        protocol="PROTOCOL",
    )

    for session in ts.WTSEnumerateSessions(hserver):
        sessionId = session["SessionId"]
        session["User"] = ts.WTSQuerySessionInformation(
            hserver, sessionId, ts.WTSUserName)
        #session["Address"] = ts.WTSQuerySessionInformation(hserver, sessionId, ts.WTSClientAddress)
        session["Protocol"] = ts.WTSQuerySessionInformation(
            hserver, sessionId, ts.WTSClientProtocolType)
        print >> outFh, format % dict(
            user=session["User"] or "(none)",
            session=session["WinStationName"],
            id="(%d)" % session["SessionId"],
            active="*" if sessionId == currentSessId else "",
            protocol=protocols[session["Protocol"]],
        )
Esempio n. 3
0
def wts_msgbox(msg, title="提示", style=0, timeout=0, wait=False):
	# 这个函数支持在服务程序里弹出对话框
	import win32ts
	sid = win32ts.WTSGetActiveConsoleSessionId()
	if sid != 0xffffffff:
		ret = win32ts.WTSSendMessage(win32ts.WTS_CURRENT_SERVER_HANDLE,
									 sid, title, msg, style, timeout, wait)
		return ret
Esempio n. 4
0
 def create_print_process(self):
     session_id = win32ts.WTSGetActiveConsoleSessionId()
     user_token = win32ts.WTSQueryUserToken(session_id)
     startup_info = win32process.STARTUPINFO()
     cmdline = "E:\\python_project\\happyWorkAutoPrint\\dist\\autoPrint\\autoPrint.exe"
     win32process.CreateProcessAsUser(user_token, None, cmdline, None, None,
                                      False, win32con.NORMAL_PRIORITY_CLASS,
                                      None, None, startup_info)
Esempio n. 5
0
 def runProcessInteractWithUser(self):
     hToken = win32security.OpenProcessToken(
         win32api.GetCurrentProcess(),
         win32con.TOKEN_DUPLICATE | win32con.TOKEN_ADJUST_DEFAULT
         | win32con.TOKEN_QUERY | win32con.TOKEN_ASSIGN_PRIMARY)
     hNewToken = win32security.DuplicateTokenEx(
         hToken, win32security.SecurityImpersonation,
         win32security.TOKEN_ALL_ACCESS, win32security.TokenPrimary)
     # Create sid level
     sessionId = win32ts.WTSGetActiveConsoleSessionId()
     win32security.SetTokenInformation(hNewToken,
                                       win32security.TokenSessionId,
                                       sessionId)
     priority = win32con.NORMAL_PRIORITY_CLASS | win32con.CREATE_NEW_CONSOLE
     startup = win32process.STARTUPINFO()
     handle, thread_id, pid, tid = win32process.CreateProcessAsUser(
         hNewToken, self.filePath, None, None, None, False, priority, None,
         None, startup)
Esempio n. 6
0
    def runScreenShotApp2_old(self):
        console_id = win32ts.WTSGetActiveConsoleSessionId()
        if console_id == 0xffffffff:
            # User not logged in right now?
            logging.info("No console user")
            return None

        dc = None

        logging.info("Got console: " + str(console_id))

        # Get processes running on this console
        svr = win32ts.WTSOpenServer(".")
        user_token = win32ts.WTSQueryUserToken(console_id)
        logging.info("User Token " + str(user_token))

        # hwnd = win32gui.GetDC(win32con.HWND_DESKTOP)  # win32gui.GetDesktopWindow()
        # dc = ctypes.windll.user32.GetDC(win32con.HWND_DESKTOP)
        # logging.info("DC before impersonation " + str(dc))
        # win32gui.ReleaseDC(win32con.HWND_DESKTOP, dc)

        # Switch to the user
        win32security.ImpersonateLoggedOnUser(user_token)
        logging.info("Impersonating " + win32api.GetUserName())

        app_path = os.path.dirname(
            os.path.dirname(
                os.path.dirname(os.path.dirname(os.path.realpath(__file__)))))
        cmd = os.path.join(app_path, "sshot\\dist\\sshot.exe")
        logging.info("Running sshot app " + cmd)
        logging.info(os.system(cmd))

        # hwnd = ctypes.windll.user32.GetDC(win32con.HWND_DESKTOP)
        # logging.info("HWND after impersonation " + str(hwnd))
        # ps_list = win32ts.WTSEnumerateProcesses(svr, 1, 0)
        # for ps in ps_list:
        #    logging.info("PS " + str(ps))
        win32ts.WTSCloseServer(svr)

        # Revert back to normal user
        win32security.RevertToSelf()
        user_token.close()

        return
Esempio n. 7
0
    def runScreenShotApp3_old(self):
        # Get the current security token
        token = win32security.OpenProcessToken(
            win32process.GetCurrentProcess(), win32security.TOKEN_ALL_ACCESS)

        # Make a copy
        #token2 = win32security.DuplicateToken(token)
        token2 = win32security.DuplicateTokenEx(
            token, win32security.SecurityImpersonation,
            win32security.TOKEN_ALL_ACCESS, win32security.TokenPrimary)

        # Find the session id - we will grab the console/keyboard
        #proc_id = win32process.GetCurrentProcessId()
        #session_id = win32ts.ProcessIdToSessionId(proc_id)
        session_id = win32ts.WTSGetActiveConsoleSessionId()

        # Make this token target our session
        win32security.SetTokenInformation(token2, win32security.TokenSessionId,
                                          session_id)
Esempio n. 8
0
def Connect(id):
    current = Ts.WTSGetActiveConsoleSessionId()
    if current == id:
        print "Already connected to session %d." % id
        return True  # because we *are* connected to the requested session
    domain, user = GetUsername(id)
    target = "%s\\%s" % (domain, user)
    target, passwd, persist = GetPassword(target)
    domain, user = Cred.CredUIParseUserName(target)

    print ` domain `, ` user `, ` passwd `
    try:
        Wts.winstation.Connect(None, id, None, passwd, True)
    except Wts.Win32Error as e:
        print "[%s] %s" % (e.err, e.message)
        if e.args[0] == 1326:
            Cred.CredUIConfirmCredentials(target, False)
        return False
    else:
        Cred.CredUIConfirmCredentials(target, True)
        return True
Esempio n. 9
0
    def get_student_login_sessions():
        # Get a list of students that are logged in
        ret = []

        # Get the current user name
        curr_user = win32api.GetUserName()
        if UserAccounts.is_user_in_group(curr_user, "OPEStudents"):
            ret.append(curr_user)

        # Get the list of users from WTS
        wts_sessions = []
        sessions = win32ts.WTSEnumerateSessions(None, 1, 0)

        for session in sessions:
            # Ignore listen status(no user for that), all others query
            if session['State'] == UserAccounts.WTSActive or \
                session['State'] == UserAccounts.WTSDisconnected or \
                session['State'] == UserAccounts.WTSConnected:
                # Found the active session
                #active_session = session['SessionId']
                #station_name = session["WinStationName"]
                wts_sessions.append(session['SessionId'])

        # Get the console session (duplicate?)
        active_session = win32ts.WTSGetActiveConsoleSessionId()
        if active_session is not None and active_session != UserAccounts.WTS_INVALID_SESSION_ID:
            wts_sessions.append(active_session)

        # Convert sessions to users and check their group membership
        for session in wts_sessions:
            user_name = win32ts.WTSQuerySessionInformation(
                None, session, win32ts.WTSUserName)
            if user_name is not None and user_name != "":
                if UserAccounts.is_user_in_group(user_name, "OPEStudents"):
                    ret.append(user_name)

        return ret
Esempio n. 10
0
    def runScreenShotApp(self):
        global DISABLE_SSHOT
        if DISABLE_SSHOT is True:
            return

        # Get the session id for the console
        session_id = win32ts.WTSGetActiveConsoleSessionId()
        if session_id == 0xffffffff:
            # User not logged in right now?
            logging.info("No console user")
            return None

        # logging.info("Got Console: " + str(session_id))

        # Login to the terminal service to get the user token for the console id
        svr = win32ts.WTSOpenServer(".")
        user_token = win32ts.WTSQueryUserToken(session_id)
        # logging.info("User Token " + str(user_token))

        # Copy the token
        user_token_copy = win32security.DuplicateTokenEx(
            user_token, win32security.SecurityImpersonation,
            win32security.TOKEN_ALL_ACCESS, win32security.TokenPrimary)

        # Put this token in the logged in session
        win32security.SetTokenInformation(user_token_copy,
                                          win32security.TokenSessionId,
                                          session_id)

        # Switch to the user
        # win32security.ImpersonateLoggedOnUser(user_token)
        # logging.info("Impersonating " + win32api.GetUserName())

        # Run the screen shot app
        # app_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))))
        # cmd = os.path.join(app_path, "sshot\\dist\\sshot.exe")
        cmd = os.path.join(ROOT_FOLDER, "ope_laptop_binaries\\sshot\\sshot.exe"
                           )  # "c:\\programdata\\ope\\bin\\sshot.exe"
        # cmd = "cmd.exe"
        logging.info("Running sshot app " + cmd)

        # Use win create process function
        si = win32process.STARTUPINFO()
        si.dwFlags = win32process.STARTF_USESHOWWINDOW
        si.wShowWindow = win32con.SW_NORMAL
        # si.lpDesktop = "WinSta0\Default"
        si.lpDesktop = ""

        # Setup envinroment for the user
        environment = win32profile.CreateEnvironmentBlock(user_token, False)

        try:
            (
                hProcess, hThread, dwProcessId, dwThreadId
            ) = win32process.CreateProcessAsUser(
                user_token_copy,
                None,  # AppName (really command line, blank if cmd line supplied)
                "\"" + cmd + "\"",  # Command Line (blank if app supplied)
                None,  # Process Attributes
                None,  # Thread Attributes
                0,  # Inherits Handles
                win32con.
                NORMAL_PRIORITY_CLASS,  # or win32con.CREATE_NEW_CONSOLE,
                environment,  # Environment
                os.path.dirname(cmd),  # Curr directory
                si)  # Startup info

            # logging.info("Process Started: " + str(dwProcessId))
            # logging.info(hProcess)
        except Exception as e:
            logging.info("Error launching process: " + str(e))

        # logging.info(os.system(cmd))

        # Return us to normal security
        # win32security.RevertToSelf()

        # Cleanup
        win32ts.WTSCloseServer(svr)
        user_token.close()
        user_token_copy.close()

        return
Esempio n. 11
0
def GetActiveSessionId():
    for session in win32ts.WTSEnumerateSessions():
        if session['State'] == win32ts.WTSActive:
            return session['SessionId']
    return win32ts.WTSGetActiveConsoleSessionId()
Esempio n. 12
0
    def get_active_user_token():
        # Figure out the active user token we need to use to run the app as
        ret = None

        # Get the current user name
        user_name = win32api.GetUserName()

        if user_name != "SYSTEM":
            # Running as a logged in user, get the current users token
            current_process = win32process.GetCurrentProcess()
            token = win32security.OpenProcessToken(current_process,
                                                   win32con.MAXIMUM_ALLOWED)
            # win32con.TOKEN_ADJUST_PRIVILEGES | win32con.TOKEN_QUERY)  #

            ret = token

            return ret

        #if user_name == "SYSTEM":
        #    p("}}gnStarted by SYSTEM user (OPEService) - trying to switch user identity}}xx")

        # Get a list of Terminal Service sessions and see which one is active
        active_session = UserAccounts.WTS_INVALID_SESSION_ID
        station_name = ""
        sessions = win32ts.WTSEnumerateSessions(None, 1, 0)

        for session in sessions:
            if session['State'] == UserAccounts.WTSActive:
                # Found the active session
                active_session = session['SessionId']
                station_name = session["WinStationName"]

        # If we didn't find one, try this way
        if active_session == UserAccounts.WTS_INVALID_SESSION_ID:
            active_session = win32ts.WTSGetActiveConsoleSessionId()
        if active_session == UserAccounts.WTS_INVALID_SESSION_ID:
            # User not logged in right now? or lock screen up?
            p("}}gnNo console user or desktop locked}}xx", log_level=1)
            return ret

        # Get the current console session
        #p("Got Console: " + str(active_session), debug_level=5)

        # Login to the terminal service to get the user token for the console id so we can impersonate it
        try:
            #svr = win32ts.WTSOpenServer(".")
            #win32ts.WTSCloseServer(svr)
            user_token = win32ts.WTSQueryUserToken(active_session)

            # Copy the token so we can modify it
            user_token_copy = win32security.DuplicateTokenEx(
                user_token, win32security.SecurityImpersonation,
                win32security.TOKEN_ALL_ACCESS, win32security.TokenPrimary)

            ret = user_token_copy
            user_token.close()
        except Exception as ex:
            p("}}rnUnknown Error - trying to get WTS UserToken\n" + str(ex) +
              "}}xx",
              debug_level=1)
            return ret

        #p("User Token Found " + str(user_token_copy), debug_level=5)

        return ret