Python实现根据指定端口探测服务器模块部署的方法

Python实现根据指定端口探测服务器模块部署的方法,第1张

概述本文实例讲述了Python实现根据指定端口探测服务器/模块部署的方法,非常具有实用价值。分享给大家供大家参考借鉴。

本文实例讲述了Python实现根据指定端口探测服务器/模块部署的方法,非常具有实用价值。分享给大家供大家参考借鉴。

有些时候,在维护过程中,服务器数量非常多。应用模块部署在不同服务器上。有时维护人员做了模块迁移,而未及时同步至手册中。查找比较困难。于是,产生Python根据应用端口进行探测,获取模块部署。

设想非常简单:通过简单的tcp链接,如果能够成功的建立,立即断开,防止影响业务。表示模块在某服务器上有部署。

具体功能代码如下:

#!/bin/env python#import socketimport timefrom threading import ThreadhostList=["10.10.126.170","10.10.126.173","10.10.126.177","10.10.126.170","10.10.126.177"]online=[]offline=[]gathered=[]hostDict={"online":[],"offline":[]}class detect(Thread): def __init__(self,ip,port=22): Thread.__init__(self) self.ip=ip self.port=port def run(self): address=(self.ip,self.port) sock=socket.socket(socket.AF_INET,socket.soCK_STREAM) try:  sock.connect(address)  buff=sock.recv(1024)  if(len(buff)):  print("detect Host %s Online" % self.ip)  online.append(self.ip) except:  print("detect Host %s Offline" % self.ip)  offline.append(self.ip) sock.closedef sigle_detect(ip): p=detect(ip) p.start() p.join(60)def multi_detect(host): T_thread=[] for ip in set(host): t=detect(ip) t.name=ip t.start() T_thread.append(t) for t in T_thread: t.join(15) def filter_gather(hList): gather=[] for t in set(hList): gather.append(t) return gatherdef mak_hostList_byip3(ipList): global hostList hostList=[] for ip in set(ipList): tmp=ip.split('.') if(len(tmp)==3):  for i in range(2,254):  hostList.append('%s.%d' % (ip,i)) elif(len(tmp)==4):  hostList.append(ip) else:  continue return hostListdef update_hostDict(online,offline): hostDict["online"]=online hostDict["offline"]=offlinedef make_pickle_filename(): import time filename="" for s in time.localtime()[:5]: filename=filename+str(s) filename="Host_%s.pkl" % filename return filenamedef save_gathered(filename,hostDict): import pickle F=open(filename,'wb') pickle.dump(hostDict,F) F.close()def recovery_gathered(filename,keyList): import pickle try: F=open(filename,'rb') E=pickle.load(F) keyList.append(E) except: F.close() return while E: try:  E=pickle.load(F)  keyList.append(E) except:  F.close()  breakif __name__=='__main__': sigle_detect(hostList[0]) #--------------- mak_hostList_byip3(hostList) multi_detect(hostList) online=filter_gather(online) print(online) offline=filter_gather(offline) print(offline) gathered=online+offline print(gathered) update_hostDict(online,offline) print(hostDict) fN=make_pickle_filename() save_gathered(fN,hostDict) keyList=[] recovery_gathered(fN,keyList) print(keyList)

希望本文讲述的方法对大家的Python程序设计有所帮助。

总结

以上是内存溢出为你收集整理的Python实现根据指定端口探测服务器/模块部署的方法全部内容,希望文章能够帮你解决Python实现根据指定端口探测服务器/模块部署的方法所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1202819.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存