我最近开始研究用于远程部署的结构.我需要切换到diff用户(从我登录的用户),我无法弄明白.甚至是可能的,如果是这样的话怎么样?我当前的用户没有sudo
权限.
我尝试更改以下环境变量
env.sudo_prefix = "su newUser -c " env.sudo_prompt = "Password:"
但是Fabric不会等待'newUser'的密码输入而失败.
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.
更新:
正如JF Sebastian建议的那样,su newUser -c
但它会为每个服务器的每个命令提示密码,这会破坏自动化的目的.Fabric中是否有任何方法可以根据提示传递相同的值(在这种情况下,它始终是Password:
)
谢谢JF Sebastian,有几次捕获.
Fabric会延迟连接,所以我必须在调用su之前进行虚拟连接以避免上下文切换.
Pwd需要存储在全局范围内,以便可以重复使用.Fabric不会将其放在高速缓存中以覆盖su命令.
这是最终做的事情.它的工作.
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)
如果你不能ssh as newuser
并且不能使用sudo(command, user='newuser')
:
import getpass # just for demonstration from fabric.api import sudo, settings def su(user, command): with settings(password=getpass.getpass('enter password for %s: ' % user), sudo_prefix="su %s -c " % user, sudo_prompt="Password:"): sudo(command)