gpt4 book ai didi

Python:必须按 ctrl+c 才能得到结果

转载 作者:太空宇宙 更新时间:2023-11-03 19:10:39 25 4
gpt4 key购买 nike

我正在尝试创建一个 python 脚本来检查端口是否可用。下面是一段代码(不是整个脚本)。

但是当我运行脚本时,终端没有显示任何输出,当我按 ctrl + c 时,我得到脚本的单个结果,当我再次按 ctrl+c 时,我得到第二个结果。当脚本完成后,它最终退出......

#!/usr/bin/python

import re
import socket
from itertools import islice

resultslocation = '/tmp/'
f2name = 'positives.txt'
f3name = 'ip_addresses.txt'
f4name = 'common_ports.txt'

#Trim down the positive results to only the IP addresses and scan them with the given ports in the common_ports.txt file

with open(resultslocation + f2name, 'r') as f2, open(resultslocation + f3name, 'w') as f3:
hits = f2.read()
list = re.findall(r'name = (.+).', hits)
for items in list:
ip_addresses = socket.gethostbyname(items)
with open(resultslocation + f4name, 'r') as f4:
for items in f4:
ports = int(items)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((ip_addresses, ports))
s.shutdown(2)
print 'port', ports, 'on', ip_addresses, 'is open'
except:
print 'port', ports, 'on', ip_addresses, 'is closed'

我做错了什么?

提前致谢!

最佳答案

默认情况下,套接字以阻塞模式创建。

因此,一般情况下,建议在调用 connect() 之前调用 settimeout() 或将超时参数传递给 create_connection() 并使用它而不是连接。由于您的代码已经捕获了异常,因此第一个选项很容易实现;

with open(resultslocation + f2name, 'r') as f2, open(resultslocation + f3name, 'w') as f3:
hits = f2.read()
list = re.findall(r'name = (.+).', hits)
for items in list:
ip_addresses = socket.gethostbyname(items)
with open(resultslocation + f4name, 'r') as f4:
for items in f4:
ports = int(items)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1.0) # Set a timeout (value in seconds).
try:
s.connect((ip_addresses, ports))
s.shutdown(2)
print 'port', ports, 'on', ip_addresses, 'is open'
except:
# This will alse catch the timeout exception.
print 'port', ports, 'on', ip_addresses, 'is closed'

关于Python:必须按 ctrl+c 才能得到结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13069201/

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