import socket,os,time def getstrtime(): return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) def connecthost(ip,port): sk1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sk1.settimeout(5) try: sk1.connect((ip,port)) msg = getstrtime() + ' ' + ip + ' ' + str(port) + ' '+ "端口开启" msg = '' return msg except Exception as e: msg = getstrtime() + ' ' + ip + ' ' + str(port) + ' ' + "端口已关闭" return msg sk1.close() while True: getstrtime() f = open(file='monitor.txt', mode='r') dada = f.read() f.seek(0) for line in f: line = line.split() ip,port = line ret = connecthost(ip, int(port)) try: flogs = open(file='logs.txt', mode='a') if ret != '': flogs.write(ret + '\n') print(ret) except: flogs.close()