-
Notifications
You must be signed in to change notification settings - Fork 0
/
sshcfg.py
76 lines (52 loc) · 1.55 KB
/
sshcfg.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import os
import urlparse
import argh
import paramiko
def get_sshconfig_path():
return os.path.expanduser('~/.ssh/config')
def load_sshconfig():
cfg = paramiko.SSHConfig()
with open(get_sshconfig_path()) as f:
cfg.parse(f)
return [item for item in cfg._config if item['config']]
def write_sshconfig(lines):
with open(get_sshconfig_path(), 'w') as f:
for line in lines:
f.write(line + '\n')
def dump_sshconfig(cfg):
for item in cfg:
yield 'host {}'.format(item['host'][0])
for k, v in item['config'].items():
yield ' {} {}'.format(k, v)
yield ''
def to_uri(config):
if 'user' in config:
yield config['user']
yield '@'
yield config['hostname']
if 'port' in config:
yield ':'
yield config['port']
def parse_uri(uri):
p = urlparse.urlsplit('ssh://' + uri)
return {
"hostname": p.hostname,
"user": p.username,
"port": p.port,
}
def vacumm_dict(d):
return dict((k, v) for k, v in d.items() if v)
def ls():
for item in load_sshconfig():
yield '{}\t{}'.format(item['host'][0], ''.join(to_uri(item['config'])))
def add(name, uri):
cfg = load_sshconfig()
cfg.append({"host": [name], "config": vacumm_dict(parse_uri(uri))})
write_sshconfig(dump_sshconfig(cfg))
def rm(name):
cfg = [item for item in load_sshconfig() if item['host'] != [name]]
write_sshconfig(dump_sshconfig(cfg))
def main():
argh.dispatch_commands([ls, add, rm])
if __name__ == '__main__':
main()