Python is deployed to detect servers/modules based on specified ports.

Source: Internet
Author: User

Python is deployed to detect servers/modules based on specified ports.

This example describes how to deploy a server/Module Based on a specified port in Python, which is of great practical value. Share it with you for your reference.

In some cases, the number of servers is very large during maintenance. Application modules are deployed on different servers. Sometimes the maintenance personnel migrate the module, but the module is not synchronized to the manual in time. Searching is difficult. Therefore, Python is generated to test based on the application port and obtain the module deployment.

The assumption is very simple: through a simple tcp link, if it can be successfully established, it will be immediately disconnected to prevent business impact. Indicates that the module has been deployed on a server.

The specific function code is as follows:

#!/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.173","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)

I hope the method described in this article will be helpful for Python programming.


How to send a specified file to the specified port (using socket) of the host in python

# Sender #-*-coding: UTF-8-*-import Tkinterimport tkFileDialogfrom socket import * import structimport osdef client (filename): Addr = ('123. 0.0.1 ', 8000) BUFSIZE = 2048 Sendsocket = socket (AF_INET, SOCK_STREAM) Sendsocket. connect (Addr) FileHead = struct. pack ('128s11i', filename, 0, 0, 0, 0, 0, 0, 0, OS. stat (filename ). st_size, 0, 0) Sendsocket. send (FileHead) fp = open (filename, 'rb') while 1: FileData = fp. read (BUFSIZE) if not FileData: break Sendsocket. send (FileData) fp. close () Sendsocket. close () def FileOpen (): r = tkFileDialog. askopenfilename (title = 'python Tkinter ', filetypes = [('all files', '*')]) filename = r. split ('/') client (filename [-1]) root = Tkinter. tk () button1 = Tkinter. button (root, text = 'file open', height = 8, width = 14, bg = 'blue', command = FileOpen) button1.pack () root. mainloop () # acceptor #-*-coding: UTF-8-*-from socket import * import osimport structAddr = ('2017. 0.0.1 ', 8000) BUFSIZE = 1024 FileInfoSize = struct. calcsize ('128s32si8s') SocketRecv = socket (AF_INET, SOCK_STREAM) SocketRecv. bind (Addr) SocketRecv. listen (5) print "waitting ........ "conn, addr = SocketRecv. accept () print "send from", addrFileHead = conn. recv (FileInfoSize) filename, temp1, filesize, temp2 = struct. unpack ('128s32si8s', FileHead) print filename, len (filename), type (filename) print filesizefilename = 'new _ '+ ...... remaining full text>

How can I use python (25 or other versions) to implement a graphical interface and send data packets to the specified port of the specified IP address? Answer note version

You can use pygtk to implement a graphical interface. You can find some tutorials on the Internet.

Send data packets to a specified port and use the socket built-in library. Below is a simple demo for your reference:
Server:
Import sockets = socket. socket (socket. AF_INET, socket. SOCK_DGRAM) s. bind ("", 8081) while True: # Receive up to 1,024 bytes in a datatedata, addr = s. recvfrom (1024) print "Received:", data, "from", addrclient:
Import sockets = socket. socket (socket. AF_INET, socket. SOCK_DGRAM) port = 8081 host = "localhost" while True: msg = raw_input () s. sendto (msg, (host, port ))
Thank you for your support!


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.