subprocess模块的使用
获取基本信息
import subprocess
class Base():
def run_cmd(self,cmd): #定义一个执行函数
stat,result = subprocess.getstatusoutput(cmd) #返回一个状态码和执行结果
if not stat:
return self.parse(result)
def parse(self,data): #处理数据,返回数据
if data.endswith('_'):
data = data[:-1]
return data
"""
操作系统 uname -s
系统架构 uname -m
系统版本信息 cat /etc/redhat-release |tr -s ' ' | tr ' ' '_'
主机名
内核信息
"""
def cmd_handle(self): #调用函数执行来获取数据
result = {
'os_name': self.run_cmd('uname -s').strip(),
'machine': self.run_cmd("uname -m").strip(),
'os_version': self.run_cmd("cat /etc/redhat-release |tr -s ' ' | tr ' ' '_'"),
'hostname': self.run_cmd("hostname").strip(),
'kernel': self.run_cmd('uname -r')
}
return result
硬盘信息
import subprocess
class Disk():
def __init__(self):
self.file = "task/模块化/cmdb/R710-disk-info.txt"
self.cmd = "grep -v '^$' %s" % self.file
def run_cmd(self, cmd):
stat, result = subprocess.getstatusoutput(cmd)
if not stat:
return self.parse(result)
def parse(self, data):
info_disk = {}
key_map = {
'Raw Size':'raw', #原始磁盘容量
'Slot Number':'slot', #插槽号
'PD Type':'pd', #接口类型
'Coerced Size':'coreced' #强制磁盘容量
}
disk_list = [ disk for disk in data.split('Enclosure Device ID: 32') if disk]
for item in disk_list:
single_slot = {}
for line in item.splitlines():
line = line.strip()
if len(line.split(':')) == 2:
key, val = line.split(':')
key,val = key.strip(), val.strip()
if key in key_map:
single_slot[key_map[key]] = val
info_disk[single_slot["slot"]] = single_slot
return info_disk
def cmd_handle(self):
"""获取R710数据接口"""
return self.run_cmd(self.cmd)
if __name__ == '__main__':
disk_obj = Disk()
info = disk_obj.cmd_handle()
print(info)
内存信息
import subprocess
class Cpu():
def run_cmd(self,cmd):
"""执行命令,并返回结果"""
stat, cpu_msg = subprocess.getstatusoutput(cmd)
if not stat:
return self.parse(cpu_msg)
def parse(self,data):
"""处理数据"""
return data
def cmd_handle(self):
"""获取数据的接口 """
cpu_msg = {
"physical_count": self.run_cmd("cat /root/cpuinfo.txt|grep 'physical id' /proc/cpuinfo | sort -u | wc -l"),
"physical_cores": self.run_cmd("cat /root/cpuinfo.txt|grep 'cpu cores' /proc/cpuinfo | uniq |cut -d: -f2").strip(),
"model_name":self.run_cmd("cat /root/cpuinfo.txt |grep 'model name' /proc/cpuinfo | uniq |cut -d: -f2|tr ' ' '_'"),
"cpu_type":self.run_cmd("cat /root/cpuinfo.txt |uname -p")
}
return cpu_msg
汇总信息
import sys,os,json,requests
Base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# print(Base_dir)
sys.path.insert(0,Base_dir)
# print(sys.path)
from cmdb import cpu_info,base_info,mem_info,disk_info
base = base_info.Base().cmd_handle()
cpu = cpu_info.Cpu().cmd_handle()
mem = mem_info.Memory().cmd_handle()
disk=disk_info.Disk().cmd_handle()
host_info={}
host_info['base_info']=base
host_info['cpu_info']=cpu
host_info['mem_info']=mem
host_info['disk_info'] = disk
# print(host_info)
def post_info(data):
requests.post(url='http://127.0.0.1:8000/cmdb/asset/', data=json.dumps(data))
post_info(host_info)
time,daytime模块
import datetime,time
inp = input("请输入预约时间(1970-1-1 00:00:00)")
nowtime = datetime.datetime.now()
restime = datetime.datetime.strptime(inp,'%Y-%m-%d %H:%M:%S')
t = restime - nowtime
if t.days >= 0 :
h,s = divmod(t.seconds, 3600)
m,s =divmod(s,60)
print(f"{t.days}天{h}小时{m}分{s}秒")
else:
print("时间无法倒流!")
还需区别注意的点
input:print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1522071229.4780636)))
output:2018-03-26 21:33:49
input:print(time.strptime('2018-03-26 21:41', "%Y-%m-%d %H:%M"))
output:time.struct_time(tm_year=2018, tm_mon=3, tm_mday=26, tm_hour=21, tm_min=41, tm_sec=0, tm_wday=0, tm_yday=85, tm_isdst=-1)