Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- import getpass
- from pathlib import Path
- from argparse import ArgumentParser
- from paramiko.client import (
- SSHClient,
- MissingHostKeyPolicy,
- )
- from paramiko.ssh_exception import AuthenticationException
- def ask_password():
- return getpass.getpass('Please enter password: ')
- def connect(
- hostname,
- username=None,
- password=None,
- port=22,
- key=False,
- **kwargs,
- ):
- client = SSHClient()
- client.set_missing_host_key_policy(MissingHostKeyPolicy)
- if key:
- # use only private keys for login,
- # if it was explicit requested
- client.load_system_host_keys()
- client.connect(hostname, port=port, username=username, password=password)
- return client
- def command_executor(client, script):
- with script.open() as fd:
- for line in fd:
- print(f'Executing command: {line.rstrip()}')
- stdin, stdout, stderr = client.exec_command(line)
- stdout, stderr = stdout.read().decode(), stderr.read().decode()
- print(stdout, end='')
- def main(**kwargs):
- if not kwargs['key']:
- kwargs['password'] = ask_password()
- client = connect(**kwargs)
- command_executor(client, kwargs['script'])
- client.close()
- if __name__ == '__main__':
- parser = ArgumentParser()
- parser.add_argument('hostname', help='Hostname of the host you want to connect')
- parser.add_argument('username', type=str, help='User for login')
- parser.add_argument('script', type=Path, help='Path to script file, which should executed')
- parser.add_argument('--port', type=int, default=22, help='Port of SSH service')
- parser.add_argument('--key', action='store_true', help='Use only private key for login')
- args = parser.parse_args()
- if not args.script.exists():
- print(f'The script {args.script} does not exist')
- sys.exit(1)
- try:
- main(**vars(args))
- except AuthenticationException:
- print('Problem with authentication', file=sys.stderr)
- sys.exit(2)
Add Comment
Please, Sign In to add comment