抓取服務器硬件信息腳本
阿新 • • 發佈:2018-07-13
elif values write for exceptio false etc total ddr 說明:
本例hard.py文件是抓取本地配置的腳本,然後往數據庫寫,寫之前會做判斷是否有該和數據,如果沒有才會插入,如果沒有不會插入數據
本例用的python版本是3.5,用的庫有os,sys,time,psutil,pymysql。
腳本內容如下:
本例hard.py文件是抓取本地配置的腳本,然後往數據庫寫,寫之前會做判斷是否有該和數據,如果沒有才會插入,如果沒有不會插入數據
本例用的python版本是3.5,用的庫有os,sys,time,psutil,pymysql。
腳本內容如下:
#!/usr/local/python3/bin/python3 import psutil,os,sys,pymysql,time #cpu型號 cpu_model = os.popen(‘cat /proc/cpuinfo | grep name | cut -f2 -d: | uniq -c|cut -c 10-50‘).read() cpu_count = psutil.cpu_count() cpu_core = psutil.cpu_count(logical=False) #內存相關 info = psutil.virtual_memory() #總內存(M) total_memory = int(info.total/1024/1024/1024) #用了多少內存(M) use_memory = int(info.used/1024/1024) #空閑內存(M) free_memory = int(info.free/1024/1024) #磁盤容量 D_result = 0 Disk_size = os.popen("fdisk -l|grep Disk|grep -v identifier|awk ‘{print $3}‘|sed ‘s/,//g‘").read() with open(‘/tmp/a.txt‘,‘w‘) as f: f.write(Disk_size) with open(‘/tmp/a.txt‘,‘r‘) as f1: for line in f1: line = line.strip(‘\n‘) D_result = D_result + float(line) #IP地址 out = os.popen("ifconfig | grep ‘inet addr:‘ | grep -v ‘127.0.0.1‘ | cut -d: -f2 | awk ‘{print $1}‘ | head -1").read() ip = out.split(‘\n‘)[0] print(‘‘‘ 機器配置如下: cpu型號: %s cpu邏輯數量: %s cpu物理核心數: %s 內存(G): %s 磁盤容量(G): %s IP地址: %s ‘‘‘%(cpu_model,cpu_count,cpu_core,total_memory,D_result,ip)) #插入庫 db= pymysql.connect(host="192.168.1.14",user="abc",password="abc",db="cmdb",port=3306) cur = db.cursor() check_ip_sql = "select ip from cmdb_host where ip=‘%s‘"%ip cur.execute(check_ip_sql) result = cur.fetchone() db.commit() #判斷插入的數據是否存在,如果存在不插入,反之則插入數據 if result == None: print("開始添加記錄.......") time.sleep(1) sql_insert = "insert into cmdb_host(cpu,mem,disk,ip) values(‘%s‘,‘%sG‘,‘%sG‘,‘%s‘);" %(cpu_count,total_memory,D_result,ip) try: cur.execute(sql_insert) #提交 db.commit() print("添加成功!^_^") except Exception as e: #錯誤回滾 db.rollback() finally: db.close() elif ip == result[0]: print("此條記錄已添加過") pass
抓取服務器硬件信息腳本