连接到主机并运行ps aux命令

时间:2017-08-22 03:37:46

标签: python linux

尝试ssh到Ubuntu并获取进程详细信息。可以连接并登录设备,但无法获得输出。获得如下输出,

连接到设备x.x.x.x. 1 ('命令:','ps aux | grep vmstat') 2 没有连接到x.x.x.x

import os
import paramiko
import time
import signal
import subprocess

processname = 'vmstat'

def connect_to_devices(ip, procname):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        ssh.connect(ip, username = 'xxxxx', password='xxxxx', timeout = 10)
        time.sleep(.25)
        channel = ssh.invoke_shell()
        output = channel.recv(10000)
        print(output)
        print("connected to device")
        proc = findprocess(procname)
        time.sleep(10)
        print('2')
        print(proc)
        return proc

    except:
        print("Did not connect to %s" % ip)
        return 'failed'

def findprocess(p):
    print('1')
    command = 'ps aux | grep ' + processname
    print('Command: ', command)
    print('2')
    for line in os.popen(command,'r',1):
        print('3')
        fields = line.split()
        print('4')
    print (fields)
    return fields

hosts = ['x.x.x.x']
for h in hosts:
    t = connect_to_devices(h, processname)

0 个答案:

没有答案