Python:Paramiko在尝试通过SSH执行命令时挂起

时间:2013-05-29 10:32:34

标签: python python-2.7 ssh paramiko

我对Paramiko的工作方式还不熟悉,但我的主要目标是能够使用Python在SSH上运行自动命令。

我有以下代码,我试图运行一个简单的ls命令开始,但由于一些奇怪的原因,代码似乎卡住了,没有产生输出或错误消息。

import sys
import paramiko as pm
sys.stderr = sys.__stderr__
import os

class AllowAllKeys(pm.MissingHostKeyPolicy):
    def missing_host_key(self, client, hostname, key):
        return

HOST = '192.168.31.1'
USER = 'admin'
PASSWORD = 'admin'

client = pm.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(pm.AutoAddPolicy())

client.connect(HOST, username=USER, password=PASSWORD)

channel = client.invoke_shell()
stdin = channel.makefile('wb')
stdout = channel.makefile('rb')

stdin.write('''
ls
exit
''')
print stdout.read()

stdout.close()
stdin.close()

非常感谢任何帮助:)

3 个答案:

答案 0 :(得分:2)

我尝试了你想要的相同路线,也没有太多运气。我之后选择的是paramiko Channel类的send()recv()方法。这是我使用的:

>>> s = paramiko.SSHClient()
>>> s.load_system_host_keys()
>>> s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
>>> s.connect(HOST,USER,PASS)
>>> c = s.invoke_shell()
>>> c.send('ls')
>>> c.recv(1024)
ls
bin     etc     usr     home
proc    var     lib     tmp

答案 1 :(得分:1)

import paramiko ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) target_host = 'x.x.x.x' target_port = 22 target_port = 22 pwd = ':)' un = 'root' ssh.connect( hostname = target_host , username = un, password = pwd ) stdin, stdout, stderr = ssh.exec_command('ls;exit')

答案 2 :(得分:-1)

@ mrpopo,试试这个使用pecpect的代码,

import pexpect
import pxssh
import time
import os

    def tc(ipaddr,password):
        try:
            ss = pexpect.spawn(ipaddr)
            ss.logfile = sys.stdout
                print "SSH connecting"
                print 
        except:
            print "connection refused"
            print
            #sys.exit()

            try:
                ss.expect (':')
                ss.sendline (password +"\n")
                    print "connected"
                    time.sleep(30)
                    ss.expect (">")
                    print "connection established"
                    print

            except:
                    print "Permission denied, please try again."
                        print
                        sys.exit()
            try:
                ss.sendline ('ls\n')
                ss.expect ('>')

    tc("ssh admin@192.168.31.1,admin")