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

时间:2019-07-28 16:00:11

标签: python paramiko scp

编辑:感谢下面的两个用户,我的脚本现在可以工作了。我已更新以下代码,以供所有希望使用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)行,但不在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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您不希望将整个列表作为主机名。

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

代替

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