在 Python 中使用 Paramiko 执行 SFTP 命令 [英] Executing SFTP commands using Paramiko in Python
问题描述
我想连接到 SFTP 服务器并执行命令,例如 ls
.但我收到一个错误:
I want to connect to SFTP server and execute commands, like ls
. But I'm getting an error:
paramiko.ssh_exception.SSHException:无法打开频道.
paramiko.ssh_exception.SSHException: Unable to open channel.
import paramiko
import pysftp
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('xxxxxxxx', username='xxxxxxx', password='xxxxxxxx', key_filename='xxxxxxxxxxx')
stdin, stdout, stderr = ssh.exec_command('ls')
print stdout.readlines()
ssh.close()
exit()
推荐答案
您似乎相信您的代码执行 SFTP ls
命令.它不是.它尝试执行 ls
shell 命令.您的服务器可能甚至不允许执行 shell 命令,因此会出现错误.
It seem that you believe that your code executes SFTP ls
command. It does not. It tries to execute ls
shell command. Your server probably does not even allow executing shell commands, hence the error.
如果要使用SFTP,需要使用SFTPClient
类 及其方法,如 SFTPClient.listdir
.
If you want to use SFTP, you need to use SFTPClient
class and its methods like SFTPClient.listdir
.
请注意,SFTP 协议没有像 ls
这样的文本命令.SFTP 是一种二进制协议.您知道的命令是常见SFTP客户端的命令——OpenSSH sftp
.OpenSSH sftp
将用户文本命令映射到二进制 SFTP 协议请求.以相同的方式 Paramiko SFTPClient
类将调用映射到其方法到等效的二进制 SFTP 协议请求.
Note that SFTP protocol does not have textual commands like ls
. SFTP is a binary protocol. The commands, that you know, are commands of a common SFTP client – the OpenSSH sftp
. The OpenSSH sftp
maps user text commands to binary SFTP protocol requests. The same way Paramiko SFTPClient
class maps calls to its methods to equivalent binary SFTP protocol requests.
有关更多详细信息,另请参阅我对使用命令行对子系统 SFTP 进行 SSH 调用的回答.
For more details, see also my answer to SSH invocation of a subsystem SFTP using command line.
这篇关于在 Python 中使用 Paramiko 执行 SFTP 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!