【问题标题】:python telnetlib.telnet() not connecting using variablespython telnetlib.telnet() 没有使用变量连接
【发布时间】:2020-08-06 13:34:20
【问题描述】:

我正在编写一个脚本以从 GNS3 中的 Cisco 设备中提取配置。该脚本应该循环通过一个文本文件并将每一行的 IP 和端口分割成变量。然后将这些变量作为Telnetlib 的 IP 和端口参数输入 telnet 连接。

import telnetlib

#Open file with list of switches
f = open ("C:\ProgramData\ports.txt")

#Telnet to each switch and configure it
for line in f:
    linePort = line[10:]
    lineIP = line[:-6]
    print "Getting running-config " + lineIP + " " + linePort
    tn = telnetlib.Telnet(lineIP,linePort)

但是,使用变量总是会引发错误(见下文),但如果我对相同的值进行硬编码,我可以毫无问题地创建连接。由于它适用于硬编码值,我尝试在两个变量上强制使用 str() 的字符串类型,但它没有改变结果,它仍然抛出以下错误。

C:\Users\SomeUser>python %userprofile%\desktop\config.py
Getting running-config 127.0.0.1  5000

Traceback (most recent call last):
  File "C:\Users\Michael\desktop\config.py", line 11, in <module>
    tn = telnetlib.Telnet(lineIP,linePort)
  File "C:\python27amd64\lib\telnetlib.py", line 211, in __init__
    self.open(host, port, timeout)
  File "C:\python27amd64\lib\telnetlib.py", line 227, in open
    self.sock = socket.create_connection((host, port), timeout)
  File "C:\python27amd64\lib\socket.py", line 557, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno 10109] getaddrinfo failed

抛出的错误是socket.gaierrr: [Errno 10109] getaddrinfo failed,我已尝试调查但未能找到适合我的解决方案。鉴于这个过程应该是自动化的并且在一个循环中,让它与变量一起工作是至关重要的。因此,我们将不胜感激您能提供的任何帮助。

【问题讨论】:

    标签: python telnetlib


    【解决方案1】:

    我在另一个问题中偶然发现了answer,这让我觉得自己像个白痴一样疏忽大意。

    当为Telnet 的参数使用变量时,端口需要是整数。因此,解决方案是使用int(var) 强制它,然后连接没有问题。现在工作的代码如下。

    import telnetlib
    
    #Open file with list of switches
    f = open ("C:\ProgramData\ports.txt")
    
    #Telnet to each switch and configure it
    for line in f:
        linePort = line[10:]
        lineIP = line[:-6]
        print "Getting running-config " + lineIP + " " + linePort
        tn = telnetlib.Telnet(lineIP,int(linePort))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-22
      • 2018-01-27
      • 1970-01-01
      • 2017-02-15
      • 2014-01-26
      • 1970-01-01
      • 2012-08-20
      相关资源
      最近更新 更多