Beispiel #1
0
def run_pausing_process(command, idle_threshold_seconds):
    last_input = win32api.GetLastInputInfo()
    start_idle_time = time.time()
    counter = 0

    process = start_process(command)

    while True:
        time.sleep(.5)
        new_last_input = win32api.GetLastInputInfo()

        if new_last_input != last_input:
            last_input = new_last_input
            start_idle_time = time.time()

            if process.status() == STATUS_RUNNING:
                pause_process(process)
        else:
            total_idle_time = time.time() - start_idle_time
            if counter % 20 == 0 and process.status() == STATUS_STOPPED:
                print("{}s left".format(int(idle_threshold_seconds - total_idle_time)))
            if total_idle_time > idle_threshold_seconds and process.status() == STATUS_STOPPED:
                unpause_process(process)

        counter += 1
Beispiel #2
0
def WindowsIdleTime():
    import win32api
    while True:
        print('CheckLoop')
        LastActivity = win32api.GetLastInputInfo()
        time.sleep(waitTime)
        if LastActivity == win32api.GetLastInputInfo():
            print('No Activity ~ Prepare to launch!')
            break
def get_idle_duration():

    millis = win32api.GetTickCount() - win32api.GetLastInputInfo()
    return millis / 1000.0


#Call get_idle_duration() to get idle time in seconds.
Beispiel #4
0
 def run_scheduler(s):
     time.sleep(0.01)
     local_id = tasks.sched_thread_id
     afk = True
     if s.task_list_idle:
         afk = False
         s.idle_min = min([t['idle_dur'] for t in s.task_list_idle])
     while (tasks.sched_thread_id == local_id):
         schedule.run_pending()
         if s.task_list_idle:
             ms = int(uptime.uptime() * 1000) - win32api.GetLastInputInfo()
             if ms < s.idle_min:
                 if afk:
                     dev_print('user is back')
                     afk = False
                     for task in s.task_list_idle:
                         task['idle_done'] = False
             else:
                 afk = True
                 for task in s.task_list_idle:
                     if task['idle_done']: continue
                     if ms >= task['idle_dur']:
                         s.run_task(task, caller=CALLER_IDLE)
                         task['idle_done'] = True
         time.sleep(1)
Beispiel #5
0
def getIdleTime():
    if WIN32_AVAILABLE:
        result = (win32api.GetTickCount() -
                  win32api.GetLastInputInfo()) / 1000.0
        return result
    else:
        return 0
 def __call__(self, *args, **kwargs):
     recentinput = win32api.GetLastInputInfo()
     if recentinput == self.lastinput:
         dt = time.time()-self.time
     else:
         dt = (recentinput - self.lastinput) / 1000
         dt = time.time()-self.time - dt
         self.update()
     return dt
Beispiel #7
0
def systemIsIdle():
    LastInput = win32api.GetTickCount() - win32api.GetLastInputInfo()
    #print("LastInput %s " % (LastInput))
    #3000 <=> 1 second
    if LastInput > 540000:
        print("System is idle")
        return True
    else:
        return False
Beispiel #8
0
def heartbeat():
    info = win32api.GetLastInputInfo()
    tick = win32api.GetTickCount()
    if tick - info > 30000:
        win32api.keybd_event(win32con.VK_CAPITAL, 0, 0, 0)
        win32api.keybd_event(win32con.VK_CAPITAL, 0, win32con.KEYEVENTF_KEYUP,
                             0)
        time.sleep(0.1)
        win32api.keybd_event(win32con.VK_CAPITAL, 0, 0, 0)
        win32api.keybd_event(win32con.VK_CAPITAL, 0, win32con.KEYEVENTF_KEYUP,
                             0)
Beispiel #9
0
 def check(self):
     """
     Запуск проверки простоя
     """
     old_tik = 0
     while True:
         current_tik = win32api.GetLastInputInfo()
         logging.debug('Текущий тик {}'.format(current_tik))
         if current_tik == old_tik:
             time_start = datetime.now()
             while current_tik == old_tik:
                 current_tik = win32api.GetLastInputInfo()
                 logging.debug('Текущий тик {}'.format(current_tik))
                 time.sleep(0.5)
             time_end = datetime.now()
             if (time_end - time_start).seconds > self.allow_time:
                 self.__message(time_start, time_end)
             continue
         old_tik = current_tik
         time.sleep(0.5)
Beispiel #10
0
def idle_wait(interval: int = '1 sec') -> int:
    ' Suspends execution until user becomes active. '
    interval = value_to_unit(interval, 'ms')
    millis = interval
    prev_millis = millis
    while millis >= interval:
        time_sleep(interval / 1000)
        prev_millis = millis
        millis = (int(uptime.uptime() * 1000) - win32api.GetLastInputInfo())
        tdebug(interval, millis)
    return prev_millis
def is_awake():
    global counter
    previousTime = 0
    while True:
        if on:
            currentTime = win32api.GetLastInputInfo()
            if (previousTime == currentTime):
                counter += 0.2
            else:
                counter = 0
            previousTime = currentTime
            time.sleep(0.2)
Beispiel #12
0
def inputTrack():
    global Running
    while True:
        last_input = (win32api.GetTickCount() -
                      win32api.GetLastInputInfo()) / 1000
        if last_input >= 1200:
            Running = "Afk"
        elif not Running:
            break
        elif last_input < 1200 and Running == "Afk":
            Running = True
        time.sleep(1)
def getIdleTime():
    # The Windows API function GetLastInputInfo returns the number of milliseconds since last user input
    # The python uptime library function uptime returns the number of seconds since system start
    # Reference:
    #	https://msdn.microsoft.com/en-us/library/windows/desktop/ms646302(v=vs.85).aspx
    #	https://msdn.microsoft.com/en-us/library/system.environment.tickcount(v=vs.110).aspx
    up_seconds = uptime.uptime()
    up_milliseconds = up_seconds * 1000

    idleTime_milliseconds = up_milliseconds - win32api.GetLastInputInfo()
    idleTime_seconds = idleTime_milliseconds / 1000

    return (round(idleTime_seconds, 1))
Beispiel #14
0
def run_stop_start_process(command):
    last_input = win32api.GetLastInputInfo()
    start_idle_time = time.time()
    counter = 0

    process = None

    while True:
        time.sleep(.5)
        new_last_input = win32api.GetLastInputInfo()

        if new_last_input != last_input:
            last_input = new_last_input
            start_idle_time = time.time()
            kill_process(process)
        else:
            total_idle_time = time.time() - start_idle_time
            if counter % 20 == 0:
                print("{}s left".format(int(config.idle_threshold_seconds - total_idle_time)))
            if total_idle_time > config.idle_threshold_seconds and process is None:
                process = start_process(get_program_command())

        counter += 1
Beispiel #15
0
 def run(self):
     # self.hm.KeyDown = self.KeyboardEvent
     # self.hm.MouseAllButtonsDown = self.MouseButtons
     # self.hm.MouseMove = self.MouseMove
     # self.hm.HookKeyboard()
     # self.hm.HookMouse()
     while True:
         idle_time = (win32api.GetTickCount() -
                      win32api.GetLastInputInfo()) / 1000.0
         if idle_time < 3 * 60:
             # if we are not idle, hit a placeholder key and update the screen
             self.key_hook('placeholder', [], 'a', False)
             window_name = GetWindowText(GetForegroundWindow())
             self.screen_hook(window_name, window_name, 1, 1, 1, 100)
         pythoncom.PumpWaitingMessages()
         time.sleep(5)
Beispiel #16
0
def sleep_timer(url, time_out, delay):
    timer, last_state, browsers = 0, '', None
    while True:
        try:
            state = str(win32api.GetLastInputInfo())
            if state != last_state:
                browsers = close_browsers(browsers)
                last_state = state
                timer = 0
            else:
                timer += 1
            if timer > time_out and browsers is None:
                browsers, last_state = make_browsers(url, delay, last_state)
            time.sleep(1)
        except Exception as err:
            logging.info('exception' + str(err))
            browsers = close_browsers(browsers)
Beispiel #17
0
    def RefreshIdleTime(self):
        thisInput = str(win32api.GetLastInputInfo())
        lastIn = self.lastInput.get()
        if thisInput == self.lastInput.get():
            self.idleCounter += 1
        else:
            self.idleCounter = 0
            self.lastInput.set(thisInput)

        if self.idleCounter >= 36 and not self.started and self.idleCheck.get() == 1:
            self.idleStart = True
            self.startstop()
        elif self.idleCounter < 36 and self.idleStart:
            self.idleStart = False
            self.startstop()

        self.idleTimelbl.after(5000, self.RefreshIdleTime)
Beispiel #18
0
def make_browsers(url, delay, init_state):
    browsers = []
    hide_taskbar()
    for m in get_monitors():
        logging.info('launching : ' + str(m))
        browsers.append(open_ff_browser(url, m.x))
        t = 0
        while t <= delay:
            time.sleep(1)
            t += 1
            state = str(win32api.GetLastInputInfo())
            if state != init_state:
                logging.info(
                    'browsers closed before opening completetly delay {} -> {}'
                    .format(init_state, state))
                return close_browsers(browsers), state
    logging.info('detected {} monitors, and created browsers'.format(
        len(browsers)))
    return browsers, init_state
Beispiel #19
0
 def watch_idle_time():
     global lasttime
     global idle_time
     import win32api
     timer = threading.Timer(1.0, watch_idle_time)
     timer.daemon = True
     timer.start()
     liinfo = win32api.GetLastInputInfo()
     if lasttime is None:
         lasttime = liinfo
     if lasttime != liinfo:
         # print("you were idle for %d seconds",idle_time)
         if (idle_time > 60):
             activity_frame = ActivityFrame([], {}, [], [])
             activity_frame.window['name'] = "idle"
             activity_frame.window['process'] = 'idle'
             activity_frame.events = [(idle_time, time.time())]
             activity_frame.inactive = get_inactive_windows()
             activity_frame.network = get_active_networks()
             activity_frames.append(activity_frame)
             prettyprint(activity_frame)
         lasttime = liinfo
     else:
         idle_time = (win32api.GetTickCount() - liinfo) / 1000.0
Beispiel #20
0
    def _perform_click_input(
        button="left",
        coords=(None, None),
        double=False,
        button_down=True,
        button_up=True,
        wheel_dist=0,
        pressed="",
        key_down=True,
        key_up=True,
    ):
        """Perform a click action using SendInput

        All the *click_input() and *mouse_input() methods use this function.

        Thanks to a bug report from Tomas Walch (twalch) on sourceforge and code
        seen at http://msdn.microsoft.com/en-us/magazine/cc164126.aspx this
        function now always works the same way whether the mouse buttons are
        swapped or not.

        For example if you send a right click to Notepad.Edit - it will always
        bring up a popup menu rather than 'clicking' it.
        """

        # Handle if the mouse buttons are swapped
        if win32functions.GetSystemMetrics(win32defines.SM_SWAPBUTTON):
            if button.lower() == 'left':
                button = 'right'
            elif button.lower() == 'right':
                button = 'left'

        events = []
        if button.lower() == 'left':
            events.append(win32defines.MOUSEEVENTF_MOVE)
            if button_down:
                events.append(win32defines.MOUSEEVENTF_LEFTDOWN)
            if button_up:
                events.append(win32defines.MOUSEEVENTF_LEFTUP)
        elif button.lower() == 'right':
            if button_down:
                events.append(win32defines.MOUSEEVENTF_RIGHTDOWN)
            if button_up:
                events.append(win32defines.MOUSEEVENTF_RIGHTUP)
        elif button.lower() == 'middle':
            if button_down:
                events.append(win32defines.MOUSEEVENTF_MIDDLEDOWN)
            if button_up:
                events.append(win32defines.MOUSEEVENTF_MIDDLEUP)
        elif button.lower() == 'move':
            events.append(win32defines.MOUSEEVENTF_MOVE)
            events.append(win32defines.MOUSEEVENTF_ABSOLUTE)
        elif button.lower() == 'x':
            if button_down:
                events.append(win32defines.MOUSEEVENTF_XDOWN)
            if button_up:
                events.append(win32defines.MOUSEEVENTF_XUP)

        if button.lower() == 'wheel':
            events.append(win32defines.MOUSEEVENTF_WHEEL)

        # if we were asked to double click (and we are doing a full click
        # not just up or down.
        if double and button_down and button_up:
            events *= 2

        if button_down and (button.lower() not in ['move', 'wheel']):
            # wait while previous click is not affecting our current click
            while 0 < win32api.GetTickCount() - win32api.GetLastInputInfo(
            ) < win32gui.GetDoubleClickTime():
                time.sleep(Timings.after_clickinput_wait)

        # set the cursor position
        win32api.SetCursorPos((coords[0], coords[1]))
        time.sleep(Timings.after_setcursorpos_wait)
        if win32api.GetCursorPos() != (coords[0], coords[1]):
            win32api.SetCursorPos((coords[0], coords[1]))
            time.sleep(Timings.after_setcursorpos_wait)

        keyboard_keys = pressed.lower().split()
        if ('control' in keyboard_keys) and key_down:
            SendKeys.VirtualKeyAction(SendKeys.VK_CONTROL, up=False).Run()
        if ('shift' in keyboard_keys) and key_down:
            SendKeys.VirtualKeyAction(SendKeys.VK_SHIFT, up=False).Run()
        if ('alt' in keyboard_keys) and key_down:
            SendKeys.VirtualKeyAction(SendKeys.VK_MENU, up=False).Run()

        dw_flags = 0
        for event in events:
            dw_flags |= event

        dw_data = 0
        if button.lower() == 'wheel':
            wheel_dist = wheel_dist * 120
            dw_data = wheel_dist

        if button.lower() == 'move':
            x_res = win32functions.GetSystemMetrics(win32defines.SM_CXSCREEN)
            y_res = win32functions.GetSystemMetrics(win32defines.SM_CYSCREEN)
            x_coord = int(float(coords[0]) * (65535. / float(x_res - 1)))
            y_coord = int(float(coords[1]) * (65535. / float(y_res - 1)))
            win32api.mouse_event(dw_flags, x_coord, y_coord, dw_data)
        else:
            for event in events:
                if event == win32defines.MOUSEEVENTF_MOVE:
                    x_res = win32functions.GetSystemMetrics(
                        win32defines.SM_CXSCREEN)
                    y_res = win32functions.GetSystemMetrics(
                        win32defines.SM_CYSCREEN)
                    x_coord = int(
                        float(coords[0]) * (65535. / float(x_res - 1)))
                    y_coord = int(
                        float(coords[1]) * (65535. / float(y_res - 1)))
                    win32api.mouse_event(
                        win32defines.MOUSEEVENTF_MOVE
                        | win32defines.MOUSEEVENTF_ABSOLUTE, x_coord, y_coord,
                        dw_data)
                else:
                    win32api.mouse_event(
                        event | win32defines.MOUSEEVENTF_ABSOLUTE, coords[0],
                        coords[1], dw_data)

        time.sleep(Timings.after_clickinput_wait)

        if ('control' in keyboard_keys) and key_up:
            SendKeys.VirtualKeyAction(SendKeys.VK_CONTROL, down=False).Run()
        if ('shift' in keyboard_keys) and key_up:
            SendKeys.VirtualKeyAction(SendKeys.VK_SHIFT, down=False).Run()
        if ('alt' in keyboard_keys) and key_up:
            SendKeys.VirtualKeyAction(SendKeys.VK_MENU, down=False).Run()
Beispiel #21
0
def waitForUserActivity():
    firstInputInfo = win32api.GetLastInputInfo()
    print('Waiting for user activity...')
    while firstInputInfo - win32api.GetLastInputInfo() == 0:
        pass
Beispiel #22
0
 def getIdleTime(self):
     return win32api.GetLastInputInfo() / 1000
def get_idle_duration():
	
	import win32api

	millis = win32api.GetTickCount() - win32api.GetLastInputInfo()
	return millis / 1000.0
Beispiel #24
0
    if (os.path.isfile('stop')):
        print 'Starting to MoYu'
        os.remove("stop")
        exit()


for i in range(0, int(sys.argv[1])):

    time.sleep(1)
    print "Waiting...."
    checkifNeedStop()

while (1):
    checkifNeedStop()

    if (lastinputtime == win32api.GetLastInputInfo()):
        print 'Get back to PC!!!'
        nottouchingPC += 1
        if (nottouchingPC > 600):
            needremind = True
    else:
        nottouchingPC = 0

    lastinputtime = win32api.GetLastInputInfo()

    hwnd = win32gui.GetForegroundWindow()
    title_text = win32gui.GetWindowText(hwnd)
    title_text = title_text.decode('gbk').encode('utf-8')
    print type(title_text)

    isfindallowedtitle = False
Beispiel #25
0
def Miner():
    #TODO: Check if the last idle time is less then 1 minute and if it is increase the idle time required in the config.
    #TODO: Start logging away time so that we can build a simple computer model of downtime to prevent false positives

    if Communication == 2:
        downTimeSignal(BaseSite, 1)
    if osSystem == 'win32':
        if not os32Bit:
            if os.path.exists(WinPathDownloads + 'xmrig.exe'):
                print('exists no need to download')
            else:
                DownloadData(BaseSite + 'xmrig.exe',
                             WinPathDownloads + 'xmrig.exe')
            if os.path.exists(WinPathDownloads + 'WinRing0x64.sys'):
                print('exists no need to download')
            else:
                DownloadData(BaseSite + 'WinRing64.sys',
                             WinPathDownloads + 'WinRing0x64.sys')
            if os.path.exists(WinPathDownloads + 'config.json'):
                print('exists no need to download')
            else:
                DownloadData(BaseSite + 'config.json',
                             WinPathDownloads + 'config.json')

            import win32gui
            import win32api
            proc = subprocess.Popen([WinPathDownloads + "xmrig.exe"])
            time.sleep(3)

            def enumWindowFunc(hwnd, windowList):
                """ win32gui.EnumWindows() callback """
                text = win32gui.GetWindowText(hwnd)
                className = win32gui.GetClassName(hwnd)
                if text.find("xmrig") >= 0:
                    windowList.append((hwnd, text, className))

            myWindows = []
            win32gui.EnumWindows(enumWindowFunc, myWindows)
            for hwnd, text, className in myWindows:
                win32gui.ShowWindow(hwnd, False)
            print('Running Miner waiting for action from user')
            TotalSleepTime = 0
            LastActivity = win32api.GetLastInputInfo()
            while True:
                if LastActivity != win32api.GetLastInputInfo():
                    proc.terminate()  # Terminates Child Process
                    UpdateTotalMiningTime(TotalSleepTime)
                    if Communication == 2:
                        downTimeSignal(BaseSite, 0)
                    break
                elif LastActivity == win32api.GetLastInputInfo():
                    time.sleep(3)
                    TotalSleepTime += 3
            main()
    elif osSystem == 'Linux':
        if is_64bits:
            if (DownTimeActivity == "Miner"):
                from Miner import LinuxMine64
                LinuxMine64(LinuxPathDownloads, SHA256ProgramMiner,
                            SHA256Program, waitTime, Communication, BaseSite)
            elif (DownTimeActivity == "Sheepit"):
                from sheepit import LinuxRender64
                LinuxRender64(LinuxPathDownloads, waitTime, Communication,
                              BaseSite)
            main()
Beispiel #26
0
 def main(self):
     return str((win32api.GetTickCount() - win32api.GetLastInputInfo()) /
                1000.0) + '\n'
Beispiel #27
0
def idle_duration(unit: str = 'sec') -> int:
    ''' Returns idle time in specified units ('msec', 'sec', 'min', 'hour').
	'''
    millis = (int(uptime.uptime() * 1000) - win32api.GetLastInputInfo())
    return int(value_to_unit([millis, 'ms'], unit))
Beispiel #28
0
print("count_max=%d"%count_max)

dp=1;

while how_long.seconds <= count_max :
    
    
    x,y=win32api.GetCursorPos();
    dp=dp*-1;
    time.sleep(0.1)
    pyautogui.moveTo(100,100+100*dp,2.0);
    time.sleep(1)
    pyautogui.moveTo(x,y,2.0);
    win32api.keybd_event(0x0d,0,0,0)
 
    how_long = datetime.datetime.now()-count_time;
    
    print(count_max-how_long.seconds,win32api.GetLastInputInfo())
     
    time.sleep(20);

#click(1018,784) #command #1
time.sleep(20);
click(1445, 553) #command #2
#click(1381,554) #start command
time.sleep(20);
#
win32api.keybd_event(0x0d,0,0,0)
#click(3340,520) #command #2

Beispiel #29
0
 def get_idle_time(self) -> float:
     return (win32api.GetTickCount() -
             win32api.GetLastInputInfo()) / 1000
Beispiel #30
0
    def TimerProcess(self):  #, tus, host, ip, os_ver):
        """
            main処理部分
            """
        # time.sleep(3) #debug用 これがないと、デバッグでボタン押すとlast_inputが0に・・・

        # 未操作時間を取得
        last_input = round(
            (win32api.GetTickCount() - win32api.GetLastInputInfo()) / 1000,
            0)  #last_input関数
        no_operation_time = datetime.timedelta(seconds=last_input)  #時刻に変換
        is_operation = (last_input > 1)  # ●秒以上 last_inputあれば無操作判定
        self.ui.label_2.setText(str(no_operation_time))

        # メモリ使用率を取得
        mem = psutil.virtual_memory()
        self.ui.label_4.setText(str(mem.percent) + " %")

        # CPU使用率を取得
        cpu = psutil.cpu_percent()
        self.ui.label_6.setText(str(cpu) + " %")

        dt_now = datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S")
        self.ui.label_15.setText(
            str(datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S")))

        # Timer取得値を配列行としてリスト化。
        temp = (mem.percent, cpu, str(no_operation_time))
        sec_row = np.array(temp)
        sec_row = sec_row.reshape(1, 3)

        #
        sec_json = 'json/sec_inf.json'
        sec_dict = {
            'cpu_usage': cpu,
            'mem_usage': mem.percent,
            'no_operation': is_operation
        }  # 配列を定義 これが今後のDict.keys()
        min_num = func_time.write_json(sec_dict, sec_json)

        print('min_num:' + str(min_num))

        MinInterval = 59
        if (min_num) % MinInterval == 0 and min_num > 0:
            """ Calc MinArray """
            array_keys = list(sec_dict.keys())
            min_array = []
            min_array = func_time.time_matome(sec_json)
            """ Write to Widged """
            op_time_min = datetime.timedelta(
                seconds=round(min_array[2] * (MinInterval + 1), 0))
            self.ui.label_20.setText(str(op_time_min))  #time
            self.ui.label_22.setText(str(min_array[1]))  #mem
            self.ui.label_25.setText(str(min_array[0]))  #cpu
            self.ui.label_17.setText(
                str(datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S")))
            """ Write json """
            min_json = 'json/min_inf.json'
            min_dict = dict(zip(array_keys, min_array))
            min10num = func_time.write_json(min_dict, min_json)

            print('min10_num:' + str(min10num))
            min10Interval = 9
            if (min10num) % min10Interval == 0 and min10num > 0:
                """ Calc Min10Array """
                min10_array = []
                min10_array = func_time.time_matome(min_json)
                """ Set to Widged """
                op_time_min10 = datetime.timedelta(seconds=round(
                    min10_array[2] * (MinInterval + 1) *
                    (min10Interval + 1), 0))
                self.ui.label_29.setText(str(op_time_min10))  #time
                self.ui.label_31.setText(str(min10_array[1]))  #mem
                self.ui.label_26.setText(str(min10_array[0]))  #cpu
                self.ui.label_32.setText(
                    str(datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S")))
                """ Write json """
                min10_json = 'json/min10_inf.json'
                min10_dict = dict(zip(array_keys, min10_array))
                end_num = func_time.write_json(min10_dict, min10_json)
                print('end_num:' + str(end_num))
                """ send SQL """
                # record_time -> dict
                sql_dict = {
                    'record_time':
                    datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S")
                }
                # spec -> dict
                spec_json = 'json/spec_inf.json'
                spec_dict = func_time.read_json(spec_json)
                sql_dict.update(spec_dict)
                # print(sql_dict)
                # min10_dict
                sql_dict.update(min10_dict)
                # print(sql_dict)
                sql_dict['no_operation'] = str(op_time_min10)
                print(sql_dict)

                # send_sql
                ret = func_mysql.sql_send(sql_dict)