user5142625
user5142625

Reputation: 85

Subprocess remote command execution in python

I am trying to execute remote command using subprocess:

import subprocess
x=subprocess.Popen(['ssh','15.24.13.14', ' ps -ef | grep -i upgrade | wc -l'],stdout=subprocess.PIPE)
y=x.stdout.read()
print y
print '\n'
z=int(y)
print z

I need to get number of processes runing with 'upgrade' in their name. But for some reason, script is not executed well. I get message: "Warning: Permanently added '15.24.13.14' (RSA) to the list of known hosts." And then nothing happens. Where is the problem?

Upvotes: 1

Views: 2791

Answers (2)

Buyuk
Buyuk

Reputation: 1094

The problem is that if you are connecting for the first time via ssh to the given host, it asks you to add this host to the known hosts list and user has to confirm this by pressing 'y'. Since you didn't, than it hangs and does nothing.

You should either:

  • turn off host verification: ssh -o "StrictHostKeyChecking no" user@host
  • send 'y' to the ssh input, or
  • add this host manually to the known hosts, or
  • change the method of performing remote calls.

Upvotes: 2

FunkySayu
FunkySayu

Reputation: 8061

Because you didn't specify any stderr to the subprocess.Popen, the standard error will be directly print to your display. This is why you will always have the Warning: Permanently added '<hostname>' (ECDSA) to the list of known hosts. message until you clearly redirect stderr to a subprocess.PIPE (or /dev/null)

Also, to avoid hosts file issues, here is a little trick (be careful with it, it's kind of dangerous) :

from subprocess import Popen, PIPE
p = Popen(['ssh', '-o', 'UserKnownHostsFile=/dev/null', '-o', 'StrictHostKeyChecking=no', hostname, 'ps aux | grep -i upgrade | wc -l'], stdout=PIPE, stderr=PIPE)
result = int(p.communicate()[0][:-1]) # don't forget there's the \n at the end.

Why is it dangerous ? Because in case of MITM attack, you don't have any knowledge base of the remote, so you considere the attacker as your remote destination. Be careful about over-using this feature.

Upvotes: 1

Related Questions