To transfer files using your established Paramiko SSH connection, you can use SFTP (SSH File Transfer Protocol). Here's how to do it:
# Open an SFTP session from the SSH connection
sftp = ssh.open_sftp()
try:
# Download a file from remote to local
remote_path = '/path/to/remote/file.txt'
local_path = '/path/to/local/file.txt'
sftp.get(remote_path, local_path)
print(f"Downloaded {remote_path} to {local_path}")
# Upload a file from local to remote
local_file = '/path/to/local/upload.txt'
remote_file = '/path/to/remote/upload.txt'
sftp.put(local_file, remote_file)
print(f"Uploaded {local_file} to {remote_file}")
finally:
# Close the SFTP session
sftp.close()
Here are some additional useful SFTP operations:
# List files in a directory
files = sftp.listdir('/remote/directory')
for file in files:
print(file)
# Get file information
file_stat = sftp.stat('/remote/file.txt')
print(f"File size: {file_stat.st_size} bytes")
# Create a directory
sftp.mkdir('/remote/new_directory')
# Remove a file
sftp.remove('/remote/file_to_delete.txt')
# Rename/move a file
sftp.rename('/remote/old_name.txt', '/remote/new_name.txt')
You can also add progress callbacks for large file transfers:
def progress_callback(transferred, total):
print(f"Transferred: {transferred}/{total} bytes ({100.0 * transferred / total:.1f}%)")
# Download with progress
sftp.get(remote_path, local_path, callback=progress_callback)
# Upload with progress
sftp.put(local_file, remote_file, callback=progress_callback)
Remember to handle exceptions appropriately and close both the SFTP and SSH connections when you're done:
try:
sftp = ssh.open_sftp()
# ... file operations ...
except IOError as e:
print(f"File operation failed: {e}")
finally:
if 'sftp' in locals():
sftp.close()
ssh.close()