用python实现批量获取Linux主机简要信息并保存到Excel中 unstable 1.1
#!/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的更多相关文章
- python爬取当当网的书籍信息并保存到csv文件
python爬取当当网的书籍信息并保存到csv文件 依赖的库: requests #用来获取页面内容 BeautifulSoup #opython3不能安装BeautifulSoup,但可以安装Bea ...
- python 数据如何保存到excel中--xlwt
第一步:下载xlwt 首先要下载xlwt,(前提是你已经安装好了Python) 下载地址: https://pypi.python.org/pypi/xlwt/ 下载第二个 第二步:安装xl ...
- python爬取数据保存到Excel中
# -*- conding:utf-8 -*- # 1.两页的内容 # 2.抓取每页title和URL # 3.根据title创建文件,发送URL请求,提取数据 import requests fro ...
- python批量修改linux主机密码
+++++++++++++++++++++++++++++++++++++++++++标题:python批量修改Linux服务器密码时间:2019年2月24日内容:基于python实现批量修改linu ...
- 使用 python 获取 Linux 的 IP 信息(通过 ifconfig 命令)
我们可以使用 python 代码通过调用 ifconfig 命令来获取 Linux 主机的 IP 相关信息,包括:网卡名称.MAC地址.IP地址等. 第一种实现方式: #!/usr/bin/pytho ...
- 运用Python语言编写获取Linux基本系统信息(三):Python与数据库编程,把获取的信息存入数据库
运用Python语言编写获取Linux基本系统信息(三):Python与数据库编程 有关前两篇的链接: 运用Python语言编写获取Linux基本系统信息(一):获得Linux版本.内核.当前时间 运 ...
- 运用Python语言编写获取Linux基本系统信息(二):文件系统使用情况获取
本文跟着上一篇文章继续写,上一篇文章的链接 运用Python语言编写获取Linux基本系统信息(一):获得Linux版本.内核.当前时间 一.随便说说 获取文件系统使用情况的思路和上一篇获取主要系统是 ...
- python使用traceback获取详细的异常信息
原创来自:https://blog.csdn.net/mengtao0609/article/details/55049059 python使用traceback获取详细的异常信息 2017年02月1 ...
- 批量生成随机字符串并保存到excel
需要导入jxl.jar,commons-lang-2.6.jar 链接:https://pan.baidu.com/s/1NPPh24XWxkka68x2JQYlYA 提取码:jvj3 链接:http ...
随机推荐
- 2018-2-13-C#-复制列表
title author date CreateTime categories C# 复制列表 lindexi 2018-2-13 17:23:3 +0800 2018-2-13 17:23:3 +0 ...
- mysql 联合表查询从表即使有索引依然ALL的一个原因
那就是主表和从表的关联字段的编码方式不一样!!! 晕啊,折腾了半天才发现,可能是不知道啥时候mysql更改主体编码方式了,结果导致后来新建的表的关联字段和之前的主表的字段的编码方式不一样 改成一样的编 ...
- svnkit 异常:Exception in thread "main" org.tmatesoft.svn.core.SVNException: svn: E200030: SQLite error
https://stackoverflow.com/questions/16063105/org-tmatesoft-sqljet-core-sqljetexception-busy-error-co ...
- Hadoop的基础命令
首次使用Hadoop时,格式化文件系统命令:hdfs namenode -format 启动HDFS:start-dfs.sh 启动YARN:start-all.sh start-all.sh等价于s ...
- boost graph
Boost Graph provides tools to work with graphs. Graphas are two-dimensional point clouds with any nu ...
- webpack 图片文件处理loader
目录结构: 引用图片: body { /*background: red;*/ /*background: url("../img/test2.jpg"); 小图片*/ backg ...
- 每天一个linux命令:which(17)
which which命令用于查找并显示给定命令的绝对路径,环境变量PATH中保存了查找命令时需要遍历的目录.which指令会在环境变量$PATH设置的目录里查找符合条件的文件.也就是说,使用whic ...
- idea将本地项目推送到git远程库
如何将本地项目推送到github远程仓库? 1. 在github上创建一个仓库,取名mybatis 2. 在idea中将项目交由git管理 注意,文件名会变红了, 说明这些文件在git工作区,但还没规 ...
- AT2000 Leftmost Ball(计数dp+组合数学)
传送门 解题思路 设\(f[i][j]\)表示填了\(i\)个白色,\(j\)种彩色的方案数,那么显然\(j<=i\).考虑这个的转移,首先可以填一个白色,就是\(f[i][j]=f[i-1][ ...
- [HDU2294]Pendant
题目:Pendant 链接:http://acm.hdu.edu.cn/showproblem.php?pid=2294 分析: 1)f[i][j]表示长度为i,有j种珍珠的吊坠的数目. $f[i][ ...