此脚本可用于zabbix ,用来确认存活主机的数量
修改脚本,加入host文件即可,比正常的ping -c 快
import sys
import socket
import math
import threading
listPort=[22, 90, 99, 21]
class Mythread(threading.Thread ):
def __init__(self, func, args):
threading.Thread.__init__(self)
self.func = func
self.args = args
self.result = []
def run(self):
for i in self.args:
print(i)
self.result.append(self.func(i))
def getResult(self):
return self.result
def testOpenPort(host):
testResult = {"{0}".format(host): {"open": [], "close": []}}
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2)
for i in listPort:
result = sock.connect_ex((host, i))
if result == 0:
testResult[host]['open'].append(i)
else:
testResult[host]['close'].append(i)
sock.close()
return testResult
if __name__ == '__main__':
pint_type = 'Open'
hostList = ['192.168.1.1', '192.168.1.2']
AllResult = []
#线程数
threads = 1
step = math.ceil(len(hostList)/threads)
newList = [hostList[i: i+step] for i in range(0, len(hostList), step)]
threadP = []
for x in newList:
t = Mythread(testOpenPort, hostList)
threadP.append(t)
for x in threadP:
x.start()
for x in threadP:
x.join()
for x in threadP:
result = x.getResult()
AllResult.extend(result)
OpenSList = [(list(x.keys()))[0] for x in AllResult if 22 in x[(list(x.keys()))[0]]['open']]
OpenResult = len(OpenSList) if pint_type == "Open" else len(hostList)-len(OpenSList)
print(OpenResult)