使用pexpect.spawn.interact在pexpect.spawn进程中输入lxc-start的sudo密码

时间:2014-05-23 17:29:08

标签: python sudo pexpect lxc

我想在python脚本中使用sudo lxc-start -n <lxc-name> --lxcpath=/some/custom/path启动lxc并使用pexpect控制它(登录,安装包,添加用户并注销/关闭lxc)。一个例子看起来像这样(我非常接近解决方案,只需要escape_character的正确pexpect.spawn.interact参数):

import pexpect
child = pexpect.spawn("sudo lxc-start --name=debian-wheezy-amd64 --lxcpath=/some/custom/path/")
child.expect("Password:") # the sudo password prompt (might be optional if the script has been invoked with sudo (let's keep in anyway as an exercise))
child.interact("??") # tried "\r" -> never returns, "\r\r" and "\n" -> accepts the sudo password, but doesn't give back the control to the python interpreter (stuck at lxc login)
child.expect("login")
child.sendline("root")
# etc. (tasks mentioned above)
child.expect("[#$][\\s]")
child.sendline("shutdown -h 0")

如果我使用getpassword输入密码,则Everythings运行良好,将其存储在变量中并使用child.expect("Password:"); child.sendline(mypassword)传递,因此上面的解决方案更适合于pexpect

是否所有操作系统/ lxcs都有一个通用的escape_character来输入sudo密码,或者它们是否有所不同(如果它们确实有一种通用的方法来确定它们,而与操作系统的知识无关(例如, shell变量)?)

0 个答案:

没有答案