[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

python3 subprocess run sudo cmd in remote failed

On 17Sep2019 13:02, lampahome <pahome.chen at mirlab.org> wrote:
>> Note also that since stdin and stdout are pipes and not the terminal
>> then ssh will not be interactive, and will not allocate a tty at the far
>> end either. You can get ssh to open a remote tty with the -t option.
>> But I suspect you don't want stdin=PIPE or stdout=PIPE at all. Why are
>> they there?
> I thought I can use ps.stdin.write(password), so I make stdin and 
> stdout be pipe as input and output.

The trouble here is that ssh will only accept a password from a 
terminal. As soon as you connect a pipe it refuses to prompt. This is 
partly security (having a terminal is a proxy for "talking to a human"), 
and partly because ssh normally passes stdin to the remote process once 
authentication is complete, so things get fiddly.

You can give it a terminal by obtaining a pty and associating the 
subprocess with that. You could install the pexpect module with "pip 
install pexpect" and use that to manage this interaction. See the docs:


for further info.

However, I repeat my recommendation to use a keypair for the 
authentication, as it avoids needing interactive passwords (and having 
your programme know the password has its own suite of problems to do 
with where that password comes from).

>Here are I tried:
>>from subprocess import Popen, PIPE
>>ps = Popen('ssh -o \'StrictHostKeyChecking no\' hello at \'sudo
>sysctl -w vm.drop_caches=3\', shell=True)
>>  hello at's password:
>>from subprocess import Popen, PIPE
>>ps = Popen(['ssh',  '-o \'StrictHostKeyChecking no\'',  '
>hello at', '\'sudo sysctl -w vm.drop_caches=3\''])
>>  hello at's password:
>It always prompt immediately, that make me hard to enter password.

Well ssh will be connected to your terminal. Do things work if you hand 
type the password at that point?

> Maybe I should try  paramiko...

Or pexpect.

But use a keypair - it will simplify your life, and generally be far 
more secure anyway.

Cameron Simpson <cs at cskk.id.au>