欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python實(shí)現(xiàn)多線程端口掃描

 更新時(shí)間:2019年08月31日 14:04:52   作者:sime_km  
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)多線程端口掃描,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

一個(gè)簡(jiǎn)易的TCP端口掃描器,使用python3實(shí)現(xiàn)。

需求:掃描目標(biāo)網(wǎng)站開(kāi)放哪些端口號(hào),將所有開(kāi)放的端口號(hào)輸出。

分析:使用socket連接,如果連接成功,認(rèn)為端口開(kāi)放,如果連接失敗,認(rèn)為端口關(guān)閉(有可能端口開(kāi)放但連接失敗,這里簡(jiǎn)單認(rèn)為端口不開(kāi)放)

使用到的庫(kù):socket, threading

過(guò)程:

先定義一個(gè)函數(shù),對(duì)給定的(ip, port)進(jìn)行掃描,看其是否能連接成功。

def tcpPortScan(ip, port, openPort):
 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 創(chuàng)建套接字
 sock.settimeout(0.1)   # 設(shè)置延時(shí)時(shí)間
 try:
  result = sock.connect_ex((ip, port))
  if result == 0:    # 如果連接成功,返回值為0
   openPort.append(port) # 如果端口開(kāi)放,就把端口port賦給openPort
 except:
  pass
 sock.close()     # 關(guān)閉套接字

當(dāng)需要掃描目標(biāo)地址的多個(gè)端口時(shí),循環(huán)使用上述函數(shù)的話,掃描速度會(huì)極其慢,因?yàn)榭紤]使用多線程。

再定義一個(gè)函數(shù),實(shí)現(xiàn)多線程掃描。

def threadingPortScan(host, portList, openPorts = []):
 
 hostIP = socket.gethostbyname(host) # 獲取域名對(duì)應(yīng)的IP地址
 nloops = range(len(portList))
 threads = []
 
 for i in nloops:
  t = threading.Thread(target=tcpPortScan, args=(hostIP, portList[i], openPorts))
  threads.append(t)
 
 for i in nloops:
  threads[i].start()
 
 for i in nloops:
  threads[i].join()
 return openPorts  # 返回值為該域名下開(kāi)放的端口列表

完整代碼如下:

# -*- coding:utf-8 -*-
'''
使用多線程,檢測(cè)一個(gè)目標(biāo)地址的端口開(kāi)放情況,目標(biāo)地址由用戶輸入,端口暫時(shí)定義為0~1024,
檢測(cè)TCP連接是否成功,如果連接成功,則端口開(kāi)放,不成功則端口關(guān)閉
'''
 
import socket
import threading
 
def main():
 host = input('please input domain:')
 portList = range(0, 1025)
 openPorts = threadingPortScan(host, portList)
 print(host,'open ports:', openPorts)
 
# 對(duì)給定的(ip, port)進(jìn)行TCP連接掃描
def tcpPortScan(ip, port, openPort):
 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 創(chuàng)建套接字
 sock.settimeout(0.1)   # 設(shè)置延時(shí)時(shí)間
 try:
  result = sock.connect_ex((ip, port))
  if result == 0:
   openPort.append(port) # 如果端口開(kāi)放,就把端口port賦給openPort
 except:
  pass
 sock.close()     # 關(guān)閉套接字
 
 
def threadingPortScan(host, portList, openPorts = []):
 
 hostIP = socket.gethostbyname(host) # 獲取域名對(duì)應(yīng)的IP地址
 nloops = range(len(portList))
 threads = []
 
 for i in nloops:
  t = threading.Thread(target=tcpPortScan, args=(hostIP, portList[i], openPorts))
  threads.append(t)
 
 for i in nloops:
  threads[i].start()
 
 for i in nloops:
  threads[i].join()
 return openPorts  # 返回值為該域名下開(kāi)放的端口列表
 
if __name__ == '__main__':
 main()

使用www.qq.com做一個(gè)測(cè)試,測(cè)試結(jié)果如下:

>>>please input domain: www.qq.com
www.qq.com open ports: [80, 843]

總結(jié):這個(gè)小程序僅適用于新手練習(xí),不適合真正應(yīng)用。該簡(jiǎn)易端口掃描器僅能掃描出一部分端口,有些端口可能因?yàn)榉阑饓r截導(dǎo)致掃描失敗。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論