使用Python脚本来给ubuntu换源

47 篇文章 1 订阅

## 系统没有python的情况(如docker镜像) [Updated_at: 2021-02-06]

# 需先切换到root用户
# sudo su
cd /etc/apt  # cd到源列表所在目录
[[ -f sources.list.origin ]] || cp sources.list sources.list.origin  # 备份原文件
sed -i 's/^\(deb\|deb-src\) \([^ ]*\) \(.*\)/\1 http:\/\/repo.huaweicloud.com\/ubuntu\/ \3/' sources.list  # 替换为华为源

## 系统有python(python2或python3都可以)的情况

一行命令搞定(换华为源华为开源镜像站_软件开发服务_华为云)(ubuntu16/ubuntu18/ubuntu20都已试过可行):

export mirror_target="http://repo.huaweicloud.com" && export source_fname="/etc/apt/sources.list" && ((sudo which python>>/dev/null&&export python=python) || (sudo which python3>>/dev/null&&export python=python3)||python) && export switch_apt_sources="target='$mirror_target';fname='$source_fname';import re;fp=open(fname, 'r+');s=fp.read();skip={};target not in s or skip.setdefault('a', 'Sources of \`{}\` already set to \`{}\`\nSkip.'.format(fname, target));ss=re.sub(r'https*://[^/]+/', target+'/', s);skip or fp.seek(0);skip or fp.truncate();skip or fp.write(ss);fp.close();import os;bak=fname+'.bak';bak_exists=os.path.exists(bak);os.system('sudo touch '+bak);fp2=open(bak, 'r+');bak_exists or fp2.write(s);fp2.close();tip=skip.get('a', 'Changed sources of \`{}\` to \`{}\`\nDone.'.format(fname, target));print('\n'+tip)" && sudo $python -c "$switch_apt_sources"  #echo "sudo $python -c \"$switch_apt_sources\""

curl https://gitee.com/waketzheng/carstino/raw/master/change_ubuntu_mirror_sources.py|sudo python   # 支持Python2.7+

该命令做了这些事情:

1. 读取镜像列表文件/etc/apt/sources.list的内容,判断文件中是否包含mirror_target,若已包含则什么也不做,否则进行下一步

2. 把镜像列表文件备份为/etc/apt/sources.list.bak (如果备份文件已存在,则跳过该步骤)

3. 把/etc/apt/sources.list中,所有http://xxx/的内容替换为mirror_target,最终的文件内容见文章底部

PS: 命令大致相当于如下Python代码

#!/usr/bin/env python
# -*- coding: utf-8 -*- 
import os
import re
import sys
# Note: Python2.7+ is required

SOURCES = {
    "huawei": "http://repo.huaweicloud.com",
    "163": "https://mirrors.163.com",
    "aliyun": "https://mirrors.aliyun.com",
    "qinghua": "https://mirrors.tuna.tsinghua.edu.cn",   
}
DEFAULT = SOURCES["huawei"]
SOURCE_FILE = "/etc/apt/sources.list"


def parse_argv(args):
    for arg in args:
        if arg.startswith("http"):
            return arg.rstrip("/")
        for k in SOURCES:
            if k in arg:
                return SOURCES[k]
    return DEFAULT


def main(fname=SOURCE_FILE):
    target = parse_argv(sys.argv[1:])
    with open(fname) as fp:
        s = fp.read()
    if target in s:
        msg = "Sources of `{}` already set to `{}`\nSkip."
        print(msg.format(fname, target))
        return

    ss = re.sub(r"https?://[^/]+/", target + "/", s)
    try:
        with open(fname, "w") as fp:
            fp.write(ss)
    except IOError as e:
        print(e)
        tip = "\nYou may need to run as root:\n\n  sudo python {}\n"
        print(tip.format(sys.argv[0]))
        return

    bak = fname + ".bak"
    if not os.path.exists(bak):
        with open(bak, "w") as fp:
            fp.write(s)
            print("Backup old sources file to `{}`".format(bak))

    print("Changed sources of `{}` to `{}`\nDone.".format(fname, target))


if __name__ == "__main__":
    main()

------------------------------------

清华源的话,用这个:

export mirror_target="https://mirrors.tuna.tsinghua.edu.cn" && export source_fname="/etc/apt/sources.list" && ((sudo which python>>/dev/null&&export python=python) || (sudo which python3>>/dev/null&&export python=python3)||python) && export switch_apt_sources="target='$mirror_target';fname='$source_fname';import re;fp=open(fname, 'r+');s=fp.read();skip={};target not in s or skip.setdefault('a', 'Sources of \`{}\` already set to \`{}\`\nSkip.'.format(fname, target));ss=re.sub(r'https*://[^/]+/', target+'/', s);skip or fp.seek(0);skip or fp.truncate();skip or fp.write(ss);fp.close();import os;bak=fname+'.bak';bak_exists=os.path.exists(bak);os.system('sudo touch '+bak);fp2=open(bak, 'r+');bak_exists or fp2.write(s);fp2.close();tip=skip.get('a', 'Changed sources of \`{}\` to \`{}\`\nDone.'.format(fname, target));print('\n'+tip)" && sudo $python -c "$switch_apt_sources"  #echo "sudo $python -c \"$switch_apt_sources\""

PS:

国内源的url可参照ubuntu官网对国内源的介绍模板:18.04source - Ubuntu中文

国内常用的几大源有(摘自:apt-get 软件源文件格式以及ubuntu 18.04更换阿里源_jmhIcoding-CSDN博客_ubuntu18.04换源):

Ubuntu 官方中國(目前是阿里云)http://cn.archive.ubuntu.com/ubuntu/
網易(廣東廣州電信/聯通千兆雙線接入)http://mirrors.163.com/ubuntu/
搜狐(山東聯通千兆接入)http://mirrors.sohu.com/ubuntu/
阿里云(北京萬網/浙江杭州) http://mirrors.aliyun.com/ubuntu/
開源鏡像文件搜索 http://ubuntu.mirrors.org.cn/

教育網专线:

中科大 LUG(合肥,電信/聯通/移動/教育網自動分流,同時也是 Deepin 官方)
https://mirrors.ustc.edu.cn/ubuntu/ (v4/v6) http://mirrors4.ustc.edu.cn/ubuntu/ (v4) http://mirrors6.ustc.edu.cn/ubuntu/ (v6)
中科院 OpenCAS
http://mirrors.opencas.cn/ubuntu/
清華 TUNA(教育網核心節點百兆接入,已計畫提高到千兆)
http://mirrors.tuna.tsinghua.edu.cn/ubuntu/ (v4/v6) http://mirrors.4.tuna.tsinghua.edu.cn/ubuntu/ (v4) http://mirrors.6.tuna.tsinghua.edu.cn/ubuntu/ (v6)

Ubuntu18(清华源下载的vagrant镜像版)换源后的/etc/apt/sources.list

## Note, this file is written by cloud-init on first boot of an instance
## modifications made here will not survive a re-bundle.
## if you wish to make changes you can:
## a.) add 'apt_preserve_sources_list: true' to /etc/cloud/cloud.cfg
##     or do the same in user-data
## b.) add sources in /etc/apt/sources.list.d
## c.) make changes to template file /etc/cloud/templates/sources.list.tmpl

# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
deb https://mirrors.163.com/ubuntu bionic main restricted
# deb-src https://mirrors.163.com/ubuntu bionic main restricted

## Major bug fix updates produced after the final release of the
## distribution.
deb https://mirrors.163.com/ubuntu bionic-updates main restricted
# deb-src https://mirrors.163.com/ubuntu bionic-updates main restricted

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team. Also, please note that software in universe WILL NOT receive any
## review or updates from the Ubuntu security team.
deb https://mirrors.163.com/ubuntu bionic universe
# deb-src https://mirrors.163.com/ubuntu bionic universe
deb https://mirrors.163.com/ubuntu bionic-updates universe
# deb-src https://mirrors.163.com/ubuntu bionic-updates universe

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
deb https://mirrors.163.com/ubuntu bionic multiverse
# deb-src https://mirrors.163.com/ubuntu bionic multiverse
deb https://mirrors.163.com/ubuntu bionic-updates multiverse
# deb-src https://mirrors.163.com/ubuntu bionic-updates multiverse

## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
deb https://mirrors.163.com/ubuntu bionic-backports main restricted universe multiverse
# deb-src https://mirrors.163.com/ubuntu bionic-backports main restricted universe multiverse

## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
# deb http://archive.canonical.com/ubuntu bionic partner
# deb-src http://archive.canonical.com/ubuntu bionic partner

deb https://mirrors.163.com/ubuntu bionic-security main restricted
# deb-src https://mirrors.163.com/ubuntu bionic-security main restricted
deb https://mirrors.163.com/ubuntu bionic-security universe
# deb-src https://mirrors.163.com/ubuntu bionic-security universe
deb https://mirrors.163.com/ubuntu bionic-security multiverse
# deb-src https://mirrors.163.com/ubuntu bionic-security multiverse

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值