获取SSH到Cisco路由器的IP地址时出错

时间:2013-12-26 19:05:05

标签: python ssh

我正在尝试通过ssh在思科设备列表上执行一组命令;这样做,我得到以下错误

  

“gaierror:[Errno 11004] getaddrinfo失败了。”

Fetch.txt是一个文本文件,其中逐个提到设备的IP地址。

import paramiko
import sys
import os
import select
import subprocess

with open('fetch.txt', 'r') as f:
    for line in f:

        print line
        dssh = paramiko.SSHClient()
        dssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        dssh.connect(line, username='cisco', password='cisco')
        mystring = stdout.read()
        print mystring
        f = open('output.txt', 'a+')
        f.write(mystring)
        f.close()

dssh.close()

Fetch.txt文件如下所示,

    10.0.0.1
    10.0.0.2
    10.0.0.3
    10.0.0.4
    10.0.0.5
    10.0.0.6
    10.0.0.7

1 个答案:

答案 0 :(得分:0)

迭代文件,line包含一个尾随换行符。这可能是导致gaierror..例外的原因之一。

>>> import socket
>>> socket.create_connection(('www.stackoverflow.com', 80)) # without newline
<socket._socketobject object at 0x0000000002C1B180>
>>> socket.create_connection(('www.stackoverflow.com\n', 80)) # with newline
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\socket.py", line 553, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno 11004] getaddrinfo failed

使用str.strip删除尾随换行符,然后将其传递给paramiko.SSHClient.connect

...
for line in f:
    line = line.strip() # <---
    print line
    ...