Created
October 8, 2015 04:06
-
-
Save henocdz/10ada609c2394ec0b97a to your computer and use it in GitHub Desktop.
Connect to a given hostname in a given SSH config file (Invoke + Paramiko)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| Used with Invoke to automate tasks | |
| Connect to a given hostname in a given SSH config file | |
| Inpired by: https://gist.github.com/acdha/6064215 | |
| """ | |
| from invoke import task, run | |
| from paramiko import SSHConfig, SSHClient, SSHException, AutoAddPolicy | |
| import logging | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger('ParamikoInvoke') | |
| def connect_to_server(server='some_hostname'): | |
| """ Returns a paramiko.SSHClient connected to specific server """ | |
| # Open configuration file | |
| with open('config') as config_file: | |
| ssh_config = SSHConfig() | |
| ssh_config.parse(config_file) | |
| server_config = ssh_config.lookup(server) | |
| user, hostname, port, keys = ( | |
| server_config.get('user'), | |
| server_config.get('hostname'), | |
| server_config.get('port'), | |
| server_config.get('identityfile') | |
| ) | |
| if not user or not hostname or not port or not keys: | |
| logger.error('Server name not found inn config file') | |
| return exit() | |
| try: | |
| port = int(port) | |
| except ValueError as e: | |
| logger.critical('Invalid port') | |
| exit() | |
| ssh_client = SSHClient() | |
| # Auto add to unknown hosts | |
| ssh_client.set_missing_host_key_policy(AutoAddPolicy()) | |
| try: | |
| ssh_client.connect( | |
| hostname, port, | |
| username=user, key_filename=keys | |
| ) | |
| except SSHException as e: | |
| logger.critical('Could not connect to SSH Server') | |
| logger.error(e) | |
| exit() | |
| return ssh_client |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment