DeaD_EyE

ssh_test_2

Jul 26th, 2019
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.04 KB | None | 0 0
  1. import sys
  2. import getpass
  3. from pathlib import Path
  4. from argparse import ArgumentParser
  5. from paramiko.client import (
  6.     SSHClient,
  7.     MissingHostKeyPolicy,
  8. )
  9. from paramiko.ssh_exception import AuthenticationException
  10.  
  11.  
  12. def ask_password():
  13.     return getpass.getpass('Please enter password: ')
  14.  
  15.  
  16. def connect(
  17.     hostname,
  18.     username=None,
  19.     password=None,
  20.     port=22,
  21.     key=False,
  22.     **kwargs,
  23.     ):    
  24.     client = SSHClient()
  25.     client.set_missing_host_key_policy(MissingHostKeyPolicy)
  26.     if key:
  27.         # use only private keys for login,
  28.         # if it was explicit requested
  29.         client.load_system_host_keys()
  30.     client.connect(hostname, port=port, username=username, password=password)
  31.     return client
  32.  
  33.  
  34. def command_executor(client, script):
  35.     with script.open() as fd:
  36.         for line in fd:
  37.             print(f'Executing command: {line.rstrip()}')
  38.             stdin, stdout, stderr = client.exec_command(line)
  39.             stdout, stderr = stdout.read().decode(), stderr.read().decode()
  40.             print(stdout, end='')
  41.  
  42.  
  43. def main(**kwargs):
  44.     if not kwargs['key']:
  45.         kwargs['password'] = ask_password()
  46.     client = connect(**kwargs)
  47.     command_executor(client, kwargs['script'])
  48.     client.close()
  49.  
  50.  
  51. if __name__ == '__main__':
  52.     parser = ArgumentParser()
  53.     parser.add_argument('hostname', help='Hostname of the host you want to connect')
  54.     parser.add_argument('username', type=str, help='User for login')
  55.     parser.add_argument('script', type=Path, help='Path to script file, which should executed')
  56.     parser.add_argument('--port', type=int, default=22, help='Port of SSH service')
  57.     parser.add_argument('--key', action='store_true', help='Use only private key for login')
  58.     args = parser.parse_args()
  59.     if not args.script.exists():
  60.         print(f'The script {args.script} does not exist')
  61.         sys.exit(1)
  62.     try:
  63.         main(**vars(args))
  64.     except AuthenticationException:
  65.         print('Problem with authentication', file=sys.stderr)
  66.         sys.exit(2)
Add Comment
Please, Sign In to add comment