12.6.0 判断系统版本
>>> import os
>>> print(os.popen('ver').read())
Microsoft Windows [版本 10.0.18363.720]
>>> import sys
>>> print(sys.getwindowsversion())
sys.getwindowsversion(major=10, minor=0, build=18363, platform=2, service_pack='')
>>> import platform
>>> print(platform.platform())
Windows-10-10.0.18362-SP0
12.6.1 扩展库 psutil
(1)查看 CPU 信息。
>>> import psutil
>>> psutil.cpu_count() # 查看 CPU 核数
4
>>> psutil.cpu_count(logical = False) # 查看物理 CPU 个数
2
>>> psutil.cpu_percent() # 查看 CPU 使用率
2.7
>>> psutil.cpu_percent(percpu = True) # 查看每个 CPU 使用率
[8.9, 0.4, 1.2, 1.0]
>>> psutil.cpu_times() # 查看 CPU 分配情况
scputimes(user=1461.34375, system=1978.3437500000146, idle=106300.68749999999, interrupt=429.578125, dpc=143.078125)
(2)查看开机时间。
>>> import datetime
>>> t = psutil.boot_time()
>>> datetime.datetime.utcfromtimestamp(t).strftime('%Y-%m-%d %H:%M:%S')
'2023-02-14 11:30:51'
(3)查看内存信息。
>>> virtual_memory = psutil.virtual_memory()
>>> virtual_memory.total / 1024 / 1024 / 1024 # 内存总大小
11.887954711914062
>>> virtual_memory.used / 1024 / 1024 / 1024 # 已使用内存
3.7194747924804688
>>> virtual_memory.free / 1024 / 1024 / 1024 # 空闲内存
8.168479919433594
>>> virtual_memory.percent # 内存使用率
31.3
(4)查看磁盘信息。
>>> psutil.disk_partitions() # 查看所有分区信息
[sdiskpart(device='C:\\', mountpoint='C:\\', fstype='NTFS', opts='rw,fixed', maxfile=255, maxpath=260), sdiskpart(device='D:\\', mountpoint='D:\\', fstype='NTFS', opts='rw,fixed', maxfile=255, maxpath=260)]
>>> psutil.disk_usage('C:\\') # 查看指定分区磁盘空间情况
sdiskusage(total=125605064704, used=61094645760, free=64510418944, percent=48.6)
>>> psutil.disk_io_counters(perdisk = True) # 查看硬盘读写操作情况。
{'PhysicalDrive0': sdiskio(read_count=225520, write_count=191226, read_bytes=9609406464, write_bytes=3232138240, read_time=323, write_time=105), 'PhysicalDrive1': sdiskio(read_count=7570, write_count=1997, read_bytes=682519040, write_bytes=11046912, read_time=244, write_time=24)}
(5)查看网络流量与收发情况。
>>> psutil.net_io_counters()
snetio(bytes_sent=6064570, bytes_recv=15310685, packets_sent=15129, packets_recv=22942, errin=0, errout=0, dropin=0, dropout=0)
(6)查看当前登录用户信息。
>>> psutil.users()
(7)查看进程信息。
>>> import psutil
>>> psutil.pids() # 查看所有进程 id
[0, 4, 96, 392, 492, 612, 712, 784, 800, 832, 908, 920, 924, 952, 972, 1108, 1124, 1384, 1400, 1420, 1432, 1440, 1492, 1512, 1548, 1560, 1604, 1660, 1692, 1732, 1784, 1796, 1824, 1836, 1852, 1916, 1928, 1992, 2012, 2076, 2080, 2148, 2172, 2180, 2200, 2308, 2328, 2340, 2368, 2588, 2684, 2720, 2728, 2736, 2828, 2884, 2904, 2968, 2984, 3032, 3040, 3044, 3104, 3116, 3132, 3284, 3292, 3336, 3356, 3384, 3436, 3496, 3556, 3568, 3592, 3596, 3696, 3780, 3852, 4040, 4068, 4196, 4200, 4208, 4216, 4232, 4240, 4248, 4276, 4284, 4292, 4328, 4336, 4356, 4388, 4432, 4460, 4552, 4560, 4588, 4592, 4600, 4608, 4640, 4648, 4672, 4684, 4696, 4704, 4744, 4780, 4788, 4796, 4808, 4816, 4876, 4896, 4912, 4948, 5064, 5084, 5328, 5376, 5388, 5400, 5492, 5528, 5704, 5716, 5984, 6180, 6220, 6272, 6296, 6384, 6404, 6504, 6732, 6872, 6920, 7204, 7368, 7504, 7724, 7756, 7808, 8024, 8052, 8112, 8228, 8284, 8336, 8396, 8456, 8548, 8608, 8612, 8644, 8820, 8836, 8928, 9004, 9372, 9908, 9960, 10104, 10428, 10552, 10756, 10888, 10892, 11044, 11096, 11184, 11244, 11308, 11336, 11352, 11412, 11496, 11500, 11512, 11536, 11668, 11800, 11832, 11920, 11984, 12076, 12108, 12188, 12300, 12484, 12652, 13156]
>>> p = psutil.Process(4208) # 获取指定 id 进程
>>> p.name() # 进程名
'svchost.exe'
>>> p.username() # 创建该进程的用户名
'NT AUTHORITY\\SYSTEM'
>>> p.cmdline() # 进程对应的 exe 文件
['C:\\WINDOWS\\system32\\svchost.exe', '-k', 'LocalSystemNetworkRestricted', '-p', '-s', 'DeviceAssociationService']
>>> p.cwd() # 进程的工作目录
'C:\\WINDOWS\\system32'
>>> p.exe() # 进程对应的可执行文件名
'C:\\Windows\\System32\\svchost.exe'
>>> p.cpu_affinity() # 进程的 CPU 占用情况
[0, 1, 2, 3]
>>> p.num_threads() # 进程包含的线程数量
3
>>> p.status() # 进程状态
'running'
>>> p.is_running() # 进程是否在运行
True
>>> p.suspend() # 挂起
>>> p.resume() # 恢复运行
>>> p.kill() # 结束
(8)查看记事本是否在运行,是则返回其 id。
>>> import os
>>> for id in psutil.pids():
try:
p = psutil.Process(id)
if os.path.basename(p.exe()) == 'notepad.exe':
print(id)
except Exception as e:
print(e)
(pid=0)
12.6.2 使用 pywin32 实现事件查看器
Windows 系统会对运行过程中发生的很多事情进行记录,通过事件查看器可以查看系统日志。右击“计算机”->单击“管理”菜单->单击“事件查看器”。
import win32evtlog
import win32evtlogutil
import win32security
import win32con
import winerror
import time
import re
import sys
import traceback
import threading
def date2sec(evt_date):
''' '''
# 把日期和时间分开
the_date, the_time = evt_date.split()
(month, day, year) = map(lambda x:int(x), the_date.split(r'/'))
(hour, minute, second) = map(lambda x:int(x), the_time.split(r':'))
if 70 < year < 100:
year = year + 1990
elif year < 50:
year = year + 2000
tup = (year, month, day, hour, minute, second, 0, 0, 0)
seconds = time.mktime(tup)
return second
def main(computer = '.', logtype = 'System', interval = 480):
flags = win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ
evt_dict = {win32con.EVENTLOG_AUDIT_FAILURE:'审核失败事件',
win32con.EVENTLOG_AUDIT_SUCCESS:'审核成功事件',
win32con.EVENTLOG_INFORMATION_TYPE:'通知事件',
win32con.EVENTLOG_WARNING_TYPE:'警告事件',
win32con.EVENTLOG_ERROR_TYPE:'错误事件'}
begin_sec = time.time()
begin_time = time.strftime('%H:%M:%S', time.localtime(begin_sec))
try:
# 打开日志
hand = win32evtlog.OpenEventLog(computer, logtype)
except Exception as e:
print('无法打开"{0}"服务器上的"{1}"日志'.format(computer, logtype))
print(e)
return
print(logtype, ' events found in the last {0} hours before {1}'.format(interval/60/60, begin_time))
events = 1
while events:
events = win32evtlog.ReadEventLog(hand, flags, 0)
for ev_obj in events:
try:
the_time = ev_obj.TimeGenerated.Format('%D %H:%M:%S')
seconds = date2sec(the_time)
# 只查看指定时间段内的日志
if seconds < begin_sec - interval:
break
computer = ev_obj.ComputerName
cat = str(ev_obj.EventCatgory)
src = str(ev_obj.SourceName)
record = str(ev_obj.RecordNumber)
evt_id = str(winerror.HRESULT_CODE(ev_obj.EventID))
evt_type = evt_dict[ev_obj.EventType]
msg = win32evtlogutil.SafeFormatMessage(evt_obj, logtype)
print(':'.join((the_time, computer, src, cat, record, evt_id, evt_type, msg)))
print('=' * 20)
if seconds < begin_sec - interval:
break
except Exception as e:
print(e)
win32evtlog.CloseEventLog(hand)
t3 = threading.Thread(target = main, args = ('.', 'System', 5400))
t3.start()
t3.join()
12.6.3 切换用户登录身份
在系统中创建一个账号 dddd 并设置密码 123456,创建文件夹 D:\test_ddd。
import os
import win32security
import win32con
import win32api
class Impersonate:
def __init__(self, loginName, password):
self.domain = 'WORKGROUP'
self.loginName = loginName
self.password = password
self.handel = None
def logon(self):
self.handel = win32security.LogonUser(self.loginName, self.domain, self.password,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT)
# 登录另一个账号
win32security.ImpersonateLoggedOnUser(self.handel)
def logoff(self):
# 切换至本来的用户名
win32security.RevertToSelf()
print('OK. I am back ' + win32api.GetUserName())
# 关闭句柄
self.handel.Close()
print('Origionally I am ' + win32api.GetUserName())
# 要模仿的用户名和密码
a = Impersonate('dddd', '123456')
try:
# 以别人的身份登录
a.logon()
# 显示当前登录用户名
print('Now I become ' + win32api.GetUserName())
os.mkdir(r'D:\\test_ddd\ddd')
# 注销切换至本来的用户身份
a.logoff()
except Exception as e:
print("Denied.Now I will become an administrator and try again")
print(e)
a.logoff()
os.mkdir(r'D:\test_ddd\administartor')