#!/usr/bin/python3'''
apt install python3-dev
apt install pip
pip3 install pynput
'''from pynput.keyboard import Key as kbKey, Listener as kbListener
from pynput.mouse import Listener as msListener
import threading
import time
import datetime
import os
updateDatetime = datetime.datetime.now()
currentDatetime = datetime.datetime.now()'''
关于键盘的事件回调
'''#defining function to print when key is presseddefon_press(key):global updateDatetime
updateDatetime = datetime.datetime.now()print('{0} pressed'.format(key))#defining function to print when key is releaseddefon_release(key):global updateDatetime
updateDatetime = datetime.datetime.now()print('{0} release'.format(key))'''
关于鼠标及触控的事件回调
'''defon_move(x, y ):global updateDatetime
updateDatetime = datetime.datetime.now()print('Pointer moved to {0}'.format((x,y)))defon_click(x, y , button, pressed):global updateDatetime
updateDatetime = datetime.datetime.now()print('{0} at {1}'.format('Pressed'if pressed else'Released',(x, y)))defon_scroll(x, y ,dx, dy):global updateDatetime
updateDatetime = datetime.datetime.now()print('scrolled {0} at {1}'.format('down'if dy <0else'up',(x, y)))'''
键盘的事件监控
'''deftoListenerKb(threadName):# # Collect events until releasedwhileTrue:with kbListener(
on_press=on_press,
on_release=on_release)as listener:
listener.join()'''
鼠标的事件监控
'''deftoListenerMouse(threadName):whileTrue:with msListener(on_move = on_move,on_click = on_click,on_scroll = on_scroll)as listener:
listener.join()if __name__ =='__main__':
threads =[]
t1 = threading.Thread( target=toListenerKb , args=("Listener keyBoard",))
t2 = threading.Thread( target=toListenerMouse , args=("Listener Mouse",))
threads.append(t1)
threads.append(t2)for t in threads:
t.setDaemon(True)
t.start()whileTrue:
currentDatetime = datetime.datetime.now()
sub = currentDatetime - updateDatetime
time.sleep(1)# 30s 没有操作就杀死远程if sub.seconds >30:
os.system("ps -ef | grep remmina | grep -v grep; if [ $? -eq 0 ]; then killall -9 remmina; fi")print('空闲时间: {0}秒'.format(sub.seconds))
三、使用X11的extensions监控鼠标键盘事件
3.1 使用Python的python3-xlib库进行监控
#!/usr/bin/python3'''
apt install python3-xlib
Simple demo for the RECORD extension
Not very much unlike the xmacrorec2 program in the xmacro package.
'''# apt install python3-xlib# Python 2/3 compatibility.from __future__ import print_function
import sys
import threading
import time
import datetime
import os
from Xlib import X, XK, display
from Xlib.ext import record
from Xlib.protocol import rq
updateDatetime = datetime.datetime.now()
currentDatetime = datetime.datetime.now()
local_dpy = display.Display()
record_dpy = display.Display()# Check if the extension is presentifnot record_dpy.has_extension("RECORD"):print("RECORD extension not found")
sys.exit(1)
r = record_dpy.record_get_version(0,0)print("RECORD extension version %d.%d"%(r.major_version, r.minor_version))# Create a recording context; we only want key and mouse events
ctx = record_dpy.record_create_context(0,[record.AllClients],[{'core_requests':(0,0),'core_replies':(0,0),'ext_requests':(0,0,0,0),'ext_replies':(0,0,0,0),'delivered_events':(0,0),'device_events':(X.KeyPress, X.MotionNotify),'errors':(0,0),'client_started':False,'client_died':False,}])deflookup_keysym(keysym):for name indir(XK):if name[:3]=="XK_"andgetattr(XK, name)== keysym:return name[3:]return"[%d]"% keysym
defrecord_callback(reply):'''
回调函数
'''if reply.category != record.FromServer:returnif reply.client_swapped:print("* received swapped protocol data, cowardly ignored")returnifnotlen(reply.data)or reply.data[0]<2:# not an eventreturnglobal updateDatetime
data = reply.data
whilelen(data):
event, data = rq.EventField(None).parse_binary_value(
data, record_dpy.display,None,None)if event.typein[X.KeyPress, X.KeyRelease]:
updateDatetime = datetime.datetime.now()
pr = event.type== X.KeyPress and"Press"or"Release"
keysym = local_dpy.keycode_to_keysym(event.detail,0)ifnot keysym:print("KeyCode%s"% pr, event.detail)else:print("KeyStr%s"% pr, lookup_keysym(keysym))if event.type== X.KeyPress and keysym == XK.XK_Escape:
local_dpy.record_disable_context(ctx)
local_dpy.flush()returnelif event.type== X.ButtonPress:
updateDatetime = datetime.datetime.now()print("ButtonPress", event.detail)elif event.type== X.ButtonRelease:
updateDatetime = datetime.datetime.now()print("ButtonRelease", event.detail)elif event.type== X.MotionNotify:
updateDatetime = datetime.datetime.now()print("MotionNotify", event.root_x, event.root_y)defmonitor(threadName):'''
线程函数
'''# Enable the context; this only returns after a call to record_disable_context,# while calling the callback function in the meantime
record_dpy.record_enable_context(ctx, record_callback)# Finally free the context
record_dpy.record_free_context(ctx)if __name__ =='__main__':
t = threading.Thread(target=monitor, args=("Listener",))
t.setDaemon(True)
t.start()whileTrue:
currentDatetime = datetime.datetime.now()
sub = currentDatetime - updateDatetime
time.sleep(1)print('空闲时间: {0}秒'.format(sub.seconds))