为什么使用Paramiko会出现这个异常?

问题描述 投票:0回答:1

我正在尝试自学 Python 连接到 SFTP 服务器。我尝试了以下示例代码:如何使用 Paramiko 更改目录?

import paramiko

# Create an SSH client
ssh = paramiko.SSHClient()

# Connect to the remote server
ssh.connect('hostname', username='user', password='pass')

# Open a new channel
channel = ssh.get_transport().open_session()

# Start a shell on the channel
channel.get_pty()
channel.invoke_shell()

# Execute the `cd` command to change to the `/tmp` directory
channel.exec_command('cd /tmp')

# Close the channel
channel.close()

# Close the SSH client
ssh.close()

但是当到达

channel.*
行时,我得到以下信息(我输入了正确的主机和凭据)。

$ python3 -V
Python 3.8.2

$ python3 sftp.py 
Traceback (most recent call last):
  File "sftp.py", line 27, in <module>
    channel.get_pty()
  File "/Users/kmhait/Library/Python/3.8/lib/python/site-packages/paramiko/channel.py", line 70, in _check
    return func(self, *args, **kwds)
  File "/Users/kmhait/Library/Python/3.8/lib/python/site-packages/paramiko/channel.py", line 201, in get_pty
    self._wait_for_event()
  File "/Users/kmhait/Library/Python/3.8/lib/python/site-packages/paramiko/channel.py", line 1224, in _wait_for_event
    raise e
paramiko.ssh_exception.SSHException: Channel closed.

这是什么意思?

python python-3.x paramiko
1个回答
0
投票

您正在尝试的代码是错误的。它看起来像是由 ChatGPT 生成的代码片段的随机组合。该代码甚至没有使用 SFTP。它试图在 shell 中执行命令(即使这样做也不正确)。

如果你想真正使用SFTP,请使用

SFTPClient

它有

SFTPClient.chdir
方法。但请注意,SFTP 协议没有工作目录的概念。所以它实际上并没有像
cd
这样的东西。 Paramiko 只是在本地模拟。因此
chdir
甚至没有真正与服务器对话(除了检查目标目录是否存在)。

© www.soinside.com 2019 - 2024. All rights reserved.