让python在运行csh脚本时输入密码
题
我正在编写一个在Solaris 10中执行csh脚本的python脚本.csh脚本会提示用户输入root密码(我知道)但是我不知道如何让python脚本回答提示密码。这可能吗?以下是我用来执行csh脚本的内容:
import commands
commands.getoutput('server stop')
解决方案
查看 pexpect 模块。它旨在处理交互式程序,这似乎是你的情况。
哦,请记住shell或python脚本中的硬编码root密码可能是一个安全漏洞:D
其他提示
使用子流程。调用Popen()创建进程并使用communic()发送文本。对不起,忘了加入PIPE ..
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)
诀窍! Pexpect规则!
在 proc.communicate()
中添加 input =
使其运行,适合喜欢使用标准库的人。
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身份运行脚本。这个问题仍然没有答案,但我想我现在就这样做。
不隶属于 StackOverflow