python 端口扫描程序代码实例

发布时间:2020-01-27编辑:脚本学堂
python 端口扫描的二个实例代码,python多线程模块threading用法,Python 端口扫描程序,扫描目标主机的端口开放情况。

例1,python多线程模块threading实现端口扫描

代码:
 

#!/usr/bin/env python
#coding:utf-8

import socket
import threading
import time
class SkPort(threading.Thread):
    def __init__(self,ip,port):
        threading.Thread.__init__(self)
        self.ip = ip
        self.port = port
    def run(self):
        sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sk.settimeout(1000)
        #print('Port scaning:%d' % self.port)
        try:
            sk.connect((self.ip,self.port))
            print('Server %s port %d OK!' % (self.ip,self.port))
        except Exception:
            print('Server %s port %d is not connected!' % (self.ip,self.port))
        sk.close()
def main():
    ip = raw_input('Please input ip(default:127.0.0.1): ')
    sport = int(raw_input('Please input start port(default:80): '))
    eport = int(raw_input('Please input start port(default:80): '))
    for port in range(sport,eport+1):
        item = (ip,port)
        t = SkPort(ip,port)
        t.start()
        time.sleep(0.1)
    
if __name__ == '__main__':
    main()

例2,Python 端口扫描程序
 

#!/usr/bin/env python
# Name:        PortScan
# Purpose:     扫描目标主机的端口开放情况
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()