1. 程式人生 > >Python指令碼寫埠掃描器

Python指令碼寫埠掃描器

一個用python寫的簡單的埠掃描器,python環境為 3.7.0,windows系統

TCP連線掃描是利用TCP的三次握手來確定主機的埠是否開放。確定主機埠開放之後,給埠傳送訊息,接收埠返回的訊息,看該埠執行的服務。

使用時,-H 引數可以提供主機的域名或者ip地址,-p/-P 寫要掃描的埠,多個埠用逗號分隔

# -*- coding: utf-8 -*-
"""
Created on Sat Nov  3 16:44:28 2018
@author: 小謝
"""
import optparse
from socket import *
import threading
threadLock=threading.Lock()    #例項化threadLock物件
def connScan(Host,Port):
    try:
        conn=socket(AF_INET,SOCK_STREAM)
        conn.connect((Host,Port))
        conn.send('test message'.encode("utf-8")) #傳送測試資訊給埠
        results=conn.recv(100)                    #接收主機返回的資訊
        threadLock.acquire()                      #加鎖
        print('[+]%d/tcp open'% Port)
        print('[+] '+results.decode("utf-8"))
        conn.close()
    except Exception as e:
        threadLock.acquire()
        print(e)
        print('[-]%d/tcp closed'% Port)
    finally:
        threadLock.release()           #釋放鎖
        conn.close()
def portScan(Host,Ports):
    try:
        IP=gethostbyname(Host)          ##獲得對應主機的ip地址
    except:
        print("[-] Cannot resolve '%s':Unknown host" %Host)
        return
    try:
        Name=gethostbyaddr(Host)     ##獲得ip對應主機的資訊
        print ("\n[+] Scan Results for:"+Name[0])
    except:
        print ("\n[+] Scan Results for:"+IP)
    setdefaulttimeout(1)
    for Port in Ports:
        print ("Scanning port "+Port)
        connScan(Host,int(Port))
def main():
    usage="usage %prog -H <target host> -p/-P <target ports>"
    parser=optparse.OptionParser(usage)  #建立物件例項
    parser.add_option('-H',dest='Host',type='string',help='target host')   ##需要的命令列引數
    parser.add_option('-P','-p',dest='Ports',type='string',help='target ports')
    (options,args)=parser.parse_args()
    Host=options.Host
    Ports=str(options.Ports).split(',')
    if (Host==None)|(Ports==None):         ##如果主機和埠都是空的話
        print(parser.usage)
        exit(0)
    portScan(Host,Ports)
if __name__=='__main__':
    main()