Advertisement
Guest User

Paramiko SFTP example

a guest
Aug 28th, 2016
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.81 KB | None | 0 0
  1. import paramiko.client
  2. import os.path
  3. import sys
  4. import configparser
  5.  
  6. def get_ssh_config():
  7.     config_file = os.path.expanduser("~/.ssh/config")
  8.     if not os.path.exists(config_file):
  9.         return None
  10.     ssh_config = paramiko.SSHConfig()
  11.     ssh_config.parse(config_file)
  12.     return ssh_config
  13.  
  14. def ssh_connect(host, ssh_config=None, known_hosts=None):      
  15.     config = { 'hostname': host, 'compress': True }
  16.     if not ssh_config is None:
  17.         user_config = ssh_config.lookup(host)
  18.         for k in ('hostname', 'username', 'port'):
  19.             if k in user_config:
  20.                 config[k] = user_config[k]
  21.         if 'proxycommand' in user_config:
  22.             config['sock'] = paramiko.ProxyCommand(user_config['proxycommand'])
  23.         if 'identityfile' in user_config:
  24.             config['key_filename'] = user_config['identityfile']
  25.     client = paramiko.client.SSHClient()
  26.     #   client.set_missing_host_key_policy(paramiko.client.AutoAddPolicy())
  27.     client.connect(*config)
  28.     return client
  29.    
  30. def download_querylog(fleet, from_date, to_date):
  31.     config_file = os.path.expanduser('~/.querylog.ini')
  32.     if not os.path.exists(config_file):
  33.         print("No config file ~/.querylog.ini", file=sys.stderr)
  34.         return
  35.     config = configparser.ConfigParser()
  36.     config.read(config_file)
  37.     fleet_section = "fleet." + fleet
  38.     if not config.has_section(fleet_section):
  39.         print("No fleet %s defined in ~/.querylog.ini" % fleet, file=sys.stderr)
  40.         return
  41.    
  42.     fleet_hosts = config.get(fleet_section, "hosts")
  43.     if fleet_hosts is None:
  44.         print("Fleet %s didn't define any host" % fleet)
  45.         return
  46.     fleet_hosts = [ h.strip() for h in fleet_hosts.split(',')]
  47.    
  48.     fleet_package = config.get(fleet_service, "package")
  49.     if package is None:
  50.         print("Fleet %s didn't define a package to retrieve")
  51.        
  52.     ssh_config = get_ssh_config()
  53.     for host in fleet_hosts:
  54.         sftp_client = ssh_connect(host, ssh_config=ssh_config).open_sftp()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement