如何检查端口是否可用?

时间:2018-05-06 01:11:56

标签: python multithreading

我正在尝试自己构建端口检查器,我尽我所能,但我想在循环中使用线程。从my-hosts文件中获取IP然后我可以在新线程上运行检查器而不是阻塞主线程。是否有人知道如何实现这一点或更正我的代码?

import socket
import threading
import time
counting_open = []
counting_close = []
port = 25
hosts = "ip.txt"
def scan():
    with open(hosts) as e:
        p = e.read().split("\n")
    for host in p : #iwant to use this for threading into the function
        s = socket.socket()
        result = s.connect_ex((host,port))
        print('working on port > '+(str(port)))      
        if result == 0:
            counting_open.append(port)
            print((str(port))+' -> open on ' + str(host)) 
            s.close()
        else:
            counting_close.append(port)
            print((str(port))+' -> close on ' + str(host))`

2 个答案:

答案 0 :(得分:1)

由于 它已经工作了

import socket
import threading
import time
counting_open = []
counting_close = []
threads = []
port = 25
hosts = "ip.txt"

def scan(host):    
        s = socket.socket()
        result = s.connect_ex((host,port))
        if result == 0:
            counting_open.append(port)
            print((str(port))+' -> open on ' + str(host)) 
            s.close()
        else:
            counting_close.append(port)
            print((str(port))+' -> close on ' + str(host))

with open(hosts) as e:
    p = e.read().split("\n")
for h in p:
   thread = threading.Thread(target = scan, args = (h, )) 
   threads.append(thread)    # Wait until the thread terminates
   thread.start()    # Start the new thread
for x in threads:
    x.join()

答案 1 :(得分:0)

所以我觉得你想要检查不同线程中的每个端口。我对python线程库做了一些研究,你应该能够简单地将你想要在新线程中运行的所有代码放在一个函数中,然后用该函数作为目标启动一个新线程。

在下面的示例中,我创建了一个在新线程中基于arg时间打印“running”的函数。

from threading import Thread
from time import sleep

def threaded_function(arg):
    for i in range(arg):
        print("running")
        sleep(1)

thread = Thread(target = threaded_function, args = (10, ))
thread.start()
thread.join()
print("thread finished...exiting")

在自己的代码中使用它的方法可能是:

import socket
from threading import thread
import time
counting_open = []
counting_close = []
port = 25
hosts = "ip.txt"

def scan(host):    
        s = socket.socket()
        result = s.connect_ex((host,port))
        print('working on port > '+(str(port)))      
        if result == 0:
            counting_open.append(port)
            print((str(port))+' -> open on ' + str(host)) 
            s.close()
        else:
            counting_close.append(port)
            print((str(port))+' -> close on ' + str(host))`

with open(hosts) as e:
    p = e.read().split("\n")
for h in p:
   thread = Thread(target = scan, args = (h, )) 
   thread.start()    # Start the new thread
   thread.join()     # Wait until the thread terminates

希望这会有所帮助。请记住,上述代码尚未经过测试。

相关问题