由于所在项目需要对我们管理的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等系统分类写入到文件中。