# python telnetlib 模块
## 实现功能端口扫描
- 功能1 将开放的端口和失败的端口写入到各自的文件中
- 功能2 先删除创建的文件
1 ``` 2 #!/usr/bin/env python 3 #-*- coding: utf-8 -*- 4 5 import telnetlib 6 import threading 7 8 def get_ip_status(key,value): 9 server = telnetlib.Telnet() 10 11 try: 12 server.open(key,value,timeout=0.1) 13 print('{0} port {1} is open'.format(key,value)) 14 with open('/root/chech_ip_open.txt','a+') as f_open: 15 f_open.write('{0} {1}'.format(key,' ')) 16 except Exception as err: 17 print('{0}'.format(key,value)) 18 with open('/root/chech_ip_fial.txt','a+') as f_fial: 19 f_fial.write('{0} {1}'.format(key,' ')) 20 finally: 21 server.close() 22 23 24 def check_open(): 25 #ip = q.get_nowait() 26 # 这里模拟多IP地址的情况,也可以从文件中读取IP??list,改成json格式 27 hosts = [] 28 with open('/root/iplist', "rb") as f: 29 for file_name in f: 30 if file_name.startswith(b'#'): 31 pass 32 elif file_name == b'': 33 pass 34 else: 35 ips = file_name.strip().decode() 36 ipt = ips.split('|')[0] 37 port = ips.split('|')[1] 38 # hosts.append(file_name.strip('|').decode()) 39 D = {ipt: port} 40 hosts.append(D) 41 print(hosts) 42 for ip in hosts: 43 # print("2222",ip) 44 for key,value in ip.items(): 45 keys=key.encode('utf8') 46 values=value.encode('utf8') 47 #print("sdsd",key,value) 48 get_ip_status(keys,values) 49 50 51 52 if __name__ == '__main__': 53 54 import os 55 if os.path.exists("/root/chech_ip_open.txt"): 56 os.remove('/root/chech_ip_open.txt') 57 if os.path.exists('/root/chech_ip_fial.txt'): 58 os.remove('/root/chech_ip_fial.txt') 59 threads = [] 60 for i in range(1): 61 t = threading.Thread(target=check_open) 62 t.start() 63 threads.append(t) 64 65 for t in threads: 66 t.join() 67 68 ```