python 端口扫描的二个例子

发布时间:2020-06-09编辑:脚本学堂
分享二个python实现端口扫描的例子,学习下python中使用socket模块、threading模块进行端口扫描的方法,有需要的朋友参考下。

例1,python端口扫描
 

复制代码 代码示例:

#!/bin/python
#edit: www.jb200.com
#
import os
import socket
import threading
import getopt, sys

def connect_port(ip, port):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((ip, port))
        print 'port %d is open' % (port)
        s.close()
    except socket.error, msg:
        pass

if __name__ == '__main__':
    threads = []
    opt, args = getopt.getopt(sys.argv[1:], '')
   
    if len(args) <= 0:
        quit()
      
    for i in xrange(0, 500):
        threads.append(threading.Thread(target = connect_port, args = ("192.168.1.101", i)))

    for t in threads:
        t.start()

    for t in threads:
        t.join()

例2,Python写的一个简单的端口扫描程序
 

复制代码 代码示例:

#--------------------------------------------
# Name:        PortScan
# Purpose:     扫描目标主机的端口开放情况
#
# Author:      xxh
#
# Created:     05-12-2011
# Copyright:   (c) xxh 2011
# Licence:     <your licence>
#--------------------------------------------
#!/usr/bin/env python

import socket

def main():
    sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sk.settimeout(1000)
    ip=input('请输入目标主机:(默认:127.0.0.1)')
    if ip=='':
        ip='127.0.0.1'

    s=input('请输入目标主机开始端口:(默认:80)')
    if s=='':
        startport=80
    else:
        startport=int(s)

    s=input('请输入目标主机结束端口:(默认:80)')
    if s=='':
        endport=80
    else:
        endport=int(s)

    for port in range(startport,endport+1):
        print('正在扫描端口:%d' % port)
        try:
            sk.connect((ip,port))
            print('Server %s port %d OK!' % (ip,port))
        except Exception:
            print('Server %s port %d is not connected!' % (ip,port))
    sk.close()

if __name__ == '__main__':
    main()