Python for 循环变慢并最终挂起

标签 python for-loop freeze

我是 Python 的新手(半小时前),我正在尝试编写一个简单的脚本来枚举 SMTP 服务器上的用户。

用户文件是一个简单的用户名列表(每行一个)。

脚本运行良好,但随着循环的每次迭代,它的速度变慢,直到循环 14 左右,它似乎完全挂起。没有错误 - 我必须 ^c。

任何人都可以阐明这个问题吗?

TIA, 汤姆

#!/usr/bin/python

import socket
import sys

if len(sys.argv) != 2:
        print "Usage: vrfy.py <username file>"
        sys.exit(0)

#open user file
file=open(sys.argv[1], 'r')
users=[x.strip() for x in file.readlines()]
file.close

#Just for debugging
print users

# Create a Socket
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to the Server
connect=s.connect(('192.168.13.222',25))

for x in users:
        # VRFY a user
        s.send('VRFY ' + x + '\r\n')
        result=s.recv(1024)
        print result

# Close the socket
s.close()

最佳答案

很可能您的 SMTP 服务器正在延迟您的客户端连接。这是对失控的客户端或提交大量“垃圾”命令的客户端的防御。来自 Postfix smtpd 的联机帮助页:

   smtpd_junk_command_limit (normal: 100, stress: 1)
          The number of junk commands (NOOP, VRFY, ETRN or  RSET)  that  a
          remote  SMTP  client  can  send  before  the Postfix SMTP server
          starts to increment the error counter with each junk command.

smtpd 守护程序会在看到一定数量的垃圾后在回复之前插入 1 秒的延迟。如果您对有问题的 smtp 服务器具有 root 访问权限,请尝试 strace 以查看服务器是否正在发出 nanosleep 系统调用。

这是对我的本地服务器运行脚本的跟踪。在 100 个 VRFY 命令后,它开始在命令之间休眠。您的服务器可能有约 15 个垃圾命令的下限:

nanosleep({1, 0}, 0x7fffda9a67a0)       = 0
poll([{fd=9, events=POLLOUT}], 1, 300000) = 1 ([{fd=9, revents=POLLOUT}])
write(9, "252 2.0.0 pat\r\n", 15)       = 15
poll([{fd=9, events=POLLIN}], 1, 300000) = 1 ([{fd=9, revents=POLLIN}])
read(9, "VRFY pat\r\n", 4096)           = 10

关于Python for 循环变慢并最终挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5737336/

相关文章:

python - for循环的字典输出

java - 在二维数组中查找相邻元素并计算它们。

python 由于多次重复调用 pandas 而卡住

c# - PsExec 在从编译为 "windows application"的非常简单的 c# 或 c++ gui 程序执行时挂起

python - sklearn : What is the Benefit of Recursive Feature Elimination With Cross-Validation?

python - 如何根据每个组的大小设置滚动窗口大小?

python - 解析函数

python - Numpy - 在 Python 中创建一个输入为两个矩阵、输出为二进制矩阵的函数

java - 在 Java 上启动 ServerSocket 并使用用户界面 (Swing) 卡住

python - 在 python 中模拟类似文件的行为