用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 ...
随机推荐
- query_module - 向内核查询和模块有关的各个位
总览 #include <linux/module.h> int query_module(const char *name, int which,void *buf, size_t bu ...
- Sass函数:Opacity函数-opacify()、fade-in()函数
这两个函数是用来对已有颜色的透明度做一个加法运算,会让颜色更加不透明.其接受两个参数,第一个参数是原始颜色,第二个参数是你需要增加的透明度值,其取值范围主要是在 0~1 之间.当透明度值增加到大于 1 ...
- Sass-@if的使用
@if 指令是一个 SassScript,它可以根据条件来处理样式块,如果条件为 true 返回一个样式块,反之 false 返回另一个样式块.在 Sass 中除了 @if 之,还可以配合 @else ...
- linux 性能测试之基准测试工具
https://niyunjiu.iteye.com/blog/316302 system: lmbench unixbench5.1.2 ubench freebench nbench ltp xf ...
- .net core 操作oracle
依赖项——右键——管理NuGet程序包——浏览——输入以下内容 oracle.ManagedDataAccess.core(记得勾选包括预发行版) 在页面中加入操作数据库的方法 public IAct ...
- 【串线篇】Mybatis缓存之缓存查询顺序
1. 不会出现一级缓存和二级缓存中有同一个数据.因为二级缓存是在一级缓存关闭之后才有的 2.任何时候都是先看二级缓存.再看一级缓存,如果大家都没有就去查询数据库,数据库的查询后的结果放在一级缓存中了: ...
- BZOJ1899 [Zjoi2004]Lunch 午餐 贪心+DP
题目传送门 https://lydsy.com/JudgeOnline/problem.php?id=1899 题解 如果只有一个窗口,那么可以这样考虑:因为最后一个人打完饭的时间是固定的,那么不如就 ...
- CF240E Road Repairs
最小树形图+输出方案 输出方案的话记录一下哪些边 然后记得最后拆环要倒着拆就行了
- ConcurrentLinkedQueue和LinkedBlockingQueue区别
原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/11394436.html 线程安全队列类图 两者的区别在于 ConcurrentLinkedQueue基 ...
- https 配置
参考:https://www.cnblogs.com/tanghuachun/p/9951849.html 1.将pfx文件拷贝到application.properties同级目录下 2.添加配置文 ...