本帖最后由 zyjsuper 于 2020-5-23 07:15 编辑
客户这边的运维提出了一个需求,需要完成内网中所有HP服务器iLo口SBSN和KEY的收集,类似格式如下:
完成的python脚本如下,该脚本只收集可以ping通的服务器的iLo信息,如果没有iLo信息的ip地址标记为Fail。朋友们手里如果有更好的实现脚本,请不吝分享。[Python] 纯文本查看 复制代码 #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from urllib import request
from xml.etree import ElementTree
import xml.etree.cElementTree as ET
import threading
import subprocess
import time
from queue import Queue
import os
# 定义工作线程
WORD_THREAD = 300
# 将需要 ping 的 ip 加入队列
IP_QUEUE = Queue()
for i in range(1,255):
IP_QUEUE.put('10.10.1.'+str(i))
IP_QUEUE.put('10.10.2.'+str(i))
IP_QUEUE.put('10.10.3.'+str(i))
IP_QUEUE.put('10.10.4.' + str(i))
IP_QUEUE.put('10.10.5.' + str(i))
IP_QUEUE.put('10.10.6.' + str(i))
IP_QUEUE.put('10.10.7.' + str(i))
IP_QUEUE.put('10.16.8.' + str(i))
def getinfo(ip):
url="http://"+ip+"/xmldata?item=cpqkey"
web = request.urlopen(url,timeout=1)
f = web.read()
#解码
data = ElementTree.XML(f.decode('utf-8'))
#获取根节点
tree = ET.ElementTree(data)
root = tree.getroot()
#根据索引和标签名获取所需要的值
SBSN = root.find("SBSN").text
KEY = root.find("KEY").text
if(KEY):
info=(ip + ", " + SBSN.strip() + ", " + KEY.strip() + ", " + "OK" + "\n")
with open (filename,"a+") as file:
file.write(info)
def ping_ip():
while not IP_QUEUE.empty():
ip = IP_QUEUE.get()
res = os.system('ping -c 2 -w 3 %s >/dev/null' % ip) # Windows系统将 '-c' 替换成 '-n',根据网络情况调整,如果网络0延迟,可以改为 "-c 1 -w 1"
#res = subprocess.call('ping -n 1 -w 2 %s' % ip,stdout=subprocess.PIPE) windows用这种方式
# 打印运行结果
if(res==0):
try:
getinfo(ip)
except:
info = (ip + ", " + ", " + ", " + "Fail" + "\n")
with open(filename, "a+") as file:
file.write(info)
if __name__ == '__main__':
filename="iLOinfo"+time.strftime("%Y%m%d")+".csv"
if(os.path.isfile(filename)):
os.system("rm -f "+filename) #windows系统将 "rm -f"替换成"del /F"
info = ("ip地址" + ", " + "SBSN" + ", " + "KEY" + ", " + "状态" + "\n")
with open(filename, "w") as file:
file.write(info)
threads = []
start_time = time.time()
for i in range(WORD_THREAD):
thread = threading.Thread(target=ping_ip)
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
print("报告文件" + filename + "已经生成.")
print('程序运行耗时:%s' % (time.time() - start_time))
|