code-8
code-8

Reputation: 58810

SSH into a VM and run a command line and print the output - Python

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.

Upvotes: 0

Views: 3253

Answers (2)

danny
danny

Reputation: 5270

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.

Upvotes: 1

Charles Duffy
Charles Duffy

Reputation: 296019

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".

Upvotes: 1

Related Questions