python telnetlib 模块实现功能端口扫描

python telnetlib 模块

实现功能端口扫描

  • 功能1 将开放的端口和失败的端口写入到各自的文件中
  • 功能2 先删除创建的文件
#!/usr/bin/env python
#-*- coding: utf-8 -*- 

import telnetlib
import threading

def get_ip_status(key,value):
    server = telnetlib.Telnet()

    try:
        server.open(key,value,timeout=0.1)
        print('{0} port {1} is open'.format(key,value))
        with open('/root/chech_ip_open.txt','a+') as f_open:
            f_open.write('{0} {1}'.format(key,'\n'))
    except Exception as err:
        print('{0}'.format(key,value))
        with open('/root/chech_ip_fial.txt','a+') as f_fial:
            f_fial.write('{0} {1}'.format(key,'\n'))
    finally:
        server.close()


def check_open():
   #ip = q.get_nowait()
   # 这里模拟多IP地址的情况,也可以从文件中读取IP??list,改成json格式
   hosts = []
   with open('/root/iplist', "rb") as f:
       for file_name in f:
           if file_name.startswith(b'#'):
               pass
           elif file_name == b'':
               pass
           else:
               ips = file_name.strip().decode()
               ipt = ips.split('|')[0]
               port = ips.split('|')[1]
               # hosts.append(file_name.strip('|').decode())
               D = {ipt: port}
               hosts.append(D)
   print(hosts)
   for ip in hosts:
      # print("2222",ip)
       for key,value in ip.items():
            keys=key.encode('utf8')
            values=value.encode('utf8')
           #print("sdsd",key,value)
            get_ip_status(keys,values)



if __name__ == '__main__':

    import os 
    if os.path.exists("/root/chech_ip_open.txt"):
        os.remove('/root/chech_ip_open.txt')
    if os.path.exists('/root/chech_ip_fial.txt'):
        os.remove('/root/chech_ip_fial.txt')
    threads = []
    for i in range(1):
        t = threading.Thread(target=check_open)
        t.start()
        threads.append(t)

    for t in threads:
        t.join()

posted @ 2020-09-03 10:22  Mr.zou  阅读(449)  评论(0编辑  收藏  举报