您可以使用Pexpect的解决您的问题。使用这个python模块,你可以产生一个root shell,发送root密码到进程中,然后执行多个命令。
Pexpect的是一个很好的把戏自动化任何类型的交互shell程序......它工作正常,在这个例子 - 但存储根PW在这样的脚本有严重的安全隐患(将用户添加到sudoers文件,而不密码有严重的安全隐患,以及)...
import pexpect, sys
# spawn a root shell with sudo or su depending on your linux
proc = pexpect.spawn("su")
proc.logfile = sys.stdout
# wait until the programm finds the string Password or password
# in the shell output
proc.expect("[Pp]assword")
# then: send the password to the waiting shell
proc.sendline("yourRootPW123")
# wait until the command completed ("#" is part of the next prompt)
proc.expect("#")
# run the whoami command
proc.sendline("whoami")
# wait for next prompt
proc.expect("#")
proc.sendline("ls -al")
proc.expect("#")
# ...
这将输出:
[email protected]:~$ python script
[sudo] password for myuser: **************
[email protected]:~# whoami
whoami
root
[email protected]:~# ls -al
ls -al
total 60
drwx------ 5 root root 4096 Dez 18 14:38 .
drwxr-xr-x 23 root root 4096 Jan 21 14:18 ..
-rw------- 1 root root 13149 Jan 27 10:19 .bash_history
-rw-r--r-- 1 root root 3106 Feb 20 2014 .bashrc
...
你可以阅读更多关于此这里:automate with python pexpect
须藤蟒script.py –
参见运行命令['subprocess'](https://docs.python.org/2/library/subprocess.html)模块。我建议用'sudo'运行每个命令,而不是使用'su'。用户只能在第一次被提示输入密码。 – augurar
@sanyesh:读'人sudoers',假设你的Python脚本可以驻留在标准位置和用户的一组给定需要使用它,你可以在“白名单”,要求在'sudoers'文件中超级用户权限的命令和使用'NOPASSWD',这样的脚本甚至可以无人看管。 – 0xC0000022L