forked from jblakeman/apt-select
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapt-select.py
More file actions
executable file
·179 lines (154 loc) · 4.46 KB
/
apt-select.py
File metadata and controls
executable file
·179 lines (154 loc) · 4.46 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
#!/usr/bin/env python
from sys import exit
from os import getcwd
from re import findall, search
from subprocess import check_output, CalledProcessError
try:
from urllib.request import urlopen, HTTPError
except ImportError:
from urllib2 import urlopen, HTTPError
from mirrors import RoundTrip, Data
def notUbuntu():
print("Not an Ubuntu OS")
exit(1)
try:
release = check_output("lsb_release -ics 2>/dev/null", shell=True)
except CalledProcessError:
notUbuntu()
else:
release = [s.strip() for s in release.decode().split()]
hardware = check_output("uname -m", shell=True).strip().decode()
if release[0] == 'Debian':
print("Debian is not currently supported")
exit(1)
elif release[0] != 'Ubuntu':
notUbuntu()
codename = release[1][0].upper() + release[1][1:]
mirror_list = "http://mirrors.ubuntu.com/mirrors.txt"
try:
archives = urlopen(mirror_list)
except IOError as err:
print(("Could not connect to '%s'.\nCheck network connection\n"
"%s" % (mirror_list, err)))
exit(1)
print("Got list of mirrors")
archives = archives.read().decode()
urls = findall(r'http://([\w|\.|\-]+)/', archives)
n = 0
avg_rtts = {}
for url in urls:
ping = RoundTrip(url)
print("Connecting to %s" % url)
avg = ping.avgRTT()
if avg:
avg_rtts.update({url:avg})
n += 1
print("Tested %d mirrors" % n)
if hardware == 'x86_64':
hardware = 'amd64'
else:
hardware = 'i386'
top_num = 5
ranks = sorted(avg_rtts, key=avg_rtts.__getitem__)
info = []
print("Retrieving status information")
for rank in ranks:
d = Data(rank, codename, hardware)
data = d.getInfo()
if data:
info.append(data)
if len(info) == top_num:
break
print("\nTop %d mirrors:\n" % top_num)
for i, j in enumerate(info):
print("%d. %s\n\tLatency: %d ms\n\tStatus: %s\n\tBandwidth: %s\n" %
(i + 1, j[0], avg_rtts[j[0]], j[1][0], j[1][1]))
directory = '/etc/apt/'
apt_file = 'sources.list'
try:
input = raw_input
except NameError:
pass
def ask(query):
global input
answer = input(query)
return answer
def yesOrNo(*args):
y = 'yes'
n = 'no'
options = "Please enter %s or %s: " % (y,n)
while True:
answer = ask(args[0])
if answer == y:
if args[1]:
genFile()
break
elif answer == n:
return
else:
query = options
def genFile():
s = "Please select a mirror number from the list (1 - %d) " % top_num
key = ask(s)
while True:
match = search(r'[1-5]', key)
if match and (len(key) == 1):
key = int(key)
break
else:
print("Not a valid number")
key = ask(s)
key = key - 1
global info
mirror = info[key][0]
global archives
for m in archives.splitlines():
if mirror in m:
mirror = m
break
found = None
field1 = ('deb', 'deb-src')
h = 'http://'
with open('%s' % directory + apt_file, 'r') as f:
lines = f.readlines()
for line in lines:
arr = line.split()
if not found:
if (arr and (arr[0] in field1) and
(h == arr[1][:7]) and
(release[1] in arr[2:])):
repo = [arr[1]]
found = True
continue
else:
if (arr and (arr[0] in field1) and
(h in arr[1]) and
(arr[2] == '%s-security' % (release[1]))):
repo += [arr[1]]
break
else:
print("Error finding current repositories")
exit(1)
lines = ''.join(lines)
for r in repo:
lines = lines.replace(r, mirror)
if getcwd() == directory[0:-1]:
global options
query = (
"'%(dir)s' is the current directory.\n"
"Generating a new '%(apt)s' file will "
"overwrite the current file.\n"
"You should copy or backup '%(apt)s' before replacing it.\n"
"Continue?\n[yes|no] " %
{'dir': directory, 'apt': apt_file}
)
yesOrNo(query)
with open(apt_file, 'w') as f:
try:
f.write(lines)
except IOError as err:
print("Unable to write new '%s' file\n%s" % (apt_file, err))
exit(1)
query = "Generate new '%s' file?\n[yes|no] " % apt_file
yesOrNo(query, True)
exit(0)