如何将这些值从 txt 导入到我的循环中?

How can I import these values from txt into my loop?

编辑:感谢下面的两位用户,我的脚本现在可以运行了。我已经为任何想要使用 Python/Paramiko 提示用户输入 username/password 和 SCP 文件到目的地的人更新了我的代码。

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

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

我显然还没有掌握python中while循环的概念。当我明确定义位于 ssh_client.connect(hostname=server,username=user,password=passw) 行,但不在 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

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

您不想将整个列表作为主机名,可以试试吗。

ssh_client.connect(hostname=ip,username=user,password=passw)

而不是

ssh_client.connect(hostname=ips,username=user,password=passw)