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


