使用列表项作为函数参数

时间:2015-08-15 00:56:33

标签: python function paramiko

我正在尝试使用Python / paramiko备份路由器配置。我编写了一个有效的函数,但我想读取一个CSV,拆分行,然后将列表中的项作为参数传递给函数。

这是代码:

import datetime
import paramiko

def tftpbackup(tftphost,netdevice,hostname):
    date = datetime.date.today().strftime("%Y%m%d")
    sshuser = 'autobackup'
    sshpass = 'nmol#567'
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(netdevice, username= sshuser, password= sshpass)
    stdin, stdout, stderr = ssh.exec_command("copy run tftp")
    stdin.write(tftphost+'\n')
    stdin.flush()
    stdin.write(hostname + '-cfg-' + date + '\n')
    print(hostname + '-cfg-' + date + '\n')



netdevices = open ("network devices.csv","r")

for line in netdevices:
    device = line.split(",")
    hostname = device[0]
    ipaddr = device[1]
    ipaddr.strip()
    hostname.strip()
    tftpbackup('10.20.17.21',ipaddr,hostname)
    print (ipaddr, hostname)

netdevices.close()

这是CSV:

cclcoresw,10.200.17.2
ccl1stflrmdfsw01,10.200.17.3
ccl1stflrmdfsw02,10.200.17.4
ccl1stflrmdfsw03,10.200.17.5
ccl1stflrmdfsw04,10.200.17.14
ccl3rdflridfsw01,10.200.17.8
cclphdidfsw01,10.200.17.9

失败并出现以下错误:

Traceback (most recent call last):
  File "C:\Python34\Lib\SITE-P~1\PYTHON~2\pywin\framework\scriptutils.py",              
 line 326, in RunScript
    exec(codeObject, __main__.__dict__)
  File "C:\Users\*redacted*\Desktop\tftp backup.py", line 27, in <module>
    tftpbackup('10.20.17.21',ipaddr,hostname)
  File "C:\Users\*redacted*\Desktop\tftp backup.py", line 10, in tftpbackup
    ssh.connect(netdevice, username= sshuser, password= sshpass)
  File "C:\Users\*redacted*\AppData\Roaming\Python\Python34\site-    
packages\paramiko\client.py", line 237, in connect
    for (family, socktype, proto, canonname, sockaddr) in   
socket.getaddrinfo(hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM):
  File "C:\Python34\lib\socket.py", line 530, in getaddrinfo
     for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11004] getaddrinfo failed

任何人都能看到失败的地方吗?

1 个答案:

答案 0 :(得分:0)

该行的末尾包含\n,因此您的阅读会产生IP '10.200.17.2\n',依此类推。

只需将其更改为

即可
netdevices = open ("network devices.csv","r")

for line in netdevices:
    device = line.rstrip("\n").split(",")
    hostname = device[0]
    ipaddr = device[1]
    ipaddr.rstrip("\n")
    hostname.rstrip()
    tftpbackup('10.20.17.21',ipaddr,hostname)
    print (ipaddr, hostname)

netdevices.close()

所以\n被删除了。