python运维01-获取系统基础信息

1.获取系统主机名,IP,MAC地址

import socket
import uuid

macs = uuid.UUID(int = uuid.getnode()).hex[-12:]
mac = ":".join([macs[e:e+2] for e in range(0,11,2)])

myname = socket.getfqdn(socket.gethostname())
myaddr = socket.gethostbyname(myname)

print mac,myname,myaddr
这个有一些问题,如果是多网卡的情况,就会只输出一个网卡信息。
注意注意:centos6上的默认python版本是2.6.6,这个版本下载的psutil相对来说功能较少,有些功能完全没有。所以至少使用python 2.7的,或者是python3的才可以。

2.获取CPU信息

使用psutil模块,相关的几个用法:
'cpu_count':获取物理cpu的颗数,逻辑cpu颗数
'cpu_percent':获取cpu的使用率
'cpu_stats':获取cpu的使用状态
'cpu_times':获取用户的cpu时间比
'cpu_times_percent':
 
CPU利用率有以下几个部分:
User Time:执行用户进程的时间百分比
System Time:执行内核进程和中断的时间百分比
Wait IO:由于IO等待而使CPU处于idle(空闲)状态的时间百分比
Idle:cpu处于idle状态的时间百分比
#!/usr/bin/env python
# coding:utf-8

import psutil
print psutil.cpu_count()  #逻辑cpu个数
print psutil.cpu_count(logical=False)   #物理cpu个数
print psutil.cpu_percent()   #cpu综合使用率
#是否(True/False)以列表形式列出单个cpu的使用率,interval表示统计的时间间隔
print psutil.cpu_percent(interval=1,percpu=True)  
print psutil.cpu_stats()
print psutil.cpu_times()
print psutil.cpu_times_percent() 
输出如下:
1
1
0.0
[0.0]
scpustats(ctx_switches=2163596, interrupts=4943830, soft_interrupts=4363493, syscalls=0)
scputimes(user=152.39, nice=83.79, system=160.09, idle=14650.07, iowait=431.54, irq=0.0, softirq=146.8, steal=0.0, guest=0.0, guest_nice=0.0)
scputimes(user=0.0, nice=0.0, system=0.0, idle=100.0, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)

3.获取内存信息

使用psutil模块,获取内存的以下信息:
total:总内存数
used:已使用的内存数
free:空闲内存数
buffers:缓存使用数
cache:缓存使用数
swap:交换分区使用数
分别使用psutil.virtual_memory()和psutil.swap_memory()方法来获得这些信息,如下
#!/usr/bin/env python
# coding:utf-8

import psutil
mem = psutil.virtual_memory()  #内存信息
swap = psutil.swap_memory()    #分区信息

print mem
print swap

unit = 1024*1024
print mem.total
print "总内存数: %s MB" % (mem.total/unit)
print "已用内存数: %s MB" % (mem.used/unit)
print "空闲内存数: %s MB" % (mem.free/unit)
print "内存使用率: %s %%" % (mem.percent)
输出如下:
svmem(total=1040871424, available=378040320, percent=63.7, used=507797504, free=85389312, active=218533888, inactive=597471232, buffers=0, cached=447684608, shared=3559424)
sswap(total=2147479552, used=211124224, free=1936355328, percent=9.8, sin=39768064, sout=365432832)
1040871424
总内存数: 992 MB
已用内存数: 484 MB
空闲内存数: 81 MB
内存使用率: 63.7 %

4.磁盘信息

磁盘信息包括如下:
read_count:读IO数
write_count:写IO数
read_bytes:IO读字节数
write_bytes:IO写字节数
read_times:磁盘读时间
write_times:磁盘写时间
如下:
#!/usr/bin/env python
# coding:utf-8

import psutil
print psutil.disk_partitions()   #获取磁盘分区信息
print psutil.disk_io_counters()  #获取磁盘总的IO个数,读写信息
print psutil.disk_io_counters(perdisk=True)  #"perdisk=True"获取单个分区的IO个数,读写信息
#获取单个分区的使用情况
print psutil.disk_usage('/')
print psutil.disk_usage('/home')
print psutil.disk_usage('/boot')
输出如下:
#获取磁盘分区信息
[sdiskpart(device='/dev/mapper/cl-root', mountpoint='/', fstype='xfs', opts='rw,relatime,attr2,inode64,noquota'), sdiskpart(device='/dev/sda1', mountpoint='/boot', fstype='xfs', opts='rw,relatime,attr2,inode64,noquota'), sdiskpart(device='/dev/mapper/cl-home', mountpoint='/home', fstype='xfs', opts='rw,relatime,attr2,inode64,noquota')]
#获取磁盘总的IO个数,读写信息
sdiskio(read_count=256660, write_count=134297, read_bytes=13238923264, write_bytes=4005574656, read_time=20557551, write_time=33302683, read_merged_count=9017, write_merged_count=95697, busy_time=1333693)
"perdisk=True"获取单个分区的IO个数,读写信息,以字典形式列出
{'sr0': sdiskio(read_count=0, write_count=0, read_bytes=0, write_bytes=0, read_time=0, write_time=0, read_merged_count=0, write_merged_count=0, busy_time=0), 
'sda2': sdiskio(read_count=123678, write_count=19237, read_bytes=6608251392, write_bytes=2001718272, read_time=10145957, write_time=2467917, read_merged_count=9013, write_merged_count=95697, busy_time=638950), 'sda1': sdiskio(read_count=350, write_count=16, read_bytes=22985728, write_bytes=2138112, read_time=1993, write_time=245, read_merged_count=4, write_merged_count=0, busy_time=1991), 
'dm-2': sdiskio(read_count=422, write_count=10, read_bytes=1427456, write_bytes=2117632, read_time=321, write_time=23, read_merged_count=0, write_merged_count=0, busy_time=339), 
'dm-0': sdiskio(read_count=122235, write_count=25817, read_bytes=6564831744, write_bytes=1634167808, read_time=10227519, write_time=3736611, read_merged_count=0, write_merged_count=0, busy_time=640372), 
'dm-1': sdiskio(read_count=9975, write_count=89217, read_bytes=41426944, write_bytes=365432832, read_time=181761, write_time=27097887, read_merged_count=0, write_merged_count=0, busy_time=52041)}
#获取单个分区的使用情况
sdiskusage(total=43985149952, used=6855770112, free=37129379840, percent=15.6)
sdiskusage(total=21472735232, used=43532288, free=21429202944, percent=0.2)
sdiskusage(total=1063256064, used=181338112, free=881917952, percent=17.1)

5.获取网络信息

网络信息包含以下几个方面:
bytes_sent:发送字节数
bytes_recv:接受字节数
packets_sent:发送数据报数
packets_recv:接收数据报数
这些信息使用psutil.net_io_counters()获取
#获取网络总的IO信息,默认pernic=False
In [12]: psutil.net_io_counters()
Out[12]: snetio(bytes_sent=10153696486, bytes_recv=9501486415, packets_sent=81448497, packets_recv=94917339, errin=0, errout=0, dropin=0, dropout=0)

#获取每个网络接口的IO信息
In [13]: psutil.net_io_counters(pernic=True)
Out[13]: 
{'eth0': snetio(bytes_sent=4565743301, bytes_recv=3913547648, packets_sent=6402022, packets_recv=19871113, errin=0, errout=0, dropin=0, dropout=0),
 'lo': snetio(bytes_sent=5588080423, bytes_recv=5588080423, packets_sent=75048149, packets_recv=75048149, errin=0, errout=0, dropin=0, dropout=0)}
获取网卡信息:
In [11]: psutil.net_if_addrs()
Out[11]: 
{'eth0': [snic(family=<AddressFamily.AF_INET: 2>, address='192.168.0.116', netmask='255.255.255.0', broadcast='192.168.0.255', ptp=None),
  snic(family=<AddressFamily.AF_INET6: 10>, address='fe80::f68e:38ff:fe85:febf%eth0', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None),
  snic(family=<AddressFamily.AF_PACKET: 17>, address='f4:8e:38:85:fe:bf', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)],
 'lo': [snic(family=<AddressFamily.AF_INET: 2>, address='127.0.0.1', netmask='255.0.0.0', broadcast=None, ptp=None),
  snic(family=<AddressFamily.AF_INET6: 10>, address='::1', netmask='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', broadcast=None, ptp=None),
  snic(family=<AddressFamily.AF_PACKET: 17>, address='00:00:00:00:00:00', netmask=None, broadcast=None, ptp
通过这个也可以获取网卡的网卡名,IP地址,MAC地址等信息,如下:
#!/usr/bin/env python3
# coding:utf-8
import psutil
netinfo = psutil.net_if_addrs()

for NetName,Info in netinfo.items():
    if len(Info) < 3:
        pass
    elif NetName == "lo":
        pass
    else:
        Netname = NetName
        ipaddr = Info[0].address
        ipMAC  = Info[2].address
        print(NetName,ipaddr,ipMAC)
        print("--------------------------")
输出如下:
[root@node10 ~]# python testnet.py 
('enp0s3', '192.168.0.117', '08:00:27:73:fc:5b')
--------------------------

获取网卡状态信息:

In [2]: psutil.net_if_stats()
Out[2]: 
{'enp0s3': snicstats(isup=True, duplex=2, speed=1000, mtu=1500),
 'lo': snicstats(isup=True, duplex=0, speed=0, mtu=65536),
 'virbr0': snicstats(isup=True, duplex=0, speed=0, mtu=1500),
 'virbr0-nic': snicstats(isup=False, duplex=2, speed=10, mtu=1500)}
获取网路连接信息:
In [4]: psutil.net_connections()
Out[4]: 
[sconn(fd=15, family=2, type=1, laddr=('127.0.0.1', 39920), raddr=(), status='LISTEN', pid=7662),
 sconn(fd=48, family=2, type=1, laddr=('127.0.0.1', 35170), raddr=('127.0.0.1', 58842), status='ESTABLISHED', pid=2626),
 sconn(fd=3, family=2, type=1, laddr=('192.168.0.117', 22), raddr=('192.168.0.110', 58002), status='ESTABLISHED', pid=5403)]
可以得到当前主机的网络连接状态。

6.其他信息

获取用户登录情况信息:
In [5]: psutil.users()
Out[5]: 
[suser(name='root', terminal=':0', host='localhost', started=1506392704.0),
 suser(name='root', terminal='pts/0', host='localhost', started=1506392704.0),
 suser(name='root', terminal='pts/1', host='desktop-8356', started=1506409216.0)]
 
登录用户名,登录终端,登陆主机的主机名,登录时间戳。

7.获取类似passwd文件的用户信息

In [23]: psutil.pwd.getpwall()
Out[23]: 
[pwd.struct_passwd(pw_name='root', pw_passwd='x', pw_uid=0, pw_gid=0, pw_gecos='root', pw_dir='/root', pw_shell='/bin/bash'),
 pwd.struct_passwd(pw_name='bin', pw_passwd='x', pw_uid=1, pw_gid=1, pw_gecos='bin', pw_dir='/bin', pw_shell='/sbin/nologin'),
 pwd.struct_passwd(pw_name='daemon', pw_passwd='x', pw_uid=2, pw_gid=2, pw_gecos='daemon', pw_dir='/sbin', pw_shell='/sbin/nologin')]
类似上面的输出格式,可以获取用户的一些信息。
posted @ 2017-10-10 09:06  flyme123  阅读(1134)  评论(0编辑  收藏  举报