Created
March 27, 2013 04:30
-
-
Save brent-hoover/5251654 to your computer and use it in GitHub Desktop.
A small utility for listing or searching your SSH config file
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
| #!/usr/bin/env python | |
| import os | |
| import argparse | |
| def convert_to_types(configs): | |
| config_list = list() | |
| for i, x in enumerate(configs): | |
| v = x.strip().split(' ') | |
| if v[0] == '': | |
| pass | |
| else: | |
| #print(v) | |
| if v[0] == 'Host': | |
| config_item = dict(host=v[1]) | |
| if v[0] == 'Hostname': | |
| config_item['hostname'] = v[1] | |
| config_list.append(config_item) | |
| config_dict = dict() | |
| for x in config_list: | |
| config_dict[x['host']] = x['hostname'] | |
| return config_list, config_dict | |
| def main(search=None): | |
| HOME = os.environ['HOME'] | |
| SSH_HOME = os.path.join(HOME, '.ssh') | |
| config_file = os.path.join(SSH_HOME, 'config') | |
| with open(config_file, 'rt') as cf: | |
| configs = cf.readlines() | |
| #calculate longest line for divider | |
| maxlen = 0 | |
| for w in configs: | |
| if len(w) > maxlen: | |
| maxlen = len(w) | |
| config_list, config_dict = convert_to_types(configs) | |
| if search is not None: | |
| search_list = list() | |
| for key, value in config_dict.items(): | |
| if search in key: | |
| search_list.append({'host': key, 'hostname': value}) | |
| if len(search_list) != 0: | |
| for x in search_list: | |
| print('%s -- %s' % (x['host'], x['hostname'])) | |
| else: | |
| print('No matches found') | |
| if search is None: | |
| for key, value in config_dict.items(): | |
| print('host: %s \nhostname: %s' % (key, value)) | |
| print('-' * maxlen) | |
| if __name__ == '__main__': | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("-s", "--search", help="Search your ssh \ | |
| config file for matching host names") | |
| args = parser.parse_args() | |
| main(args.search) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment