SSH 进入 VM 和 运行 命令行并打印输出 - Python

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

我正在尝试通过 SSH 连接到我的 VM 和 运行 命令行并打印输出

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 }'")

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

我一直在

/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 }'
ps -ef | grep vnc | awk 'NR==1{print }' 


Process finished with exit code 0

但是如果我 运行 它在 VM 本身上,我应该看到这个

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

25871 <--- 我的 pid 列应该打印出来

如何将命令结果存储在变量中并重新使用该变量?

例如。我的 pid。我想抓住它并杀死它,然后对它做更多的事情。

invoke_shell() 用于 互动 会话。这里不需要。

改用exec_command(cmd)在行为上完全等同于ssh yourhost "$cmd"

使用 parallel-ssh 库(它使用 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 }'")
pid = list(output.stdout)
print pid

好处:更少的样板代码、合理的默认值、自动输出剥离和解码、并行和异步 SSH 客户端作为额外功能。