forked from letharion/letharion-dot-files
-
Notifications
You must be signed in to change notification settings - Fork 1
/
update-ssh-keys.py
executable file
·76 lines (62 loc) · 2.07 KB
/
update-ssh-keys.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
#!/usr/bin/env python
# coding=utf-8
""" update-ssh-keys.py: Downloads the public ssh-keys from api.github.com for the selected user and inserts them into .ssh/authorized_keys. """
__author__ = "Jonathan stamp Grimmtjärn"
__license__ = "MIT"
try:
# For Python 3.0 and later
from urllib.request import urlopen
except ImportError:
# Fall back to Python 2's urllib2
from urllib2 import urlopen
import os, json
# Open the ssh authorized keys file
authorized_keys = open(os.path.join(os.path.expanduser('~'),'.ssh/authorized_keys'), 'a+')
def insertOrUpdateKey(key):
authorized_keys.seek(0);
# Check if it already exists
for line in authorized_keys:
try:
# Already there, exit
line.index(key);
return
except ValueError:
# Not found, check next line
continue;
# Add the key
authorized_keys.write(key);
# Download keys and go thru them
response = urlopen("https://api.github.com/users/stamp/keys")
data = json.loads(str(response.read()))
keys = []
for item in data:
try:
item["key"].index("ssh-")
key = item["key"] + " " + str(item["id"])+ "@github\r\n"
insertOrUpdateKey(key)
keys.append(key)
except ValueError:
continue;
# Remove all old keys
authorized_keys.seek(0);
old_file = authorized_keys.readlines();
authorized_keys.close();
authorized_keys = open(os.path.join(os.path.expanduser('~'),'.ssh/authorized_keys'), 'w+')
authorized_keys.seek(0);
for line in old_file:
try:
# Check that the key is from github
line.index("@github");
try:
keys.index(line);
#Key found, everything is good
authorized_keys.write(line);
except ValueError:
#Not found, remove the key
authorized_keys.write("# " + line);
except ValueError:
# Skip all lines that arent from github
authorized_keys.write(line);
continue;
# Make sure the file permissions is correct
os.chmod(os.path.join(os.path.expanduser('~'),'.ssh/authorized_keys'), 0o600);