我正在编写一个在 Solaris 10 中执行 csh 脚本的 python 脚本。csh 脚本提示用户输入 root 密码(我知道),但我不确定如何让 python 脚本用密码回答提示。这可能吗?这是我用来执行 csh 脚本的内容:
import commands
commands.getoutput('server stop')
看看pexpect模块。它旨在处理交互式程序,这似乎是您的情况。
哦,请记住,在 shell 或 python 脚本中硬编码 root 的密码可能是一个安全漏洞:D
使用子进程。调用 Popen() 来创建您的进程并使用communicate() 向它发送文本。对不起,忘了包括管道..
from subprocess import Popen, PIPE
proc = Popen(['server', 'stop'], stdin=PIPE)
proc.communicate('password')
您最好避免使用密码并尝试像 sudo 和 sudoers 这样的方案。在别处提到的 Pexpect 不是标准库的一部分。
import pexpect
child = pexpect.spawn('server stop')
child.expect_exact('Password:')
child.sendline('password')
print "Stopping the servers..."
index = child.expect_exact(['Server processes successfully stopped.', 'Server is not running...'], 60)
child.expect(pexpect.EOF)
成功了!期待规则!
input=
为喜欢使用标准库的人添加proc.communicate()
让它运行。
from subprocess import Popen, PIPE
proc = Popen(['server', 'stop'], stdin=PIPE)
proc.communicate(input='password')
应该可以将其作为参数传递。就像是:
commands.getoutput('server stop -p password')
这似乎效果更好:
import popen2
(stdout, stdin) = popen2.popen2('server stop')
stdin.write("password")
但这还不是 100%。即使“密码”是正确的密码,我仍然得到 su: 对不起,当它试图 su 到 root 时,从 csh 脚本返回。
为避免在 python 脚本中回答密码问题,我将以 root 身份运行脚本。这个问题仍然没有答案,但我想我现在就这样做。