非标准端口上的 Python telnetlib 提示

标签 python terminal console virtual-machine telnet

网络专家在这里玩编码

我有一个非常基本的脚本,可以远程登录到交换机/路由器,运行一些命令并终止。一切都是在端口 23 上完成的。我遇到的问题是,当我通过术语服务器连接到设备或通过非标准端口连接到 ESXi 主机上的虚拟路由器(csr1000v)时,我没有得到出现提示,我无法运行命令。

在 SecureCRT 中,我可以毫无问题地连接到它们,但在出现提示之前我必须按 Enter 键。在普通交换机/路由器中,会立即出现提示。 我尝试在连接建立后放入 telnet.write(b"\r\n") 但没有什么区别。

我还设置了如果我通过 SecureCRT 发出提示,断开连接然后运行脚本,它会成功执行。 我已阅读 telnetlib 文档,但没有任何看起来有帮助的内容

telnet = telnetlib.Telnet(HOST,port)
#telnet.write(b"  \r\n")
telnet.read_until(b"Username: ")
telnet.write(user.encode('ascii'))
telnet.read_until(b"Password: ")
telnet.write(password.encode('ascii'))
telnet.read_until(b">")

telnet.write(b"enable\r\n")
telnet.read_until(b"Password: ")
telnet.write(enable_password.encode('ascii'))
telnet.read_until(b"#")
telnet.write(b"term length 0\r\n")
telnet.read_until(b"#")

response = send_command(telnet,"sh run")
print (response)
response = send_command(telnet," sh ip int br | ex una")
print (response)

最佳答案

这不是常规的 telnet。这是通过 telnet 进行串行传输的。您应该发送规范。首先telnet 数据。

import time
import telnetlib
cmd_ser1 = '\xff\xfc\x25'
cmd_ser2 = '\xff\xfb\x00'
cmd_ser3 = '\xff\xfd\x00\xff\xfb\x03\xff\xfd \x03\xff\xfd\x01\xff\xfe\xe8'
cmd_ser4 = '\xff\xfe\x2c'
cmd1 = "enable"
cmd2 = "cisco"
cmd3 = "copy running-config flash:/test.cfg"
cmd4 = "exit"

promt = "%s>"%(host)
host_disable = "%s>"%(host)


tn = telnetlib.Telnet(addr,port, timeout=5)
tn.set_debuglevel(100)
tn.write(cmd_ser1)
time.sleep(1)
tn.write(cmd_ser2)
time.sleep(1)
tn.write(cmd_ser3)
time.sleep(1)
tn.write(cmd_ser4)
time.sleep(1)
tn.read_very_eager()

if promt == "host_disable":
   tn.write(cmd1.encode('ascii') + b"\n")
   time.sleep(1)
   tn.read_very_eager()
   tn.write(cmd2.encode('ascii') + b"\n")
   time.sleep(2)
   tn.read_very_eager()
   tn.write(cmd3.encode('ascii') + b"\n")
   tn.read_very_eager() 
   tn.write(b"\n")
   time.sleep(2)
   tn.write(b"\n")
   time.sleep(2)
   tn.write(cmd4.encode('ascii') + b"\n")
   tn.read_very_eager()
   tn.close()
else:
  tn.write(cmd3.encode('ascii') + b"\n")
  tn.read_very_eager()
  tn.write(b"\n")
  tn.write(b"\n")
  time.sleep(2)
  tn.write(cmd4.encode('ascii') + b"\n")
  tn.read_very_eager()
  tn.close()

关于非标准端口上的 Python telnetlib 提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30039708/

相关文章:

python - return 语句的目的是什么?它与打印有何不同?

mysql - 创建一个 MySQL 表,其字段名可能包含 INT 和 VARCHAR

function - 如何在 bashrc 中创建一个函数来接受参数?

java - 未进入 tessract 方法 doOCR(File imageFile) 内部

python - BottlePy 和 GEVENT 出现 SSL 错误

python - 如何创建一个在 python 中给出答案时关闭的循环?

python 子进程不能很好地使用 gsutil 复制/移动命令

javascript - 检测用户何时在浏览器中执行 JavaScript

c# - 从 WPF 应用程序附加到现有控制台的解决方法?

python - import 语句是否应该始终位于模块的顶部?