#!/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. Cheatsheet: 2019 03.01 ~ 04.30

    Golang How To Install Go and Set Up a Local Programming Environment on macOS Build A Go API 40+ prac ...

  2. geometry_msgs的ros message 类型赋值

    test_custom_particles.cpp // // Created by gary on 2019/8/27. // #include <ros/ros.h> #include ...

  3. 阿里腾讯校招Java面试题总结及答案

    阿里校招java面试题汇总 1.HashMap和HashTable的区别,及其实现原理. Hashtable继承自Dictionary类,而HashMap是Java1.2引进的,继承自Abstract ...

  4. jmeter 参数化3_User Defined Variables(用户自定义变量)

    User Defined Variables:  一般用于Test Plan中不需要随请求迭代的参数设置,如:Host.Port Number 操作路径:Thread Group-->Add-- ...

  5. Python3.5-20190502-廖老师-自我笔记

    python的语法主要就是严格的缩进.一般缩进都是四个空格.以冒号结尾的(:)就意味着他后面有代码块.(js代码块使用{}抱起来的,我记得c语言也是,但是python就不需要,他只要严格缩进的就可以了 ...

  6. 26.LockSupport线程阻塞工具

    import java.util.concurrent.locks.LockSupport; /** * 线程阻塞工具类:LockSupport * 可以在线程内任意位置让线程阻塞 */ public ...

  7. Vue.js----更换头像不实时更新问题

    原因 导致问题的原因是缓存造成的,因为你图片变了但是读取头像的地址还会没有变化的 解决思路 所以解决的思路就是上传之后让图片地址改变,那么我们就可以在上传的时候给地址加上一个时间戳那么久可一达到目的了 ...

  8. Android USB驱动源码分析(-)

    Android USB驱动中,上层应用协议里最重要的一个文件是android/kernel/drivers/usb/gadget/android.c.这个文件实现USB的上层应用协议. 首先包含了一些 ...

  9. 双十一高并发场景背后的数据库RDS技术揭秘

    [战报]11月11日聚石塔(阿里云数据库RDS产品形态)峰值QPS突破X00w,Proxy 峰值QPS超过X00w. 双十一就要来了,全世界都为其疯狂,但是在双十一抢购中经常会出现几万人抢一个红包或者 ...

  10. luogu P3768 简单的数学题 杜教筛 + 欧拉反演 + 逆元

    求 $\sum_{i=1}^{n}\sum_{j=1}^{n}ijgcd(i,j)$   考虑欧拉反演: $\sum_{d|n}\varphi(d)=n$   $\Rightarrow \sum_{i ...