import psutil
import math
import mmap
import contextlib
import os
from Evtx.Evtx import FileHeader
from Evtx.Views import evtx_file_xml_view
from xml.dom import minidom
#################
# 1.内存使用
#################
memory_info = {}
mem = psutil.virtual_memory()
#total = str(mem.total__int__()/1024/1024)
#free = str(mem.free.__int__()/1024/1024)
#used = str(mem.total.__int__()/1024/1024 - mem.free.__int__()/1024/1024)
total = round(mem.total/1024/1024)
free = round(mem.free/1024/1024)
used = round(mem.used/1024/1024)
memory_info['total'] = total
memory_info['used'] = used
memory_info['free'] = free
print('\033[1;35;40m Memory use(Mb)\033[0m','\n',memory_info)
#################
# 2.cpu使用
#################
cpu_info = {}
#cpu = psutil.cpu_times()
cpu = psutil.cpu_times_percent(interval=1.00)
#print(cpu)
cpu_info['user'] = round(cpu.user,1)
#cpu_info['nice'] = round(cpu.nice,1)
cpu_info['system'] = round(cpu.system,1)
cpu_info['idle'] = round(cpu.idle,1)
#cpu_info['iowait'] = round(cpu.iowait,1)
#cpu_info['irq'] = round(cpu.irq,1)
#cpu_info['softirq'] = round(cpu.softirq,1)
#cpu_info['steal'] = round(cpu.steal,1)
#cpu_info['guest'] = round(cpu.guest,1)
print('\n','\033[1;35;40m Cpu use(%)\033[0m','\n',cpu_info)
#################
# 2.硬盘使用
#################
disk_info = {}
file_system_ = psutil.disk_partitions(all=False)
disk_all = psutil.disk_usage('/')
print('\n','\033[1;35;40m Disk use(Mb)\033[0m','\n',disk_info)
for fs in file_system_:
#disk_fs = psutil.disk_usage(fs.device)
print('\n device:', fs.device, ',mountpoint', fs.mountpoint, '', fs.fstype, '', fs.opts)
disk_info['total'] = round(int(disk_all.total/1024/1024))
disk_info['used'] = round(int(disk_all.used/1024/1024))
disk_info['free'] = round(int(disk_all.free/1024/1024))
#Processes
#https://blog.csdn.net/wukai_std/article/details/70920412
def WinProceses():
print('=====start process======')
proces = psutil.pids()
for pid in proces:
p = psutil.Process(pid)
print(p.name(), '--->', p.status(), '\n')
#service
def WinService():
print('=====start services======')
for service in psutil.win_service_iter():
print(service.display_name(), '--->', service.status())
#log
def winLog():
EvtxPath = "C:\Windows\System32\winevt\Logs\Security.evtx"
eventIDs = [4624, 4625, 4720, 4724, 4725, 4728, 4732, 4635, 4740, 4748, 4756]
# 4624=login success 4625=log fail
# <Data Name="LogonType">5</Data> LogonType=3 网络访问 10远程桌面访问
with open(EvtxPath, 'r') as f:
with contextlib.closing(mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as buf:
fh = FileHeader(buf, 0)
for xml, record in evtx_file_xml_view(fh):
xmldoc = minidom.parseString(xml)
eventNode = xmldoc.getElementsByTagName('EventID')[0]
eventID = eventNode.childNodes[0].nodeValue
if int(eventID) == 4624:
findLoginInfoFromWinLog(xmldoc)
def findLoginInfoFromWinLog(xmldoc):
dataNodes = xmldoc.getElementsByTagName('Data')
login_user_name = ""
login_from_ip = ""
login_type = ""
for node in dataNodes:
if node.getAttribute('Name') == 'LogonType':
login_type = node.childNodes[0].nodeValue
if node.getAttribute('Name') == 'TargetUserName':
login_user_name = node.childNodes[0].nodeValue
if node.getAttribute('Name') == 'IpAddress':
login_from_ip = node.childNodes[0].nodeValue
if login_type == '10':
print("remote user login success! login_from_ip:%s,login_user_name:%s。" % (login_from_ip, login_user_name))
#port
def WinPort():
taskinfo = os.popen('tasklist /NH /FO CSV')
task = {} # task['pid'] = 'program'
line = taskinfo.readline()
while line:
line = line.replace('"', '') # UNIX编程艺术就提到Windows的CSV垃圾了
aList = line.split(',')
task[aList[1]] = aList[0]
line = taskinfo.readline()
taskinfo.close()
netinfo = os.popen('netstat -naO')
# netstat 输出的3行垃圾信息
line = netinfo.readline()
line = netinfo.readline()
line = netinfo.readline()
# netstat 输出的头也不要
line = netinfo.readline()
line = netinfo.readline()
aList = ['Proto', 'Local Address', 'Foreign Address', 'State', 'PID', 'Program name']
print(aList[0], aList[1], aList[2], aList[3], aList[4], aList[5])
while line:
aList = line.split()
if len(aList) == 4:
aList.append(aList[3])
aList[3] = ''
aList.append(task[aList[-1]])
print(aList[0], aList[1], aList[2], aList[3], aList[4], aList[5])
line = netinfo.readline()
netinfo.close()
def get_key():
key_info = psutil.net_io_counters(pernic=True).keys() # 获取网卡名称
recv = {}
sent = {}
for key in key_info:
recv.setdefault(key, psutil.net_io_counters(pernic=True).get(key).bytes_recv) # 各网卡接收的字节数
sent.setdefault(key, psutil.net_io_counters(pernic=True).get(key).bytes_sent) # 各网卡发送的字节数
return key_info, recv, sent
def get_rate(func):
import time
key_info, old_recv, old_sent = func() # 上一秒收集的数据
time.sleep(1)
key_info, now_recv, now_sent = func() # 当前所收集的数据
net_in = {}
net_out = {}
for key in key_info:
net_in.setdefault(key, (now_recv.get(key) - old_recv.get(key)) / 1024) # 每秒接收速率
net_out.setdefault(key, (now_sent.get(key) - old_sent.get(key)) / 1024) # 每秒发送速率
return key_info, net_in, net_out
while 1<1:
try:
key_info, net_in, net_out = get_rate(get_key)
for key in key_info:
print('%s\nInput:\t %-5sKB/s\nOutput:\t %-5sKB/s\n' % (key, net_in.get(key), net_out.get(key)))
except KeyboardInterrupt:
exit()
if __name__ == '__main__':
#WinPort()
winLog()