python3练习存档

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()

 

转载于:https://my.oschina.net/wowlinda/blog/3035571

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值