【问题标题】:Python: Have to press ctrl+c to get an resultPython:必须按 ctrl+c 才能得到结果
【发布时间】:2012-10-25 13:01:24
【问题描述】:

我正在尝试创建一个 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'

我做错了什么?

提前致谢!

【问题讨论】:

  • 你得到了什么结果? -- 我猜s.connect 会阻止执行,直到你连接到某个东西,但你连接失败,所以它就在那里等着。当您点击 ctrl-c 时,您会抛出 KeyboardInterrupt 异常,该异常在您的 (bare!) 异常处理程序中处理。
  • 其他一些事情。不要使用list 作为变量名,它是内置的,会使您的代码混乱(并且可能有错误)。此外,在内部和外部循环中使用相同的变量名来表示不同的数据也不是最好的主意(在这种情况下为items)。最后,您将portsitems 复数这一事实具有误导性,就好像这些变量实际上表示多个值一样,您的ports = int(items) 会引发异常。
  • 感谢您的提示,我将编辑我的变量名!

标签: python sockets ports


【解决方案1】:

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

所以通常建议在调用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'

【讨论】:

  • 感谢您的快速回复! s.settimeout(1.0) # Set a timeout (value in seconds) 是解决方案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多