# -*- coding:utf-8 -*- import telnetlib import os import datetime import time import codecs file_path="e:/doc/py/telnet/telnet.log" def do_telnet(host,port): while 1<2: fw=codecs.open(file_path,"a","utf-8") #,"utf-8" tm=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) try: tn = telnetlib.Telnet(host, port, timeout=5) cc=tm+" "+host+":"+port+" access success!" print(cc) fw.write(cc+"\n") fw.close() #print("access success!") tn.close() # tn.write('exit\n') time.sleep(3) except: cc=tm+" "+host+":"+port+" error timeout" print(cc) fw.write(cc+"\n") fw.close() #return False; return True; if __name__ == '__main__': host = "183.1.1.1" port = "8000" do_telnet(host,port)