使用结构切换到不同的用户 [英] switch to different user using fabric

查看:16
本文介绍了使用结构切换到不同的用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始研究用于远程部署的结构.我需要切换到一个 diff 用户(从我登录的那个用户)并且无法弄清楚.甚至有可能吗,如果有的话怎么办?我当前的用户没有 sudo 权限.

I recently started looking at fabric for remote deployment. I need to switch to a diff user (from the one that I login as) and am not able to figure it out. Is it even possible, if so how? My current user doesnt have sudo permissions.

我尝试更改以下环境变量

I tried changing following environment variables

env.sudo_prefix = "su newUser -c "
env.sudo_prompt = "Password:"

但是fabric 不等待'newUser' 的密码输入并且失败.

But fabric does not wait for password input for 'newUser' and fails.

out: Password: 
[oldUser@ec2-111-11-111-111.compute-1.amazonaws.com] out: su: incorrect password

Fatal error: sudo() received nonzero return code 1 while executing!

Requested: touch x
Executed: su newUser -c  -u "root"  /bin/bash -l -c "cd /home/oldUser/upgrade && touch x"

Aborting.
Disconnecting from oldUser@ec2-111-11-111-111.compute-1.amazonaws.com... done.

更新:

正如 J.F. Sebastian 所建议的,su newUser -c 可以工作,但它会为每个服务器的每个命令提示密码,这违背了自动化的目的.Fabric 中有没有办法根据提示传递相同的值(在这种情况下,它总是 Password:)

As J.F. Sebastian suggested, su newUser -c works, but it prompts password for every command for every server, which kind of defeats the purpose of automation. Is there any way in Fabric to pass in same value based on prompt (in this case, its always Password:)

推荐答案

谢谢 JF Sebastian,有几个的渔获物.

Thanks J F Sebastian, There were couple of catches.

  1. Fabric 懒惰地建立连接,所以我必须在调用 su 之前建立一个虚拟连接以避免上下文切换.
  2. 密码需要存储在全局范围内,以便可以重用.Fabric 不会将其放入缓存中以用于覆盖的 su 命令.

这就是最终要做的事情.它的工作.

Here is what ended up doing. Its working.

pwd = None
@hosts('myhost.com')
def test():
    with cd('/home/oldUser/upgrade'):
        run('ls')  #This is to connect aggressively (instead of lazily)
        global pwd  #Change the scope of pwd
        if pwd is None:
            pwd = getpass.getpass('enter password for newUser')

        execute(su, pwd, 'newUser', 'touch x')  
        run ('ls')
        execute(su, pwd, 'newUser', 'rm x') 
        run ('ls')

def su(pwd, user, command):
    with settings(
        password= "%s" % pwd,
        sudo_prefix="su %s -c " % user,
        sudo_prompt="Password:"
        ):
        sudo(command)

这篇关于使用结构切换到不同的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆