subprocess模塊的使用
獲取基本信息
import subprocess
class Base():
def run_cmd(self,cmd): #定義一個執(zhí)行函數(shù)
stat,result = subprocess.getstatusoutput(cmd) #返回一個狀態(tài)碼和執(zhí)行結(jié)果
if not stat:
return self.parse(result)
def parse(self,data): #處理數(shù)據(jù),返回數(shù)據(jù)
if data.endswith('_'):
data = data[:-1]
return data
"""
操作系統(tǒng) uname -s
系統(tǒng)架構(gòu) uname -m
系統(tǒng)版本信息 cat /etc/redhat-release |tr -s ' ' | tr ' ' '_'
主機(jī)名
內(nèi)核信息
"""
def cmd_handle(self): #調(diào)用函數(shù)執(zhí)行來獲取數(shù)據(jù)
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' #強(qiáng)制磁盤容量
}
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數(shù)據(jù)接口"""
return self.run_cmd(self.cmd)
if __name__ == '__main__':
disk_obj = Disk()
info = disk_obj.cmd_handle()
print(info)
內(nèi)存信息
import subprocess
class Cpu():
def run_cmd(self,cmd):
"""執(zhí)行命令添寺,并返回結(jié)果"""
stat, cpu_msg = subprocess.getstatusoutput(cmd)
if not stat:
return self.parse(cpu_msg)
def parse(self,data):
"""處理數(shù)據(jù)"""
return data
def cmd_handle(self):
"""獲取數(shù)據(jù)的接口 """
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("請輸入預(yù)約時間(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("時間無法倒流!")
還需區(qū)別注意的點(diǎn)
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)