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.
ps -ef | grep vnccan return the PID ofgrep vnc, since it contains the stringvnc. Usepgrepinstead to avoid this and other caveats, or, much better, use a proper process supervision system for managing services -- systemd, upstart, runit, DJB daemontools, etc.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.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 ofgrepitself)? Before we try to automate things with paramiko, always best to be sure they function correctly in the first place. :)sshpass).