0

I'm trying to SSH into my VM and run a command line and print the output

import paramiko
import time
import os
import sys

# Note
# sudo pip install --user paramiko


def ssh_con (ip, un, pw):
    global ssh
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    print ("SSH CONNECTION ESTABLISHED TO %s" % ip)
    ssh.connect(ip, username=un, password=pw,key_filename='/Users/keys/id_ssc-portal', timeout=200)


def cmd(command):
    global ssh_cmd

    print ("Run : " + command)
    ssh_cmd.send("%s \n" %command)
    time.sleep(1)
    output = ssh_cmd.recv(10000).decode("utf-8")

    return output

ip = '172.19.242.27'
un = 'root'
pw = '####'

ssh_con(ip,un,pw)
ssh_cmd = ssh.invoke_shell()

p_id = cmd("ps -ef | grep vnc | awk 'NR==1{print $2}'")

print p_id <---------

I kept getting

/usr/bin/python /Applications/MAMP/htdocs/code/python/restart_vnc.py
SSH CONNECTION ESTABLISHED TO 172.19.242.27
Run : ps -ef | grep vnc | awk 'NR==1{print $2}'
ps -ef | grep vnc | awk 'NR==1{print $2}' 


Process finished with exit code 0

But if I run it on the VM itself, I should see this

[root@vm ~]# ps -ef | grep vnc | awk 'NR==1{print $2}'

25871 <--- my pid column should print out

How do I store a result of command in a variable and reuse that variable?

Ex. my pid. I want to grab it and kill it, and do something else more to it.

17
  • 1
    As an aside -- ps -ef | grep vnc can return the PID of grep vnc, since it contains the string vnc. Use pgrep instead to avoid this and other caveats, or, much better, use a proper process supervision system for managing services -- systemd, upstart, runit, DJB daemontools, etc. Commented Apr 24, 2017 at 21:19
  • Or, if you're inclined to go the quick-ugly-hack route anyhow, consider ps -ef | awk '/vnc/ && ! /awk/ { print $2; }' -- that way you're still only using one command-line element (awk, in this case), but having it do the work of filtering itself out. Commented Apr 24, 2017 at 21:22
  • 1
    BTW -- does running ssh [email protected] $'ps -ef | grep vnc | awk \'NR==1{print $2}\'' work at an interactive bash prompt (other than the caveat around returning the PID of grep itself)? Before we try to automate things with paramiko, always best to be sure they function correctly in the first place. :) Commented Apr 25, 2017 at 13:15
  • 1
    (That said, if you want automation that doesn't rely on paramiko, consider sshpass). Commented Apr 25, 2017 at 13:22
  • 1
    The big advantage of paramiko is that it lets you reuse a single Transport for multiple commands without needing to play around with ControlMaster/ControlSocket (which is how the OpenSSH way of accessing that same protocol-level functionality works). If that advantage isn't important to you, it doesn't much matter. Commented Apr 25, 2017 at 14:59

2 Answers 2

1

invoke_shell() is for interactive sessions. You don't need one here.

Use exec_command(cmd) instead, which is exactly equivalent in behavior to ssh yourhost "$cmd".

Sign up to request clarification or add additional context in comments.

3 Comments

How do I get store a result of command in a variable and reuse that variable ? Ex. my pid. I want to grab it and kill it, and do something else more to it.
exec_command() returns stdin, stdout and stderr -- so if you want to read stderr into a variable, easy 'nuff. Immediately close the stdin if you don't want to write anything to the command, and then read from stdout and stderr -- the former for your result, the latter for explanatory content to include in any exception if you have a failure.
(err, should have been "read stdout into a variable", above, since that's where your result will be).
1

Complete answer using parallel-ssh library (it uses paramiko).

from pssh import ParallelSSHClient
ip = '172.19.242.27'
un = 'root'
pw = '####'

client = ParallelSSHClient(hosts=[ip], user=un, password=pw)
output = client.run_command("ps -ef | grep vnc | awk 'NR==1{print $2}'")
pid = list(output.stdout)
print pid

Benefits: Tons less boiler plate code, sane defaults, auto output strip and decode, parallel and asynchronous SSH client as extras.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.