0%

Ubuntu自动选择镜像源

众所周知,Ubuntu 使用官方源执行 apt update 等命令有时候会非常慢。国内有很多镜像服务,但是某些时候偶尔也会抽风,这就导致我们需要日常修改 apt 源。 apt 源是支持 mirror 协议的,从而自动选择可用的一个。

以下即是使用 mirror 协议后的 /etc/apt/sources.list

1
2
3
4
5
6
7
8
9
10
11
###### Ubuntu Main Repos
deb mirror://mirrors.ubuntu.com/mirrors.txt bionic main restricted universe multiverse
deb-src mirror://mirrors.ubuntu.com/mirrors.txt bionic main restricted universe multiverse

###### Ubuntu Update Repos
deb mirror://mirrors.ubuntu.com/mirrors.txt bionic-security main restricted universe multiverse
deb mirror://mirrors.ubuntu.com/mirrors.txt bionic-updates main restricted universe multiverse
deb mirror://mirrors.ubuntu.com/mirrors.txt bionic-backports main restricted universe multiverse
deb-src mirror://mirrors.ubuntu.com/mirrors.txt bionic-security main restricted universe multiverse
deb-src mirror://mirrors.ubuntu.com/mirrors.txt bionic-updates main restricted universe multiverse
deb-src mirror://mirrors.ubuntu.com/mirrors.txt bionic-backports main restricted universe multiverse

当使用 mirror 协议后,执行 apt update 时会首先通过 http 访问 mirrors.ubuntu.com/mirrors.txt 文本;文本内容实际上就是本地当前可用的镜像源列表,如下所示

1
2
3
4
5
6
7
8
9
10
11
12
13
http://mirrors.ustc.edu.cn/ubuntu/
http://mirrors.huaweicloud.com/repository/ubuntu/
http://mirrors.yun-idc.com/ubuntu/
http://mirrors.tuna.tsinghua.edu.cn/ubuntu/
http://mirrors.nju.edu.cn/ubuntu/
http://mirror.lzu.edu.cn/ubuntu/
http://mirrors.sohu.com/ubuntu/
http://mirrors.cn99.com/ubuntu/
http://ftp.sjtu.edu.cn/ubuntu/
http://mirrors.cqu.edu.cn/ubuntu/
http://mirrors.aliyun.com/ubuntu/
http://mirrors.dgut.edu.cn/ubuntu/
http://archive.ubuntu.com/ubuntu/

得到列表后 apt 会自动选择一个网速快的作为镜像源。

另外一种使用 mirror 协议的方法是:

1
$ perl -pi -e 's@^\s*(deb(\-src)?)\s+http://us.archive.*?\s+@\1 mirror://mirrors.ubuntu.com/mirrors.txt @g' /etc/apt/sources.list

在命令行执行完上述命令后,/etc/apt/sources.list变为如下,说明其选择了阿里云作为源。

1
2
3
4
5
6
7
8
9
deb http://mirrors.aliyun.com/ubuntu/ xenial main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ xenial-security main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ xenial-updates main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ xenial-proposed main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ xenial-backports main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ xenial main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ xenial-security main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ xenial-updates main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ xenial-proposed main restricted universe multiverse