如何在Paramiko的一个会话中执行多个命令?(Python)

2024-05-15 21:17:46 发布

您现在位置:Python中文网/ 问答频道 /正文

def exec_command(self, command, bufsize=-1):
    #print "Executing Command: "+command
    chan = self._transport.open_session()
    chan.exec_command(command)
    stdin = chan.makefile('wb', bufsize)
    stdout = chan.makefile('rb', bufsize)
    stderr = chan.makefile_stderr('rb', bufsize)
    return stdin, stdout, stderr

在paramiko中执行命令时,它总是在运行exec_命令时重置会话。 我希望能够执行sudo或su,并且在运行另一个exec_命令时仍然拥有这些特权。 另一个例子是尝试执行exec_命令(“cd/”),然后再次运行exec_命令并将其放在根目录中。我知道您可以执行exec_command(“cd/;ls-l”)之类的操作,但我需要在单独的函数调用中执行。


Tags: 命令selfdefstderrstdinstdoutcdmakefile
3条回答

严格来说,你不能。根据ssh规范:

A session is a remote execution of a program. The program may be a shell, an application, a system command, or some built-in subsystem.

这意味着,一旦命令执行完毕,会话就结束了。不能在一个会话中执行多个命令。但是,您可以做的是启动一个远程shell(=一个命令),并通过stdin等与该shell交互。。。(考虑执行python脚本,而不是运行交互式解释器)

尝试创建由\n字符分隔的命令字符串。这对我有效。 为了。e、 g.ssh.exec_command("command_1 \n command_2 \n command_3")

非交互式用例

这是一个非交互式示例。。。它发送cd tmpls,然后exit

import sys
sys.stderr = open('/dev/null')       # Silence silly warnings from paramiko
import paramiko as pm
sys.stderr = sys.__stderr__
import os

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

HOST = '127.0.0.1'
USER = ''
PASSWORD = ''

client = pm.SSHClient()
client.load_system_host_keys()
client.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
client.set_missing_host_key_policy(AllowAllKeys())
client.connect(HOST, username=USER, password=PASSWORD)

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

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

stdout.close()
stdin.close()
client.close()

交互式用例
如果你有一个交互式的用例,这个答案不会有帮助。。。我个人会使用pexpectexscript进行交互会话。

相关问题 更多 >