使用列表项作为函数参数

2024-10-01 00:17:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用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

有人能看到它的失败之处吗?你知道吗


Tags: inpyparamikodatestdinlinesocketssh
1条回答
网友
1楼 · 发布于 2024-10-01 00:17:53

行的末尾包含\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被删除。你知道吗

相关问题 更多 >