Python子进程telnet会自动进行快速交互

问题描述

我想远程登录到具有不同主机的控制台服务器,以检查那些主机名。在控制台服务器后面可以有大约50台主机。 所以我需要两次登录。首先对控制台服务器进行身份验证,然后对它后面的主机进行身份验证。

我想在没有键盘输入的情况下自动执行此操作。 我只需要知道如何使用它,之后我就可以自己创建一个for循环。 我一直坚持将用户名密码自动发送到服务器,然后再发送到主机。因为我的横幅很长,所以您会看到很多print(repr(command.stdout.readline()))

最后,我想将主机名存储在列表中,或者想知道是否在控制台端口后面连接了服务器。 我花了一天的时间尝试各种方法,下面的代码是我的最佳尝试。如果您还有其他建议,那就可以了!

此外,代码从低位跳到高位,而不是从上到下的好方法

import subprocess
from subprocess import Popen,PIPE

command = subprocess.Popen(['telnet','<ip>','<port>'],stdout=subprocess.PIPE,stdin=subprocess.PIPE,text=True)

#section 1 #(login console server)
command.stdin.write('<username>\n')
command.stdin.flush()
print(repr(command.stdout.readline()))
command.stdin.write('<password>\n')
command.stdin.flush()
print(repr(command.stdout.readline()))

#section 2 #(login host behind console server)
command.stdin.write('<username>\n')
command.stdin.flush()
print(repr(command.stdout.readline()))
command.stdin.write('<password>\n')
command.stdin.flush()
print(repr(command.stdout.readline()))

print(repr(command.stdout.readline()))
print(repr(command.stdout.readline()))
print(repr(command.stdout.readline()))
print(repr(command.stdout.readline()))
print(repr(command.stdout.readline()))
print(repr(command.stdout.readline()))
print(repr(command.stdout.readline()))
print(repr(command.stdout.readline()))
print(repr(command.stdout.readline()))
print(repr(command.stdout.readline()))

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)