让python在运行csh脚本时输入密码
我正在编写一个在 Solaris 10 中执行 csh 脚本的 python 脚本。csh 脚本提示用户输入 root 密码(我知道),但我不确定如何使 python 脚本使用密码回答提示。 这可能吗? 这是我用来执行 csh 脚本的内容:
import commands
commands.getoutput('server stop')
I'm writing a python script that executes a csh script in Solaris 10. The csh script prompts the user for the root password (which I know) but I'm not sure how to make the python script answer the prompt with the password. Is this possible? Here is what I'm using to execute the csh script:
import commands
commands.getoutput('server stop')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
查看 pexpect 模块。 它旨在处理交互式程序,这似乎就是您的情况。
哦,请记住,在 shell 或 python 脚本中硬编码 root 的密码可能是一个安全漏洞:D
Have a look at the pexpect module. It is designed to deal with interactive programs, which seems to be your case.
Oh, and remember that hard-encoding root's password in a shell or python script is potentially a security hole :D
使用子进程。 调用 Popen() 创建进程并使用communicate() 向其发送文本。 抱歉,忘记包含 PIPE。
您最好避免使用密码并尝试 sudo 和 sudoers 等方案。 其他地方提到的 Pexpect 不是标准库的一部分。
Use subprocess. Call Popen() to create your process and use communicate() to send it text. Sorry, forgot to include the PIPE..
You would do better do avoid the password and try a scheme like sudo and sudoers. Pexpect, mentioned elsewhere, is not part of the standard library.
成功了! 期待规则!
Did the trick! Pexpect rules!
对于喜欢使用标准库的人来说,在
proc.communicate()
中添加input=
使其运行。Add
input=
inproc.communicate()
make it run, for guys who like to use standard lib.应该能够将其作为参数传递。 就像是:
Should be able to pass it as a parameter. something like:
这似乎效果更好:
但还不是 100%。 即使“password”是正确的密码,当它尝试 su 到 root 时,我仍然从 csh 脚本中得到 su: 抱歉。
This seems to work better:
But it's not 100% yet. Even though "password" is the correct password I'm still getting su: Sorry back from the csh script when it's trying to su to root.
为了避免必须回答 python 脚本中的密码问题,我将以 root 身份运行该脚本。 这个问题仍然没有答案,但我想我现在就这样做。
To avoid having to answer the Password question in the python script I'm just going to run the script as root. This question is still unanswered but I guess I'll just do it this way for now.