记录一次公司需求,通过python3获取全网主机系统类型

由于所在项目需要对我们管理的5000多台主机进行系统获取,便于更好的管理主机系统,如果用shell去获取效率太慢啦,于是自己动手用python3多进程写了一个获取主机系统的脚本,5000多台机器,30多分钟就搞定了啊,相比较于之前的1-2个小时有很大的提升,所以记录一下。源码如下:

#!/usr/bin/python3
import subprocess as sub
import sys
import pexpect
import datetime
from multiprocessing import Process
start = datetime.datetime.now()

def get_osversion(file_paths):
    f = open(file_paths,'r')
    ip_list = f.readlines()
    ip = [i.rstrip("\n") for i in ip_list]
    for j in ip:
        cmd = "ssh -o ConnectTimeout=15 -o ConnectionAttempts=1 -o PasswordAuthentication=no -o StrictHostKeyChecking=no "+j+" 'cat /etc/redhat-release'"
        cmd1 = "ssh -o ConnectTimeout=15 -o ConnectionAttempts=1 -o PasswordAuthentication=no -o StrictHostKeyChecking=no "+j+" 'uname -a'"
        child = pexpect.spawn(cmd)
        ret = child.expect(["Password:","Red","open","22","Authentication","CentOS","redhat","Permission"])
        print(j)
        print(ret)
        if ret == 0:
            f_need_pass = open("need_password.txt","a")
            f_need_pass.write(j+"\n")
        if ret == 1:
            get_os =sub.getstatusoutput(cmd)
            os = get_os[1][-40:]
            f_redhat = open("redhat.txt","a")
            f_redhat.write(j+" "+os+"\n")
        if ret == 2:
            get_os =sub.getstatusoutput(cmd1)
            os = get_os[1][-4:]
            f_vmware=open("esxi.txt","a")
            f_vmware.write(j+" "+os+"\n")
        if ret == 3:
            f_sshfail = open("ssh_fail.txt","a")
            f_sshfail.write(j+"\n")
        if ret == 4:
            f_authfail = open("auth_fail.txt","a")
            f_authfail.write(j+"\n")
        if ret == 5:
            get_os =sub.getstatusoutput(cmd)
            os = get_os[1][-25:]
            f_centos = open("centos.txt","a")
            f_centos.write(j+" "+os+"\n") 
        if ret == 6:
            get_os=sub.getstatusoutput(cmd)
            os = get_os[1][-30:]
            f_other=open("other.txt","a")
            f_other.write(j+" "+os+"\n")
        if ret == 7:
            f_Permission =open("permission.txt","a")
            f_Permission.write(j+"\n")

Prolist = []
for l in range(10):
    p = Process(target=get_osversion, args=(sys.argv[l],))
    Prolist.append(p)
    p.start()
    print("Process end.")
for m in Prolist:
    m.join()

end = datetime.datetime.now()
print(end-start)

34分钟效率还是很高。

最后结果就是把全网的centos,redhat,esxi等系统分类写入到文件中。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值