#!/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. 浏览器报406 错误:The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers

    The resource identified by this request is only capable of generating responses with characteristics ...

  2. C/C++字符串和其他类型转换

    C语言中string char int类型转换 转载自:http://blog.sina.com.cn/s/blog_63041bb801016b4x.html ,char型数字转换为int型 &qu ...

  3. vue,一路走来(4)--vuex

    补充 调用外部js,详细介绍如何调用函数. 1.首先在main.js里引用文件 2.然后算是和jquery框架一样需要所谓的入口函数吧 不过令我烦恼的是,在应用的文件中需要把他包含在另一个函数里,才可 ...

  4. HDU 6613 Squrirrel 树形dp

    题意:给你一颗树,你可以把这棵树上的一条边的边权变为0,现在让你选一个根,让所有点到这个点的最大距离尽量的小.如果有多个根的最大距离距离相同,输出编号最小的边. 思路:如果没有把边权变为0的操作,这个 ...

  5. mongodb使用简介

    mongodb简介 在使用nodejs时候,需要存储一些简单json数据的情况下,很多人会推荐使用mongodb.mongodb是一个文档型数据库,在 sql 中,数据层级是:数据库(db) -> ...

  6. center os7 安装mysql

    安装mariadb MariaDB数据库管理系统是MySQL的一个分支,主要由开源社区在维护,采用GPL授权许可.开发这个分支的原因之一是:甲骨文公司收购了MySQL后,有将MySQL闭源的潜在风险, ...

  7. https://geewu.gitbooks.io/rabbitmq-quick/content/RabbitMQ%E5%9F%BA%E7%A1%80%E6%93%8D%E4%BD%9C.html

    https://geewu.gitbooks.io/rabbitmq-quick/content/RabbitMQ%E5%9F%BA%E7%A1%80%E6%93%8D%E4%BD%9C.html

  8. BZOJ3227 [sdoi2008]红黑树

    贪心什么的太神仙了( 老老实实dp于是就是沙茶题了 f[i][d][0/1]表示i个节点bh为d当前节点颜色白/黑[好好读题是真.. 转移一下然后就可以打表了( 由于我们发现这玩意很好卡有很好的性质( ...

  9. poj 3468: A Simple Problem with Integers (树状数组区间更新)

    题目链接: http://poj.org/problem?id=3468 题目是对一个数组,支持两种操作 操作C:对下标从a到b的每个元素,值增加c: 操作Q:对求下标从a到b的元素值之和. 这道题也 ...

  10. 百度小程序-swiper组件

    .swan <!-- 轮播图S --> <view class="swiper-box"> <swiper class="banner&qu ...