使用psutil获取系统信息

2017-11-22  本文已影响60人  无神

在Python中,我们可以使用psutil这个第三方模块方便的获取到系统信息。顾名思义,psutil = process and system utilities,它不仅可以通过一两行代码实现系统监控,还可以跨平台使用,支持Linux/UNIX/OSX/Windows等,是系统管理员和运维小伙伴不可或缺的必备模块。

使用psutil获取信息的Python记录如下:

#-*-coding: utf-8-*-
import psutil

c = psutil.cpu_count() #CPU 逻辑数量
c1 = psutil.cpu_count(logical=False) #CPU 物理核心
print('CPU 逻辑数量 %d' % c)
print('CPU 物理核心 %d' % c1)

time = psutil.cpu_times() #统计CPU的用户/系统/空闲时间
print(time)

#实现类似top命令的CPU使用率,每秒刷新一次,累计n次

def top(n):

    for x in range(n):
       list = psutil.cpu_percent(interval=1, percpu=True)
       print(list)

#top(10)

#获取内存信息
m1 = psutil.virtual_memory() #获取物理内存信息,返回以字节为单位的整数
m2 = psutil.swap_memory() #获取交换内存信息,返回以字节为单位的整数
print(m1)
print(m2)

#获取磁盘信息
print('--------获取磁盘信息---------')
d1 = psutil.disk_partitions() #磁盘分区信息
d2 = psutil.disk_io_counters() #磁盘IO
d3 = psutil.disk_usage('/') #磁盘使用情况
print(d1)
print(d2)
print(d3)

#获取网络信息  此处需要超级权限
# print('-----------获取网络信息-----------')
# netc = psutil.net_io_counters() # 获取网络读写字节/包的个数
# address = psutil.net_if_addrs() # 获取网络接口信息
# net_status = psutil.net_if_stats()# 获取网络接口状态
# net_con = psutil.net_connections() #获取网络连接
# print(netc)
# print(address)
# print(net_status)
# print(net_con)

#获取进程信息
pids = psutil.pids() #get all process ids
print(pids)

currentp = psutil.Process(1000) #use pid get current process
print(currentp)

pname = currentp.name() #name
print(pname)

pexe = currentp.exe() #process exe path
print(pexe)

pcwd = currentp.cwd() #process work dir
print(pcwd)

pcmdline = currentp.cmdline() #process start command line
print(pcmdline)

ppid = currentp.ppid()
print(ppid)

parent = currentp.parent()
print(parent)

children = currentp.children() #get children list
print(children)

status = currentp.status()
print(status)

username = currentp.username()
print(username)

create_time = currentp.create_time() #process create time
print(create_time)

terminal = currentp.terminal()
print(terminal)

cputime = currentp.cpu_times() #process use cpu time
print(cputime)

memory_info = currentp.memory_info() #process use memory info
print(memory_info)

open_files = currentp.open_files()
print(open_files)

connections = currentp.connections() #network connections
print(connections)

num_threads = currentp.num_threads() #process thread number
print(num_threads)

threads = currentp.threads() #all threads info
print(threads)

environ = currentp.environ() #进程环境变量
print(environ)

terminate = currentp.terminate() #end process
print(terminate)

温馨提示:获取网络连接和root用户的进程信息需要root权限

上一篇 下一篇

猜你喜欢

热点阅读