我最近开始研究面料进行远程部署。我需要切换到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.
更新
正如J.F. Sebastian建议的那样,su newUser -c
可以工作,但它会为每个服务器的每个命令提示密码,这会破坏自动化的目的。 Fabric中是否有任何方法可以根据提示传递相同的值(在这种情况下,它总是Password:
)
答案 0 :(得分:11)
谢谢J F Sebastian,有几次捕获。
以下是最终的结果。它的工作。
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)
答案 1 :(得分:7)
如果您不能使用newuser
ssh并且无法使用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)