SHARE
TWEET

ssh test

DeaD_EyE Jul 26th, 2019 88 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import getpass
  2. from argparse import ArgumentParser
  3. from pathlib import Path
  4. from paramiko.client import (
  5.     SSHClient,
  6.     MissingHostKeyPolicy,
  7. )
  8.  
  9.  
  10. def ask_password():
  11.     return getpass.getpass('Please enter password: ')
  12.  
  13.  
  14. def connect(
  15.     hostname,
  16.     username=None,
  17.     password=None,
  18.     pkey=None,
  19.     passphrase=None,
  20.     port=22,
  21.     **kwargs,
  22.     ):    
  23.     client = SSHClient()
  24.     client.set_missing_host_key_policy(MissingHostKeyPolicy)
  25.     client.load_system_host_keys()
  26.     client.connect(
  27.         hostname, port=port, username=username, password=password,
  28.         pkey=pkey, passphrase=passphrase,
  29.         )
  30.     return client
  31.  
  32.  
  33. def main(**kwargs):
  34.     if not kwargs['key']:
  35.         kwargs['password'] = ask_password()
  36.     client = connect(**kwargs)
  37.     # here the commands you want to execute
  38.     stdin, stdout, stderr = client.exec_command('ls -l')
  39.     # stdin, stdout, stderr are FileLike objects opened in bytes mode
  40.     print(stdout.read().decode(), stderr.read().decode())
  41.     client.close()
  42.  
  43.  
  44. if __name__ == '__main__':
  45.     parser = ArgumentParser()
  46.     parser.add_argument('hostname', help='Hostname of the host you want to connect')
  47.     parser.add_argument('username', type=str, help='User for login')
  48.     parser.add_argument('--port', type=int, default=22, help='Port of SSH service')
  49.     parser.add_argument('--key', action='store_true', help='Use only private key for login')
  50.     args = parser.parse_args()
  51.     main(**vars(args))
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top