ssh.py
Go to the documentation of this file.
00001 #!/usr/bin/env python
00002 # -*- coding: utf-8 -*-
00003 
00004 from contextlib import contextmanager
00005 import os
00006 
00007 import paramiko
00008 
00009 
00010 def connect_ssh(host, username=None, password=None):
00011     return _connect_ssh_context(host, username, password)
00012 
00013 
00014 @contextmanager
00015 def _connect_ssh_context(host, username, password):
00016     try:
00017         ssh = paramiko.SSHClient()
00018         ssh.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
00019         ssh.connect(host, username=username, password=password)
00020         yield ssh
00021     finally:
00022         ssh.close()
00023 
00024 
00025 def get_user_by_hostname(hostname):
00026     ssh_config_file = os.path.expanduser('~/.ssh/config')
00027     if not os.path.exists(ssh_config_file):
00028         return
00029     with open(ssh_config_file) as f:
00030         ssh_config = paramiko.util.parse_ssh_config(f)
00031     for entry in ssh_config._config:
00032         if 'config' not in entry:
00033             continue
00034         config = entry['config']
00035         if config.get('hostname') == hostname:
00036             return config.get('user')


jsk_data
Author(s):
autogenerated on Fri Sep 8 2017 03:39:16