python-编写端口扫描器--单线程版

用到的python模块

time,socket模块

time模块可以看我写的这篇关于time模块的使用方法的文章:https://blog.csdn.net/Kris__zhang/article/details/114884992?spm=1001.2014.3001.5501

这篇python编写udp端口脚本:https://blog.csdn.net/Kris__zhang/article/details/114830931?spm=1001.2014.3001.5501
socket模块教程:https://blog.csdn.net/Kris__zhang/article/details/114904786

代码如下:

import time
import socket


def scan(ip, port):
    time_start = time.time()  # 开始计时
    try:
        port = int(port)  # 整数型port
        #print("正在扫描端口: %d" %port)
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 实例化socket对象  socket.SOCK_STREAM  ,,将使用 Transmission Control Protocol(TCP) 协议
        sock.settimeout(4)  # 设置超时时间 ,四秒超时
        s = sock.connect_ex((ip, port))
        # 初始化tcp服务器连接,无法连接时返回错误码,而不是抛出异常,连接成功时返回0
        # print(s)
        if s == 0:
            print(f"{ip}:{port} 开放")  # 输出ip和端口
            print('-'*40)
        else:
            print(f"{port}关闭")
            print('-'*40)


    except:
        print("close")  #程序异常,退出
    time_end = time.time()  # 结束时间
    time_x = time_end - time_start #扫描端口花费的时间
    print(f"扫描端口{port}花费{time_x}秒")
    print('~'*40)

def main():
    print('*'*20,'lemonlove7','*'*20)
    ip = input('请输入IP,不输入则退出程序:')
    port =input('请输入端口,不输入则扫描常规开放端口:')
    if ip =='':
        exit()
    else:
        if port == "":
            print('开始扫描常规端口')
            list_port = [20, 21, 22, 23, 25, 53, 80, 81, 102, 109, 110, 119, 135, 137, 138, 139, 161, 443, 445,554, 1024, 1080,
                         1755, 4000, 5554, 5632, 8080]  # 常规端口
            for i in list_port:
                print(f"正在扫描{i}端口",end='\n') #不断刷新当行
                print('+'*40)
                scan(ip, i)
        else:
                scan(ip,(port))


if __name__ == "__main__":
    main()

你可能感兴趣的:(python,渗透测试工具编写,python,socket,网络,网络互联)