1. 程式人生 > >python實現埠掃描

python實現埠掃描

一 程式碼

import socket
import multiprocessing
def ports(ports_service):
    #獲取常用埠對應的服務名稱
    for port in list(range(1,100))+[143,145,113,443,445,3389, 8080]:
        try:
            ports_service[port] = socket.getservbyport(port)
        except socket.error:
            pass
def ports_scan(HOST, ports_service):
  
    ports_open = []
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        #sock.settimeout(60)
    except socket.error:
        print('socket creation error')
        sys.exit()
    for port in ports_service:
        try:
            #嘗試連線指定埠
            sock.connect((HOST,port))
            #記錄開啟的埠
            ports_open.append(port)
            sock.close()
        except socket.error:
            pass
    return ports_open
if __name__=='__main__':
    m = multiprocessing.Manager()
    ports_service = dict()
    results = dict()
    ports(ports_service)
    #建立程序池,允許最多8個程序同時執行
    pool = multiprocessing.Pool(processes=8)
    net = '192.168.0.'
    for host_number in map(str,range(105,106)):
        host = net+host_number
        #建立一個新程序,同時記錄其執行結果
        results[host] = pool.apply_async(ports_scan, (host, ports_service))
        print('starting '+host+'...')
    #關閉程序池,close()必須在join()之前呼叫
    pool.close()
    #等待程序池中的程序全部執行結束
    pool.join()
    #列印輸出結果
    for host in results:
        print('='*30)
        print(host,'.'*10)
        for port in results[host].get():
            print(port, ':', ports_service[port])
二 執行結果 starting 192.168.0.105... ============================== 192.168.0.105 .......... 80 : http