Make python enter password when running a csh scri

2020-02-26 11:18发布

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')

7条回答
Viruses.
2楼-- · 2020-02-26 11:45

Use subprocess. Call Popen() to create your process and use communicate() to send it text. Sorry, forgot to include the PIPE..

from subprocess import Popen, PIPE

proc = Popen(['server', 'stop'], stdin=PIPE)

proc.communicate('password')

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.

查看更多
▲ chillily
3楼-- · 2020-02-26 11:47
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)

Did the trick! Pexpect rules!

查看更多
淡お忘
4楼-- · 2020-02-26 11:47

Add input= in proc.communicate() make it run, for guys who like to use standard lib.

from subprocess import Popen, PIPE
proc = Popen(['server', 'stop'], stdin=PIPE)
proc.communicate(input='password')
查看更多
混吃等死
5楼-- · 2020-02-26 11:48

This seems to work better:

import popen2

(stdout, stdin) = popen2.popen2('server stop')

stdin.write("password")

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.

查看更多
Deceive 欺骗
6楼-- · 2020-02-26 11:50

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

查看更多
叼着烟拽天下
7楼-- · 2020-02-26 11:51

Should be able to pass it as a parameter. something like:

commands.getoutput('server stop -p password')
查看更多
登录 后发表回答