1

我对 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()

任何帮助将非常感激 :)

4

3 回答 3

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
于 2013-05-29T15:02:35.540 回答
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')

于 2016-03-14T07:16:38.450 回答
-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")
于 2013-05-31T06:36:41.670 回答