首页 > 解决方案 > 如何将这些值从 txt 导入到我的循环中?

问题描述

编辑:感谢下面的两个用户,我的脚本现在可以工作了。对于希望使用 Python/Paramiko 提示用户输入用户名/密码和 SCP 文件到目的地的任何人,我已经更新了下面的代码。

我正在开发一个小型自动化工具,以通过 SCP 从 Linux 服务器自动交付更新包。这个想法是创建一个包含 10-20 个 IP 地址的 txt 文件('hostfile.txt'),然后让 python 脚本在列表中运行并按顺序在列表中打开一个 SSH/SCP 会话,并交付包裹。

注意:这是我在指南书中的几个小项目之外的第一个实际的 Python 编程片段。随时提供有用的建议来改进代码:)

我显然还没有掌握python中while循环的概念。当我明确定义了位于该 ssh_client.connect(hostname=server,username=user,password=passw)行中的目标 IP,但不在 while 循环中时,该脚本有效。

以下是整个脚本,以防将来有人想要使用它:

## 29 July 2019
## This script is used for automating the transfer of files to remote devices.

import os
import getpass
import paramiko
import logging
from scp import SCPClient
from pprint import pprint

os.system("clear")

print("############################################")
print(" PROGRAM SCP to IOS - Script 29 Jul 2019 ")
print("############################################")
#user=('silkyjohnson')
user=raw_input("what is your user name?:   ")
passw=getpass.getpass("What is your password?:  ")


##Source file selection:
dirlist = os.listdir("/scp/")
pprint(dirlist)
src=raw_input("Which file would you like to transfer?:   ")

##Destination selection:
dst=raw_input("Please enter destiantion path:  ")

##Summary:
print("############################################")
print("You have chosen to load "+src+" to "+dst)
print("The above choices will be appled to the following devices: ")
with open('/scp/hostfile.txt', 'r') as hf:
    print(hf.read())
hf.close()

### ssh session

with open('/scp/hostfile.txt', 'r') as hf:
    ips = hf.readlines()
    for ip in ips:
            ssh_client =paramiko.SSHClient()
            ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh_client.connect(hostname=ips,username=user,password=passw)
##scp
        scp = SCPClient(ssh_client.get_transport())
        scp.put(src, recursive=True, remote_path=dst)

我希望脚本能够通过列表中的 IP 运行,但我对这些试验感到沮丧,这就是我创建帐户的原因。如果有人能带我完成这个,我将永远感激不尽:)

忘记包含错误代码,对不起!

Traceback (most recent call last):
  File "iosupdate.py", line 50, in <module>
    ssh_client.connect(hostname=ips,username=user,password=passw)
  File "/usr/lib/python2.7/dist-packages/paramiko/client.py", line 296, in connect
    to_try = list(self._families_and_addresses(hostname, port))
  File "/usr/lib/python2.7/dist-packages/paramiko/client.py", line 200, in _families_and_addresses
    addrinfos = socket.getaddrinfo(hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM)
TypeError: getaddrinfo() argument 1 must be string or None

标签: pythonparamikoscp

解决方案


您可以尝试ips = hf.readlines()从文件中读取行并查看它是否有效吗?


推荐阅读