简体   繁体   中英

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

I have the following script to make updates on remote systems.

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))

I have a list of few hundred IPs where I need to make updates. I do that using the following script.

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))

When the ssh key is configured everything works just fine, but I have to deploy this to the machines where ssh key is not to be configured. In that case it asks for the password each time it makes a new ssh connection. The password for all devices is the same. To type the password for few hundred times is not convenient.

When I passed the password from the command line it didn't work.

For some reason I have to login as root thus sudo password doesn't work in this case; is what I think is happening.

Is there any way to automate this or to pass the password in the argument to fab command?

thanks in advance.

Here's how I would approach your problem:

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

Then I would run it like this:

fab make_update_all

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM