Skip to content

Instantly share code, notes, and snippets.

@wuriyanto48
Created November 25, 2021 02:54
Show Gist options
  • Save wuriyanto48/9e775e5cf575962c798dc7d9d0ba23c9 to your computer and use it in GitHub Desktop.
Save wuriyanto48/9e775e5cf575962c798dc7d9d0ba23c9 to your computer and use it in GitHub Desktop.
Download file with Python and Paramiko SSH Client

You need to install paramiko package

$ pip install paramiko
import paramiko
import logging
import os
from pathlib import Path
from stat import S_ISREG
logger = paramiko.util.logging.getLogger()
logger.setLevel(logging.WARN)
# Open a transport
host, port = '1.1.1.1', 22
transport = paramiko.Transport((host,port))
# Auth
username, password = 'admin','12345'
transport.connect(None,username,password)
sftp = paramiko.SFTPClient.from_transport(transport)
# Download
remote_base_dir = '/home/foldername/'
for entry in sftp.listdir_attr(remote_base_dir):
mode = entry.st_mode
if S_ISREG(mode):
if entry.filename.endswith('.csv'):
csv_file = entry.filename
remote_full_path = os.path.join(remote_base_dir, csv_file)
if Path(csv_file).exists():
print(f'file already exist {csv_file}')
else:
print(f'download {csv_file}')
sftp.get(remote_full_path,csv_file)
# Close
if sftp: sftp.close()
if transport: transport.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment