gpt4 book ai didi

python - 制作快速端口扫描器

转载 作者:太空狗 更新时间:2023-10-29 21:16:01 28 4
gpt4 key购买 nike

所以我正在用 python 制作一个端口扫描器...

import socket
ip = "External IP"
s = socket.socket(2, 1) #socket.AF_INET, socket.SOCK_STREAM

def porttry(ip, port):
try:
s.connect((ip, port))
return True
except:
return None

for port in range(0, 10000):
value = porttry(ip, port)
if value == None:
print("Port not opened on %d" % port)
else:
print("Port opened on %d" % port)
break
raw_input()

但这太慢了,我想在一段时间不返回任何内容后能够以某种方式关闭或破坏代码。

最佳答案

除了设置套接字超时,您还可以应用多线程技术来加速进程。当你有 N 个端口要扫描时,它最多会快 N 倍。

# This script runs on Python 3
import socket, threading


def TCP_connect(ip, port_number, delay, output):
TCPsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
TCPsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
TCPsock.settimeout(delay)
try:
TCPsock.connect((ip, port_number))
output[port_number] = 'Listening'
except:
output[port_number] = ''



def scan_ports(host_ip, delay):

threads = [] # To run TCP_connect concurrently
output = {} # For printing purposes

# Spawning threads to scan ports
for i in range(10000):
t = threading.Thread(target=TCP_connect, args=(host_ip, i, delay, output))
threads.append(t)

# Starting threads
for i in range(10000):
threads[i].start()

# Locking the main thread until all threads complete
for i in range(10000):
threads[i].join()

# Printing listening ports from small to large
for i in range(10000):
if output[i] == 'Listening':
print(str(i) + ': ' + output[i])



def main():
host_ip = input("Enter host IP: ")
delay = int(input("How many seconds the socket is going to wait until timeout: "))
scan_ports(host_ip, delay)

if __name__ == "__main__":
main()

关于python - 制作快速端口扫描器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26174743/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com