嗨,我正在从 python 和 powershell 运行以下 telnet 脚本。在 python 中,我使用 telnetlib 并运行以下命令:
import telnetlib
HOST = "hostname"
PORT = 25
TIMEOUT = 5
def test_telnet(Host, Port, Timeout):
tn = telnetlib.Telnet(host=Host, port=Port, timeout=Timeout)
print 'Client Connecton Made.'
tn.write("HELO <domainName>\r\n")
tn.write("Mail From: senderemail@domain.com\r\n")
tn.write("RCPT TO: rcpt@gmail.com\r\n")
tn.write("DATA\r\n")
tn.write("Subject: Some Subject.\r\n")
tn.write("First Line of Body\r\n")
tn.write("\r\n")
tn.write("Thanks\r\n")
tn.write("\r\n")
tn.write("Name\r\n")
tn.write(".\r\n")
tn.write("exit\r\n")
print tn.read_all()
print 'Client Connection Lost.'
test_telnet(HOST, PORT, TIMEOUT)
此脚本适用于 Windows 7,但不适用于 Windows Server 2012 R2。两者甚至都给了我相同的超时错误;但是,当从 Windows 7 机器执行时,它仍然是成功的。错误如下:
C:\Anaconda\python.exe C:/telnetTest.py
Client Connecton Made.
Traceback (most recent call last):
File "C:/telnetTest.py", line 34, in <module>
test_telnet(HOST, PORT, TIMEOUT)
File "C:/telnetTest.py", line 31, in test_telnet
print tn.read_all()
File "C:\Anaconda\lib\telnetlib.py", line 384, in read_all
self.fill_rawq()
File "C:\Anaconda\lib\telnetlib.py", line 575, in fill_rawq
buf = self.sock.recv(50)
socket.timeout: timed out
Process finished with exit code 1
我什至运行了这个脚本的逐行版本,它在两台机器上都可以运行。powershell中使用的逐行命令如下:
Telnet <hostname> 25
Helo domainName
Mail From: senderemail@domain.com
RCPT TO: rcpt@gmail.com
DATA
Subject: Some Subject.
First Line of Body
Thanks
Name
.
quit
两台机器的powershell版本、pycharm版本、python版本(anaconda 2.7.8)都是一样的。
我什至尝试了这篇文章中提到的编码:telnetlib python example 但这不是问题。我很想知道为什么它没有使用 telnetlib 运行,即使它在 powershell 中运行也是如此。
谢谢。