"""
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