I'm trying to teach myself Python to connect to an SFTP server. I tried out this sample code from How do I change directories using 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()
But I get the following (I put the correct host and creds) when it gets to the channel.*
lines.
$ 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.
What does this mean?
The code that you are trying is just wrong. It looks like some random assembly of code snippets generated by ChatGPT. The code is not even using SFTP. It is trying to execute commands in a shell (and even that does incorrectly).
If you want to really use SFTP, use SFTPClient
class.
It has SFTPClient.chdir
method. Though note that SFTP protocol does not have a concept of working directory. So it does not really have anything like cd
. Paramiko just simulates that locally. So the chdir
does not even really talk to the server (except for checking if the target directory exists at all).