一、监听系统目录
import os
import win32file
import datetime
import win32con
"""
监听某目录的文件,如果文件有增删改查,则输出变动文件路径
"""
def jtwj(path_to_watch=None):
if path_to_watch is None:
path_to_watch = 'D:\\' # 要监听文件的路径, 默认为D盘
ACTIONS = {
1: "Created",
2: "Deleted",
3: "Updated",
4: "Renamed from something",
5: "Renamed to something"
}
FILE_LIST_DIRECTORY = win32con.GENERIC_READ | win32con.GENERIC_WRITE
hDir = win32file.CreateFile(
path_to_watch,
FILE_LIST_DIRECTORY,
win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
None,
win32con.OPEN_EXISTING,
win32con.FILE_FLAG_BACKUP_SEMANTICS,
None
)
while 1:
results = win32file.ReadDirectoryChangesW(
hDir, # handle(句柄):要监视的目录的句柄。这个目录必须用 FILE_LIST_DIRECTORY 访问权限打开。
1024, # size(大小): 为结果分配的缓冲区大小。
True, # bWatchSubtree: 指定 ReadDirectoryChangesW 函数是否监视目录或目录树。
win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
win32con.FILE_NOTIFY_CHANGE_SIZE |
win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
win32con.FILE_NOTIFY_CHANGE_SECURITY,
None,
None)
for action, file in results:
full_filename = os.path.join(path_to_watch, file)
status = ACTIONS.get(action, "Unknown")
print(full_filename, status)
if __name__ == '__main__':
folders = "D:\\"
jtwj(folders)
输出结果:D:\tools\Tools\June_2018\2018-6-6\2018-6-6.txt Updated
1.1、监控系统目录---并输出文件内容:
import os
import tempfile
import threading
import win32file
import win32con
# 这些是典型的临时文件所在的路径
dirs_to_monitor = ["C:\\WINDOWS\\temp",tempfile.gettempdir()]
# 文件修改行为对应的常量
FILE_CREATED = 1
FILE_DELETED = 2
FILE_MODIFIED = 3
FILE_RENAMED_FROM = 4
FILE_RENAMED_T0 = 5
def start_monitor(path_to_watch):
# 为每一个监控起一个线程
FILE_LIST_DIRECTORY = 0x0001
h_directory = win32file.CreateFile(
path_to_watch,
FILE_LIST_DIRECTORY,
win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE,
None,
win32con.OPEN_EXISTING,
win32con.FILE_FLAG_BACKUP_SEMANTICS,
None)
while 1:
try:
results = win32file.ReadDirectoryChangesW(
h_directory,
1024,
True,
win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
win32con.FILE_NOTIFY_CHANGE_SIZE |
win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
win32con.FILE_NOTIFY_CHANGE_SECURITY,
None,
None
)
for action,file_name in results:
full_filename = os.path.join(path_to_watch,file_name)
if action == FILE_CREATED:
print('[ + ] Created %s'%full_filename)
elif action == FILE_DELETED:
print('[ - ] Deleted %s'%full_filename)
elif action == FILE_MODIFIED:
print('[ * ] Modified %s'%full_filename)
# 输出文件内容
print('[vvv] Dumping contents...')
try:
with open(full_filename,'rb') as f:
contents = f.read()
print(contents.decode('gbk'))
print("[^^^] Dump complete.")
except:
print("[!!!] Failed.")
elif action == FILE_RENAMED_FROM:
print("[ > ] Renamed from: %s"%full_filename)
elif action == FILE_RENAMED_T0:
print("[ < ] Renamed to: %s"%full_filename)
else:
print("[???] Unknown: %s"%full_filename)
except:
pass
if __name__ == '__main__':
for path in dirs_to_monitor:
monitor_thread = threading.Thread(target=start_monitor,args=(path,))
print("Spawning monitoring thread for path: %s"%path)
monitor_thread.start()
执行结果:
Spawning monitoring thread for path: C:\WINDOWS\temp
Spawning monitoring thread for path: C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp
>>> [ * ] Modified C:\WINDOWS\temp\秘密.txt
[vvv] Dumping contents...
告诉你一个秘密
[^^^] Dump complete.
[ * ] Modified C:\WINDOWS\temp\秘密.txt
[vvv] Dumping contents...
告诉你一个秘密
[^^^] Dump complete.
[ + ] Created C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\etilqs_rhug6Wh45c6YmKL
[ - ] Deleted C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\etilqs_rhug6Wh45c6YmKL
二、查询本机mac地址,本机名称,本机IP
def get_mac_name_ip():
""" 获得本机计算机名称,mac地址,内网IP地址 """
import socket,uuid
# 获取Mac地址
mac = uuid.UUID(int = uuid.getnode()).hex[-12:]
mac = ":".join([mac[e:e+2] for e in range(0,11,2)])
#获取本机电脑名
name = socket.getfqdn(socket.gethostname())
#获取本机ip
ip = socket.gethostbyname(name)
return mac,name,ip
print(get_mac_name_ip())
输出结果:('88:d8:f6:c8:b5:d2', 'computerName', '192.168.1.18')
三,查询局域网内的计算机名称与对应的IP地址
import os
import re
import threading
"""
局域网内IP地址查询
"""
NAME_IP = {}
def get_local_name():
n = os.popen('net view')
n = n.read()
n = n.split()
name = [i.replace('\\','') for i in n if '\\' in i]
return name
def get_local_ip(name):
a = os.popen('ping -4 %s'%name).read()
ip = re.findall(r'\[(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\]',a)[0]
global NAME_IP
NAME_IP[name] = ip
def get_local():
names = get_local_name()
name_tdg = []
for i in names:
name_tdg.append(threading.Thread(target=get_local_ip,args=(i,)))
for i in range(len(name_tdg)):
name_tdg[i].start()
for i in range(len(name_tdg)):
name_tdg[i].join()
print(NAME_IP)
if __name__ == '__main__':
get_local()
输出结果:{'computerName': '192.168.1.18'}
四、利用 WMI 监视进程
import win32con
import win32api
import win32security
import os
import sys
import wmi
def log_to_file(message):
''' 把信息写入到日志文件 '''
with open('process_monitor_log.txt','ab') as f:
f.write(('%s\r\n'%message).encode())
def runs():
''' 开始监视我们系统的进程 '''
# 创建一个日志文件的头部信息
log_to_file("Time,User,Executable,CommandLine,PID,Parent PID,Privileges")
# 初始化WMI接口
c = wmi.WMI()
# 创建进程监控器
process_watcher = c.Win32_Process.watch_for('creation')
while True:
try:
new_process = process_watcher()
proc_owner = new_process.GetOwner()
proc_owner = '%s\\%s'%(proc_owner[0],proc_owner[2])
create_date = new_process.CreationDate
executable = new_process.ExecutablePath
cmdline = new_process.CommandLine
pid = new_process.ProcessId
parent_pid = new_process.ParentProcessId
privileges = 'N/A'
process_log_message = '%s,%s,%s,%s,%s,%s,%s\r\n'%(create_date,
proc_owner,executable,cmdline,pid,parent_pid,privileges)
print(process_log_message)
log_to_file(process_log_message)
except Exception as exc:
print(exc)
if __name__ == '__main__':
runs()
执行本程序,打开某个记事本后,输出结果:
20180615163430.968750+480,PC1\Administrator,C:\WINDOWS\system32\NOTEPAD.EXE,"C:\WINDOWS\system32\NOTEPAD.EXE" C:\Documents and Settings\Administrator\桌面\秘密.txt,10108,5600,N/A
五、关闭屏幕 与 锁屏
from ctypes import *
import time
class User32:
def __init__(self):
self.user = windll.user32
def box(self):
""" 弹出确认框,是:6,否:7,取消:2 """
return self.user.MessageBoxW(None,'现在已经12点了,该吃饭了!','消息提示',3)
def close_screen(self):
""" 关闭电脑屏幕 """
wn_syscommand = 0x0112
sc_monitorpower = 0xf170
HWND_BROAOCAST = self.user.FindWindowExA(None,None,None,None)
v=self.user.SendMessageA(HWND_BROAOCAST,wn_syscommand,sc_monitorpower,2)
print(v)
def lock_screen(self):
""" 锁屏 """
self.user.LockWorkStation()
if __name__ == '__main__':
u32 = User32()
u32.box()
for i in range(6):
u32.close_screen()
time.sleep(1)
u32.lock_screen()
六、监听键盘与鼠标
import pythoncom
import pyHook
def onMouseEvent(event):
# 监听鼠标事件
print("MessageName:", event.MessageName)
print("Message:", event.Message)
print("Time:", event.Time)
print("Window:", event.Window)
print("WindowName:", event.WindowName)
print("Position:", event.Position)
print("Wheel:", event.Wheel)
print("Injected:", event.Injected)
print("---")
# 返回 True 以便将事件传给其它处理程序
# 注意,这儿如果返回 False ,则鼠标事件将被全部拦截
# 也就是说你的鼠标看起来会僵在那儿,似乎失去响应了
return True
def onKeyboardEvent(event):
# 监听键盘事件
print("MessageName:", event.MessageName)
print("Message:", event.Message)
print("Time:", event.Time)
print("Window:", event.Window)
print("WindowName:", event.WindowName)
print("Ascii:", event.Ascii, chr(event.Ascii))
print("Key:", event.Key)
print("KeyID:", event.KeyID)
print("ScanCode:", event.ScanCode)
print("Extended:", event.Extended)
print("Injected:", event.Injected)
print("Alt", event.Alt)
print("Transition", event.Transition)
print("---")
# 同鼠标事件监听函数的返回值
return True
def main():
# 创建一个“钩子”管理对象
hm = pyHook.HookManager()
# 监听所有键盘事件
hm.KeyDown = onKeyboardEvent
# 设置键盘“钩子”
hm.HookKeyboard()
# 监听所有鼠标事件
hm.MouseAll = onMouseEvent
# 设置鼠标“钩子”
hm.HookMouse()
# 进入循环,如不手动关闭,程序将一直处于监听状态
pythoncom.PumpMessages()
if __name__ == "__main__":
main()