0

我需要通过 telnet 连接到远程服务器。要对服务器进行身份验证,我必须回答 100 个问题。因此,我尝试使用 telnetlib 在 python 中自动执行此任务,但提示停止但没有返回任何消息。

这就是我所做的

import telnetlib 

port = 2002
host = "23.23.190.204"

tn = telnetlib.Telnet(host, port)
tn.read_until("""
Welcome to EULER!
                 =================
                                  Answer 100 simple questions to authenticate yourself
""")
print tn.read_all()
tn.close()

在命令行提示符中,我收到此消息

Welcome to EULER!
=================
Answer 100 simple questions to authenticate yourself

然后我会被问到一个问题,如果答案是正确的,我会得到下一个问题,直到我完成 100。但是在 python 程序中,我既没有收到消息也没有收到问题!该怎么办?

编辑:

设置 telnet 的调试级别后,我得到了服务器的答案。你能解释一下这是为什么吗?

tn.set_debuglevel(9)
4

1 回答 1

2

ncat这是一个使用 netcat(来自Nmap )的假 telnet 服务器:

$ ncat -l 9000 < msg.txt > log.txt

在端口 9000 上列出并传递一个名为msg.txt(问题)的文件并将输入记录到log.txt(答案)中,它应该模拟您的服务器。

文件msg.txt内容:

Welcome to EULER!
=================
Answer 100 simple questions to authenticate yourself
What is your name?
How old are you?
Do you use Python?

十六进制的文件内容(使用hexdump msg.txt):

00000000: 0A 57 65 6C 63 6F 6D 65 20 74 6F 20 45 55 4C 45 | Welcome to EULE|
00000010: 52 21 0A 3D 3D 3D 3D 3D 3D 3D 3D 3D 3D 3D 3D 3D |R! =============|
00000020: 3D 3D 3D 3D 0A 41 6E 73 77 65 72 20 31 30 30 20 |==== Answer 100 |
00000030: 73 69 6D 70 6C 65 20 71 75 65 73 74 69 6F 6E 73 |simple questions|
00000040: 20 74 6F 20 61 75 74 68 65 6E 74 69 63 61 74 65 | to authenticate|
00000050: 20 79 6F 75 72 73 65 6C 66 0A 57 68 61 74 20 69 | yourself What i|
00000060: 73 20 79 6F 75 72 20 6E 61 6D 65 3F 0A 48 6F 77 |s your name? How|
00000070: 20 6F 6C 64 20 61 72 65 20 79 6F 75 3F 0A 44 6F | old are you? Do|
00000080: 20 79 6F 75 20 75 73 65 20 50 79 74 68 6F 6E 3F | you use Python?|
00000090: 0A                                              |                |
00000091;                                                 |                |

注意换行符,它是\x0Aor \n(也可以是\x0D\x0Aor \n\r)。

客户端:

import telnetlib 

port = 9000
host = "127.0.0.1"

tn = telnetlib.Telnet(host, port)
r = tn.read_until("""\nWelcome to EULER!
=================
Answer 100 simple questions to authenticate yourself\n""")

tn.read_until("What is your name?\n")
tn.write("foo\n") # The client sends `\n`, notice the server may expects `\n\r`.
print("Question 1 answered.")

tn.read_until("How old are you?\n")
tn.write("100\n")
print("Question 2 answered.")

tn.read_until("Do you use Python?\n")
tn.write("yep\n")
print("Question 3 answered.")

tn.close()

现在让我们在客户端测试它:

$ python client.py
Question 1 answered.
Question 2 answered.
Question 3 answered.
$

在服务器端,转储日志文件内容:

$ ncat -l 9000 < msg.txt > log.txt
$
$ cat log.txt # or `type log.txt` on windows
foo
100
yep

$
$ hexdump log.txt
00000000: 66 6F 6F 0A 31 30 30 0A 79 65 70 0A             |foo 100 yep |
0000000c;
$

把它放在一起,你应该明白了。

于 2014-01-25T09:11:46.203 回答