介绍
尽管不可能记录所有 GUI操作,但是可以完成诸如记录与打开的窗口相对应的命令之类的事情。以下是完成这项工作的简单python脚本。它仍在开发中,但完成了所需任务的90%。
源代码
#!/usr/bin/env python3
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('Gdk', '3.0')
from gi.repository import Gdk,Gtk
import time
import os
import subprocess
def run_cmd(cmdlist):
""" Reusable function for running external commands """
new_env = dict(os.environ)
new_env['LC_ALL'] = 'C'
try:
stdout = subprocess.check_output(cmdlist, env=new_env)
except subprocess.CalledProcessError:
pass
else:
if stdout:
return stdout
def print_info(stack,event):
base_xprop = ['xprop','-notype']
for xid in stack:
pid = None
check_pid = run_cmd(base_xprop + [ '_NET_WM_PID', '-id',str(xid)])
if check_pid:
pid = check_pid.decode().split('=')[1].strip()
with open('/proc/'+pid+'/cmdline') as fd:
command = fd.read()
print(time.strftime("%D %H:%M:%S" + " "*3) + event + pid + " " + command)
def main():
sc = Gdk.Screen.get_default()
old_stack = None
while True:
stack = [ win.get_xid() for win in sc.get_window_stack() ]
if old_stack:
# Difference between current and old stack will show new programs
diff = set(stack) - set(old_stack)
if diff:
print_info(diff," 'New window open' ")
else:
print_info(stack," 'Script Started' ")
old_stack = stack
time.sleep(2)
if __name__ == '__main__': main()
测试运行:
$ ./log_open_windows.py
01/25/17 15:33:13 'Script Started' 2915 nautilus-n
01/25/17 15:33:13 'Script Started' 3408 /opt/google/chrome/chrome
01/25/17 15:33:13 'Script Started' 12540 /usr/bin/python/usr/bin/x-terminal-emulator
01/25/17 15:33:13 'Script Started' 2454 compiz
01/25/17 15:33:13 'Script Started' 2454 compiz
01/25/17 15:33:13 'Script Started' 2454 compiz
01/25/17 15:33:13 'Script Started' 2454 compiz
01/25/17 15:33:13 'Script Started' 2454 compiz
01/25/17 15:33:21 'New window open' 15143 /usr/lib/firefox/firefox-new-window
01/25/17 15:33:27 'New window open' 15196 unity-control-center
该脚本显示时间戳,事件类型,窗口PID和相应的命令。
如何使用
任何脚本的标准规则均适用。确保将脚本存储在~/bin
目录中。如果您没有~/bin
目录,请创建一个。将脚本文件保存在那里,并确保可以使用来执行chmod +x ~/bin/log_open_windows.py
。之后,您可以随时通过~/log_open_windows.py
在命令行中调用从命令行运行它。