#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#filename get_linux_info.py
#获取Linux主机的信息
# titles=['Hostname','OS','Arch','Distribution','IPs','cpu','core','Mem','Data','Disk'] import paramiko
import sys ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
def conn_to_hosts(hostname,username,password,port=22):
"""连接目标主机的函数"""
try:
ssh.connect(hostname,username=username,password=password,port=port,timeout=10)
except:
print("ssh to {} failed".format(hostname))
sys.exit() def get_info(hostname,username,password,port=22):
"""通过shell命令获取主机信息""" #创建一个空字典存放收集的主机信息
infos={} def command(name,cmd):
stdin,info,stderr = ssh.exec_command(cmd)
infos[name] = str(info.readline()).replace('\n','')
#连接主机
conn_to_hosts(hostname,username,password,port=port)
#执行shell命名
command('Hostname','hostname')
command('OS','uname')
command('Arch','arch')
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" " "')
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')
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' ' '""")
command('cpu','grep "physical id" /proc/cpuinfo | sort | uniq | wc -l')
command('core','grep "processor" /proc/cpuinfo | wc -l')
command('Mem',"free -h | awk '/Mem/ {print $2}'")
command('Data',"""df -hT | grep "/$" | awk '{print "total:"$3,"used:"$4}'""")
command('Disk',"""lsblk -r | awk '/disk/ {print $1":"$4}' | tr '\n' ' '""") return infos
 #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#filename get_targetspy
#读取目标主机信息文件并转化为便于处理的格式
import re
def targets(filename):
#"""处理TXT文件"""
f = open(filename,'r')
hosts = []
for line in f.readlines():
line = str(line).replace("\n","")
line = line.strip(" ")
line = re.sub(r"\s{1,}"," ",line)
hosts.append(list(line.split(" ")))
return hosts
 #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#将获取的信息存到Excel表格中
#filename create_excel.py
import xlsxwriter
import os
import time
import get_targets
import get_linux_info titles=['Hostname','OS','Arch','Distribution','Version','IPs','cpu','core','Mem','Data','Disk'] def createfile(hostsfile):
#Excel文件名
time_format = "%Y%m%d-%H%M%S"
now = time.strftime(time_format,time.localtime())
filename = "hostinfo"+ now + ".xlsx" #创建 xlsx 文件
workbook = xlsxwriter.Workbook(filename)
#创建一个表
worksheet = workbook.add_worksheet("主机信息")
worksheet.set_column(0, len(titles), 15) #设置标题格式
format_title=workbook.add_format()
format_title.set_align('center')
format_title.set_bold()
#行坐标A
row_pos = []
for i in range(len(titles)):
row_pos.append(chr(65+i)) #写入标题
for i in range(len(titles)):
worksheet.write(row_pos[i]+"",titles[i],format_title) targets = get_targets.targets(hostsfile)
# print(targets)
for host in range(len(targets)):
hostname = targets[host][0].strip()
username = targets[host][1].strip()
password = targets[host][2].strip()
try:
port = targets[host][3].strip()
except:
port = ''
#使用分析出的账户密码登录目标主机
# global port
try:
hostinfo = get_linux_info.get_info(hostname,username,password,port)
print('Geting {} info'.format(hostname))
except:
print("can't ssh to host:"+hostname)
continue
#连接成功之后开始写入到Excel文件
for i in range(len(titles)):
col_pos = str(host + 2)
title = titles[i]
worksheet.write(row_pos[i]+col_pos,hostinfo[title])
workbook.close()
 #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#filename main.py
import create_excel
import os
import time
if __name__ == '__main__':
hostfile='hosts.txt'
print("Geting host info 。。。。。。")
create_excel.createfile(hostfile)
hosts.txt内容:
192.168.1.125 root root 2214

用python实现批量获取Linux主机简要信息并保存到Excel中 unstable 1.1的更多相关文章

  1. python爬取当当网的书籍信息并保存到csv文件

    python爬取当当网的书籍信息并保存到csv文件 依赖的库: requests #用来获取页面内容 BeautifulSoup #opython3不能安装BeautifulSoup,但可以安装Bea ...

  2. python 数据如何保存到excel中--xlwt

    第一步:下载xlwt 首先要下载xlwt,(前提是你已经安装好了Python) 下载地址:  https://pypi.python.org/pypi/xlwt/   下载第二个   第二步:安装xl ...

  3. python爬取数据保存到Excel中

    # -*- conding:utf-8 -*- # 1.两页的内容 # 2.抓取每页title和URL # 3.根据title创建文件,发送URL请求,提取数据 import requests fro ...

  4. python批量修改linux主机密码

    +++++++++++++++++++++++++++++++++++++++++++标题:python批量修改Linux服务器密码时间:2019年2月24日内容:基于python实现批量修改linu ...

  5. 使用 python 获取 Linux 的 IP 信息(通过 ifconfig 命令)

    我们可以使用 python 代码通过调用 ifconfig 命令来获取 Linux 主机的 IP 相关信息,包括:网卡名称.MAC地址.IP地址等. 第一种实现方式: #!/usr/bin/pytho ...

  6. 运用Python语言编写获取Linux基本系统信息(三):Python与数据库编程,把获取的信息存入数据库

    运用Python语言编写获取Linux基本系统信息(三):Python与数据库编程 有关前两篇的链接: 运用Python语言编写获取Linux基本系统信息(一):获得Linux版本.内核.当前时间 运 ...

  7. 运用Python语言编写获取Linux基本系统信息(二):文件系统使用情况获取

    本文跟着上一篇文章继续写,上一篇文章的链接 运用Python语言编写获取Linux基本系统信息(一):获得Linux版本.内核.当前时间 一.随便说说 获取文件系统使用情况的思路和上一篇获取主要系统是 ...

  8. python使用traceback获取详细的异常信息

    原创来自:https://blog.csdn.net/mengtao0609/article/details/55049059 python使用traceback获取详细的异常信息 2017年02月1 ...

  9. 批量生成随机字符串并保存到excel

    需要导入jxl.jar,commons-lang-2.6.jar 链接:https://pan.baidu.com/s/1NPPh24XWxkka68x2JQYlYA 提取码:jvj3 链接:http ...

随机推荐

  1. valueOf()对象返回值

    valueOf()对象返回值 Array数组的元素被转换为字符串,这些字符串由逗号分隔,连接在一起.其操作与 Array.toString 和 Array.join 方法相同. Boolean为Boo ...

  2. linux性能分析工具Sysstat

  3. shell使用标准输出返回函数值

  4. Win10电脑查看已连接过WiFi密码的命令

    运行中输入CMD,回车,打开命令行窗口. 输入:netsh wlan show profiles    执行后,会列出搜友已连接过的WiFi名字: 输入:netsh wlan show profile ...

  5. Beta-星期五

    所属课程 https://edu.cnblogs.com/campus/xnsy/SoftwareEngineeringClass 作业要求  https://edu.cnblogs.com/camp ...

  6. CSS书写顺序提高可读性

    属性书写顺序 [建议] 同一 rule set 下的属性在书写时,应按功能进行分组,并以 Formatting Model(布局方式.位置) > Box Model(尺寸) > Typog ...

  7. MFC的Dlg和App什么区别?应用程序类与对话框类

    MFC里有个app类..他是一个项目工程类,有一个全局的实例化.theApp你可以理解为整个项目的实例,它重载了入口函数,所有的窗口神马的,都是在这个类里实例化的. dlg是对话框,是一个窗口.一个程 ...

  8. 15_1.InetAddress

    import java.net.InetAddress; import java.net.UnknownHostException; public class InetAdressTest { pub ...

  9. Gitbook环境搭建及制作——2019年10月24日

    1.gitbook介绍 GitBook 是一个基于 Node.js 的命令行工具,支持 Markdown 和 AsciiDoc 两种语法格式,可以输出 HTML.PDF.eBook 等格式的电子书.可 ...

  10. SQL SERVER视图对查询效率的提高

    SQL SERVER视图不仅可以实现许多我们需要的功能,而且对于SQL SERVER查询效率的提高也有帮助,下面一起来了解一下. 有两张数据表:A和B,其中A的记录为2万条左右,而B中的数据为200万 ...