12.6 系统运维

     

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
1E1B2439066B51A6B7310BD52D7B4E6F.jpg

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

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,185评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,652评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,524评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,339评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,387评论 6 391
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,287评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,130评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,985评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,420评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,617评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,779评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,477评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,088评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,716评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,857评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,876评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,700评论 2 354

推荐阅读更多精彩内容