1 #!/usr/bin/env python3 2 # -*- coding: utf-8 -*- 3 #filename get_linux_info.py 4 #获取Linux主机的信息 5 # titles=['Hostname','OS','Arch','Distribution','IPs','cpu','core','Mem','Data','Disk'] 6 7 import paramiko 8 import sys 9 10 ssh = paramiko.SSHClient() 11 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy) 12 def conn_to_hosts(hostname,username,password,port=22): 13 """连接目标主机的函数""" 14 try: 15 ssh.connect(hostname,username=username,password=password,port=port,timeout=10) 16 except: 17 print("ssh to {} failed".format(hostname)) 18 sys.exit() 19 20 def get_info(hostname,username,password,port=22): 21 """通过shell命令获取主机信息""" 22 23 #创建一个空字典存放收集的主机信息 24 infos={} 25 26 def command(name,cmd): 27 stdin,info,stderr = ssh.exec_command(cmd) 28 infos[name] = str(info.readline()).replace('\n','') 29 #连接主机 30 conn_to_hosts(hostname,username,password,port=port) 31 #执行shell命名 32 command('Hostname','hostname') 33 command('OS','uname') 34 command('Arch','arch') 35 command('Distribution','egrep ^ID= /etc/os-release | egrep -o "[a-z]*" || head -1 /etc/issue | egrep -o "[A-Za-z]{2,}|[0-9]{1,}.[0-9]{1,}" | tr "\n" " "') 36 command('Version','egrep ^VERSION_ID /etc/os-release | egrep -o "[0-9]{1,}\.?[0-9]{0,}?" || egrep -o "[0-9]{1,}\.?[0-9]{0,}?" /etc/issue') 37 command('IPs',"""ifconfig | awk '/inet/ {print $2}' | egrep -o "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" | tr '\n' ' '""") 38 command('cpu','grep "physical id" /proc/cpuinfo | sort | uniq | wc -l') 39 command('core','grep "processor" /proc/cpuinfo | wc -l') 40 command('Mem',"free -h | awk '/Mem/ {print $2}'") 41 command('Data',"""df -hT | grep "/$" | awk '{print "total:"$3,"used:"$4}'""") 42 command('Disk',"""lsblk -r | awk '/disk/ {print $1":"$4}' | tr '\n' ' '""") 43 44 return infos
1 #!/usr/bin/env python3 2 # -*- coding: utf-8 -*- 3 #filename get_targetspy 4 #读取目标主机信息文件并转化为便于处理的格式 5 import re 6 def targets(filename): 7 #"""处理TXT文件""" 8 f = open(filename,'r') 9 hosts = [] 10 for line in f.readlines(): 11 line = str(line).replace("\n","") 12 line = line.strip(" ") 13 line = re.sub(r"\s{1,}"," ",line) 14 hosts.append(list(line.split(" "))) 15 return hosts
1 #!/usr/bin/env python3 2 # -*- coding: utf-8 -*- 3 #将获取的信息存到Excel表格中 4 #filename create_excel.py 5 import xlsxwriter 6 import os 7 import time 8 import get_targets 9 import get_linux_info 10 11 titles=['Hostname','OS','Arch','Distribution','Version','IPs','cpu','core','Mem','Data','Disk'] 12 13 def createfile(hostsfile): 14 #Excel文件名 15 time_format = "%Y%m%d-%H%M%S" 16 now = time.strftime(time_format,time.localtime()) 17 filename = "hostinfo"+ now + ".xlsx" 18 19 #创建 xlsx 文件 20 workbook = xlsxwriter.Workbook(filename) 21 #创建一个表 22 worksheet = workbook.add_worksheet("主机信息") 23 worksheet.set_column(0, len(titles), 15) 24 25 #设置标题格式 26 format_title=workbook.add_format() 27 format_title.set_align('center') 28 format_title.set_bold() 29 #行坐标A 30 row_pos = [] 31 for i in range(len(titles)): 32 row_pos.append(chr(65+i)) 33 34 #写入标题 35 for i in range(len(titles)): 36 worksheet.write(row_pos[i]+"1",titles[i],format_title) 37 38 39 targets = get_targets.targets(hostsfile) 40 # print(targets) 41 for host in range(len(targets)): 42 hostname = targets[host][0].strip() 43 username = targets[host][1].strip() 44 password = targets[host][2].strip() 45 try: 46 port = targets[host][3].strip() 47 except: 48 port = '22' 49 #使用分析出的账户密码登录目标主机 50 # global port 51 try: 52 hostinfo = get_linux_info.get_info(hostname,username,password,port) 53 print('Geting {} info'.format(hostname)) 54 except: 55 print("can't ssh to host:"+hostname) 56 continue 57 #连接成功之后开始写入到Excel文件 58 for i in range(len(titles)): 59 col_pos = str(host + 2) 60 title = titles[i] 61 worksheet.write(row_pos[i]+col_pos,hostinfo[title]) 62 workbook.close()
1 #!/usr/bin/env python3 2 # -*- coding: utf-8 -*- 3 #filename main.py 4 import create_excel 5 import os 6 import time 7 if __name__ == '__main__': 8 hostfile='hosts.txt' 9 print("Geting host info 。。。。。。") 10 create_excel.createfile(hostfile)
hosts.txt内容:
192.168.1.125 root root 2214