python实现端口扫描

blog 196
import socket
from sys import exec_prefix 
import time
from scapy.all import *
import optparse

def tcpscan(host,port):
    try:
        conn = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        conn.connect((host,port))
        print('[+]{}/tcp  open'.format(port))
        conn.close()
    except:
        pass
def udpscan(host,port):
    try:
        rep = sr1(IP(dst=hsot)/UDP(dport=port),timeout=1,verbose=0)
        time.sleep(1)
        if(rep.haslayer(ICMP)):
            print('[-]{}/udp not open'.format(port))
    except:
        print('[+]{}/udp open'.format(port))


def portscan(host):
    for port in range(1,1025):
        tcpscan(host,port)
        
def main():
    parser = optparse.OptionParser("help" + '-H <target host>')
    parser.add_option('-H',dest='tgthost',type='string')
    help = "specify target host"
    (options,args) = parser.parse_args()
    host = options.tgthost
    if host == None:
        print(parser.usage) 
        exit(0)
    else:
        portscan(host)
if __name__ == '__main__':
    main()

运行结果:

-H 指定目标主机

PS:只能扫描1到1024之间的端口(包含1024)。如果想扫描多个端口请修改脚本中26行的range()函数

python实现端口扫描

分享