osdir.com


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

python3 subprocess run sudo cmd in remote failed


On 17Sep2019 12:13, lampahome <pahome.chen at mirlab.org> wrote:
>Hello, I use python3.5 and found no way to solve this problem
>
>>from subprocess import Popen, PIPE
>>ps = Popen('ssh -o \'StrictHostKeyChecking no\' hello at 192.168.80.11 \'sudo
>sysctl -w vm.drop_caches=3\', stdin=PIPE, stdout=PIPE, stderr=PIPE,
>bufsize=0, shell=True)
>>  hello at 192.168.80.11's password:
>
>what I tried many times like enter password, but it failed.
>I just want to use ps.stdin.write(password) to send password, but it always
>jump password prompt immediately.

Well, there's a Python library called "paramiko" which implements ssh.  
That might help.

But really you should avoid using password authentication altogether.  
Generate a public/private keypair using ssh-keygen and install the 
public half on the target machine.

Then all you need to do is to deal with sudo's password.

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?

Also, try doing this without shell=True - it is an invitation for 
mistakes and shell injection (depending on your uses).

Cheers,
Cameron Simpson <cs at cskk.id.au>