首页 > 解决方案 > 使用 IP 打开多线程会话的问题

问题描述

我想编写脚本来扫描子网,获取 IP 列表并打开多线程会话以同时扫描所有这些 IP 以查找开放端口:

import socket
import subprocess
import sys
import threading

from netaddr import IPNetwork
from datetime import datetime


List_IP = ['33.45.48.0','33.45.48.1' ]


def subnet_port_scan(subnet):
 
   remoteServerIP = socket.gethostbyname(subnet)

   sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   result = sock.connect_ex((subnet, 22))

   if result == 0:
       print ("Port 22 is Open", subnet)
       sock.close()
   else: 
       print ("Port 22 is Closed", subnet)
       sock.close()


for function in List_IP:
   my_thread = threading.Thread(target=subnet_port_scan,args=List_IP)

   my_thread.start()

   print("Session")


my_thread.join()

现在,如果我在 List_IP 中使用超过 1 个参数,它会显示错误:

TypeError: subnet_port_scan() takes 1 positional argument but 2 were given

我需要能够使用 10-100 个 IP 并同时打开所有会话,但我不明白该怎么做。请看看,让我知道我错过了什么。

谢谢

标签: python-3.xmultithreading

解决方案


是的,您将列表中的每个 var 作为参数传递,也就是 2 个参数。您可以将每个线程添加到列表中,将它们全部启动,然后将它们全部加入,这通常是我使用多处理的方式。试试这样的东西,让你了解它是如何工作的——

import threading

print('start')
List_IP = ['33.45.48.0','33.45.48.1' ]
threads = []

def subnet_port_scan(subnet):
  print("thread called: ", subnet)

for x in List_IP:
  my_thread = threading.Thread(target=subnet_port_scan, args=(x,))
  threads.append(my_thread)

for y in threads:
  print('starting', y)
  y.start()

for z in threads:
  print('joining ', z)
  z.join()

print("Session")

推荐阅读