Python fabric 将 root 密码作为命令行参数传递不起作用

Python fabric passing root password as command line argument doesn't work

我有以下脚本可以在远程系统上进行更新。

from fabric.api import run
serverIp   = "192.168.1.1"
serverPort = "8000"
filename   = "MyFIle.tar.gz"
dirName    = "MyDir"

def makeUpdate():
    run("/bin/update.sh {0} {1} {2} {3}".format(serverIp, serverPort,
                                                filename, dirName))

我有一个包含数百个 IP 的列表,我需要在其中进行更新。我使用以下脚本来做到这一点。

import os
data =  open("clients.txt").read().strip().split("\n")

for i in data:
    if i:
        print(i)

for i in data:
    os.system("fab -H {0} -u root -I host_type".format(i))

配置 ssh 密钥后一切正常,但我必须将其部署到不配置 ssh 密钥的机器上。在这种情况下,它会在每次建立新的 ssh 连接时询问密码。所有设备的密码都相同。密码输入几百次不方便

当我从命令行传递密码时,它不起作用。

出于某种原因,我必须以 root 身份登录,因此 sudo 密码在这种情况下不起作用;这就是我认为正在发生的事情。

有什么方法可以自动执行此操作或将参数中的密码传递给 fab 命令?

提前致谢。

以下是我处理您的问题的方法:

import getpass # for getting the password from the user
import json # for outputting raw data
from fabric.api import execute, run, settings, task

@task
def make_update():
    # keeping global scope clean
    server_ip = "192.168.1.1"
    server_port = "8000"
    file_name = "MyFIle.tar.gz"
    dir_name = "MyDir"
    # return data so we can review it if we want
    return run("/bin/update.sh {0} {1} {2} {3}".format(
        server_ip, server_port, file_name, dir_name
    ))

@task
def make_update_all():
    # generate host list from file
    with open("clients.txt") as f:
        hosts = f.read().splitlines()
    # locally modify fabric environment
    with settings(
        user="root",
        password=getpass.getpass(), # get the root password
        parallel=True # do work in parallel to save time (False for debug)
    ):
        results = execute(make_update, hosts=hosts)
    print json.dumps(results, indent=4) # output results in a semi-legible way

然后我会运行这样:

fab make_update_all