Python loop to monitor remote ports
- 2020-04-02 14:38:40
- OfStack
This article illustrates a python loop monitoring method for remote ports. Share with you for your reference. The details are as follows:
With one IP address and port number per line in ip.txt, the code can iterate to monitor whether the specified port of these IP addresses is normal
#!/usr/bin/env python
# -*- coding: gbk -*-
import socket,time
while 1:
file_obj = open('ip.txt')
for line in file_obj:
try:
sc=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ip = line.split()[0]
port = int(line.split()[1])
print ip,port
# Set timeout time ( 0.0 )
sc.settimeout(2)
sc.connect((ip,port))
timenow=time.localtime()
datenow = time.strftime('%Y-%m-%d %H:%M:%S', timenow)
logstr="%s:%s The connection is successful ->%s n" %(ip,port,datenow)
print logstr
sc.close()
except:
file = open("log.txt", "a")
timenow=time.localtime()
datenow = time.strftime('%Y-%m-%d %H:%M:%S', timenow)
logstr="%s:%s The connection fails ->%s n" %(ip,port,datenow)
print logstr
file.write(logstr)
file.close()
print "sleep 10....."
time.sleep(10)
File in ip.txt format:
192.168.1.100 33001
192.168.1.101 33001
I hope this article has helped you with your Python programming.