【问题标题】:Command execution using paramiko使用 paramiko 执行命令
【发布时间】:2014-04-02 01:41:29
【问题描述】:

我正在编写一个 python 脚本,它接受在远程 linux 上执行的命令。我上网并找到了帕拉米科。我开发了一个脚本,如果像 'who', 'ps', 'ls' 这样的命令被执行,它可以正常工作。但同一脚本未能执行 'top' 和 'ping' 命令。 请帮我解决这个问题。

import paramiko
import sys

class sampleParamiko:
    ssh = ""
    def __init__(self, host_ip, uname, passwd):
        try:
            self.ssh = paramiko.SSHClient()
            self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            self.ssh.connect(host_ip, username=uname, password=passwd)
            #print "In init function"
        except (paramiko.BadHostKeyException, paramiko.AuthenticationException, paramiko.SSHException) as e:
            print str(e)
            sys.exit(-1)

    def ececuteCmd(self,cmd):
        try:
            stdin, stdout, stderr = self.ssh.exec_command(cmd)
            out_put = stdout.readlines()
            for item in out_put:
                print item,
        except paramiko.SSHException as e:
            print str(e)
            sys.exit(-1)
host_ip = "10.27.207.62"
uname = "root"
password = "linux"
cmd = str(raw_input("Enter the command to execute in the host machine: "))
conn_obj = sampleParamiko(host_ip, uname, password)
conn_obj.ececuteCmd(cmd)

【问题讨论】:

    标签: python paramiko


    【解决方案1】:

    您可能想看看paramiko.SSHClientinvoke_shell() 方法。

    根据您的代码,您可以这样做:

    import paramiko
    import sys
    
    class sampleParamiko:
        ssh = ""
        def __init__(self, host_ip, uname, passwd):
            try:
                self.ssh = paramiko.SSHClient()
                self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                self.ssh.connect(host_ip, username=uname, password=passwd)
                #print "In init function"
            except (paramiko.BadHostKeyException, paramiko.AuthenticationException,     paramiko.SSHException) as e:
                print str(e)
                sys.exit(-1)
    
        def ececuteCmd(self,cmd):
            try:
                channel = self.ssh.invoke_shell()
                timeout = 60 # timeout is in seconds
                channel.settimeout(timeout)
                newline        = '\r'
                line_buffer    = ''
                channel_buffer = ''
                channel.send(cmd + ' ; exit ' + newline)
                while True:
                    channel_buffer = channel.recv(1).decode('UTF-8')
                    if len(channel_buffer) == 0:
                        break 
                    channel_buffer  = channel_buffer.replace('\r', '')
                    if channel_buffer != '\n':
                        line_buffer += channel_buffer
                    else:
                        print line_buffer
                        line_buffer   = ''
            except paramiko.SSHException as e:
                print str(e)
                sys.exit(-1)
    host_ip = "10.27.207.62"
    uname = "root"
    password = "linux"
    cmd = str(raw_input("Enter the command to execute in the host machine: "))
    conn_obj = sampleParamiko(host_ip, uname, password)
    conn_obj.ececuteCmd(cmd)
    

    输出是:

    Jean@MyDesktop:~$ ./test_paramiko.py 
    Enter the command to execute in the host machine: ping -c2 127.0.0.1
    ping -c2 127.0.0.1 ; exit 
    [root@myserver ~]# ping -c2 127.0.0.1 ; exit 
    PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
    64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.032 ms
    64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.043 ms
    
    --- 127.0.0.1 ping statistics ---
    2 packets transmitted, 2 received, 0% packet loss, time 999ms
    rtt min/avg/max/mdev = 0.032/0.037/0.043/0.008 ms
    logout
    

    但是您不能以交互方式发送命令。因此,如果您只是ping 127.0.0.1,它将永远持续下去,直到您 [CTRL]+[C] 或杀死您的 python 脚本。 top 也一样。

    如果您想要一个交互式 shell,请查看 paramiko 附带的示例脚本。尤其是demos/demo.pydemos/interactive.py

    【讨论】:

      最近更新 更多