2015-08-15 65 views
0

我想使用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 

任何人都能够看到它失败?

+0

OP提到该功能起作用,但不是当它来自CSV文件时 – asiviero

+0

这是字符串格式问题,asiviero的答案起作用。 –

回答

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被删除。

+0

这样工作!谢谢! –