在python中连接telnet并进行测试作为登录?

2024-05-02 05:21:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要通过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()

在命令行提示符下,我得到了这个消息

^{pr2}$

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

编辑:

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

tn.set_debuglevel(9)

Tags: to答案import服务器身份验证host消息read
1条回答
网友
1楼 · 发布于 2024-05-02 05:21:16

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

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

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

文件msg.txt内容:

^{pr2}$

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

^{3}$

注意新行字符,它是\x0A或{}(它也可以是\x0D\x0A或{})。在

客户:

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;
$

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

相关问题 更多 >