AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / ubuntu / 问题 / 700860
Accepted
A.B.
A.B.
Asked: 2015-11-22 09:43:03 +0800 CST2015-11-22 09:43:03 +0800 CST 2015-11-22 09:43:03 +0800 CST

以简单的终端方式添加和删除更新频道

  • 772

我知道在 Ubuntu 中有一个 GUISoftware & Updates来启用更新通道

  • 更新
  • 建议的
  • 向后移植
  • 安全

如此屏幕截图所示:

在此处输入图像描述

我正在寻找一种简单的方法在终端内使用诸如以下的命令来执行此操作

sudo apt-add-update enable updates
sudo apt-add-update enable proposed
sudo apt-add-update enable backports
sudo apt-add-update enable security

sudo apt-add-update disable updates
sudo apt-add-update disable proposed
sudo apt-add-update disable backports
sudo apt-add-update disable security

还有一件事

sudo apt-add-update enable default

sudo apt-add-update disable default

一些例子可以更好地理解

  1. 一个空sources.list

    • cat /etc/apt/sources.list

      <empty>
      
    • sudo apt-add-update enable security

      <empty>
      
  2. 一个启用的存储库 ( main)

    • cat /etc/apt/sources.list

      deb http://archive.ubuntu.com/ubuntu wily main
      
    • sudo apt-add-update enable security

      deb http://archive.ubuntu.com/ubuntu wily main
      deb http://archive.ubuntu.com/ubuntu wily-security main
      
  3. 一行或两行中的两个或多个已启用的存储库

    • cat /etc/apt/sources.list

      deb http://archive.ubuntu.com/ubuntu wily main universe
      

      或者

      deb http://archive.ubuntu.com/ubuntu wily main
      deb http://archive.ubuntu.com/ubuntu wily universe
      
    • sudo apt-add-update enable security

      deb http://archive.ubuntu.com/ubuntu wily main universe
      deb http://archive.ubuntu.com/ubuntu wily-security main universe
      

      或者

      deb http://archive.ubuntu.com/ubuntu wily main
      deb http://archive.ubuntu.com/ubuntu wily-security main
      deb http://archive.ubuntu.com/ubuntu wily universe
      deb http://archive.ubuntu.com/ubuntu wily-security universe
      
  4. 有deb-src条目

    • cat /etc/apt/sources.list

      deb http://archive.ubuntu.com/ubuntu wily main universe
      deb-src http://archive.ubuntu.com/ubuntu wily main universe
      
    • sudo apt-add-update enable security

      deb http://archive.ubuntu.com/ubuntu wily main universe
      deb-src http://archive.ubuntu.com/ubuntu wily main universe
      deb http://archive.ubuntu.com/ubuntu wily-security main universe
      deb-src http://archive.ubuntu.com/ubuntu wily-security main universe
      
  5. 有无效deb-src条目

    • cat /etc/apt/sources.list

      deb http://archive.ubuntu.com/ubuntu wily main universe
      # deb-src http://archive.ubuntu.com/ubuntu wily main universe
      
    • sudo apt-add-update enable security

      deb http://archive.ubuntu.com/ubuntu wily main universe
      # deb-src http://archive.ubuntu.com/ubuntu wily main universe
      deb http://archive.ubuntu.com/ubuntu wily-security main universe
      
  6. default事情_

    • cat /etc/apt/sources.list

      deb http://archive.ubuntu.com/ubuntu wily-security universe
      
    • sudo apt-add-update enable default

      deb http://archive.ubuntu.com/ubuntu wily universe
      deb http://archive.ubuntu.com/ubuntu wily-security universe
      
  7. 只有一个条目和disable动作

    • cat /etc/apt/sources.list

      deb http://archive.ubuntu.com/ubuntu wily-security universe
      
    • sudo apt-add-update disable security

      <empty>
      
  8. 不同或相同的存储库的不同或相同的服务器,尊重每个服务器

    • cat /etc/apt/sources.list

      deb http://archive.ubuntu.com/ubuntu wily universe
      deb http://us.archive.ubuntu.com/ubuntu wily main
      
    • sudo apt-add-update enable security

      deb http://archive.ubuntu.com/ubuntu wily universe
      deb http://us.archive.ubuntu.com/ubuntu wily main
      deb http://archive.ubuntu.com/ubuntu wily-security universe
      deb http://us.archive.ubuntu.com/ubuntu wily-security main
      
  9. 不同存储库的不同 Ubuntu 版本,尊重每个版本

    • cat /etc/apt/sources.list

      deb http://archive.ubuntu.com/ubuntu wily main universe
      deb http://archive.ubuntu.com/ubuntu trusty main
      
    • sudo apt-add-update enable security

      deb http://archive.ubuntu.com/ubuntu wily main universe
      deb http://archive.ubuntu.com/ubuntu trusty main
      deb http://archive.ubuntu.com/ubuntu wily-security main universe
      deb http://archive.ubuntu.com/ubuntu trusty-security main
      
  10. 中的 PPA 或其他包源(非规范)sources.list?

    忽视!

  11. 不要更改协议,例如https, http, tor, ...

command-line
  • 5 5 个回答
  • 4592 Views

5 个回答

  • Voted
  1. Sergiy Kolodyazhnyy
    2015-11-23T13:31:46+08:002015-11-23T13:31:46+08:00

    2015 年 11 月 27 日更新:

    脚本的第二个版本仍然让我对源代码的臃肿和我不得不使用几种不同工具的事实感到不满。因此我试图只用 AWK 重写脚本。

    新脚本使用纯 AWK,更符合要求。本质上它会在/etc/apt/sources.list每次运行时重写。

    脚本运行sudo apt-get update后需要更新,所以脚本退出成功后再运行。

    该文件必须启用可执行权限chmod +x add-update.awk并保存在$PATH变量中包含的任何目录中。特别建议将脚本保存到$HOME/bin文件夹(也必须附加到$PATH变量)。

    /etc/apt/sources.list不需要备份原始文件,但强烈建议备份。要备份文件,请执行

    sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak

    用法:

    sudo ./add-update.awk -v ACTION=[enable|disable|help] -v SOURCE=[updates|backports|security|proposed]
    

    来源在github

    演示:

    sergrep:$ cat /etc/apt/sources.list                                                                              
    deb http://it.archive.ubuntu.com/ubuntu wily main universe
    deb http://us.archive.ubuntu.com/ubuntu wily-backports main
    
    deb-src http://it.archive.ubuntu.com/ubuntu wily main universe
    deb-src http://us.archive.ubuntu.com/ubuntu wily-backports main
    # removed
    
    sergrep:$ sudo ./add-update.awk -v ACTION="enable" -v SOURCE="security"   
    [sudo] password for xieerqi: 
    /etc/apt/sources.list
    <<< Script finished processing
    
    sergrep:$ cat /etc/apt/sources.list                                                                              
    deb http://it.archive.ubuntu.com/ubuntu wily main universe
    deb http://it.archive.ubuntu.com/ubuntu wily-security  main universe
    deb http://us.archive.ubuntu.com/ubuntu wily-backports main
    deb http://us.archive.ubuntu.com/ubuntu wily-security  main
    deb-src http://it.archive.ubuntu.com/ubuntu wily main universe
    deb-src http://it.archive.ubuntu.com/ubuntu wily-security  main universe
    deb-src http://us.archive.ubuntu.com/ubuntu wily-backports main
    deb-src http://us.archive.ubuntu.com/ubuntu wily-security  main
    

    源代码

    #!/usr/bin/awk -f
    #
    ###########################################################
    # Author: Serg Kolo
    # Date: Nov 27,2015
    # Purpose: A script that enables/disables 4 ubuntu sources
    # (namely updates, backports, proposed, and security )
    # much in a way like software-properties-gtk does
    # Written for:  http://paste.ubuntu.com/13434218/
    ###########################################################
    #
    # Permission to use, copy, modify, and distribute this software is hereby granted
    # without fee, provided that  the copyright notice above and this permission statement
    # appear in all copies.
    #
    # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
    # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    # DEALINGS IN THE SOFTWARE.
    
    function printUsage() {
        print "Usage: sudo ./add-update.awk -v ACTION=[enable|disable|help] -v SOURCE=[updates|backports|security|proposed]";
        exit
    }
    
    function checkSourceEnabled()
    {
        if ( $3 ~ SOURCE) {
            print SOURCE" is enabled; exiting"
            VAL = 1
        }
        else {
            VAL = 0
        }
        return VAL
    }
    
    function disableSource()
    {
        if ( $0 ~ SOURCE ) $0="# removed";
        j++;
        newLines[j]=$0;
    }
    
    function listStuff () {
        for(k=4; k<=NF; k++) if ( $k~/#/  ) {break} else {
                COMPONENTS=COMPONENTS" "$k
            };
        gsub(/\-.*/,"",$3);
        STRING=$1" "$2" "$3APPEND" "COMPONENTS;
        COMPONENTS=""
                   return STRING;
    }
    
    function replaceFile()
    {
        command="mv  /tmp/sources.list "ARGV[1]
                system(command);
    }
    
    ############
    #  MAIN
    #############
    BEGIN {
    
    # argument checking sequence
    # must remain written in if-else
    # structure rather than case,
    # to consider users who may not be able
    # to install gawk due to broken sources.list
    # which is what this script should be aimed at
    
    # actions checked first so that 
    # help message can be printed 
     if ( ACTION ==  "enable" ||
          ACTION == "disable" ||
          ACTION == "default"  ) {
    
        print "<<< ACTION ARG OK" 
      }
      else if (ACTION == "help" ){
        printUsage()
        exit
      }
    
    
      if ( SOURCE == "update" || 
           SOURCE == "security" || 
           SOURCE == "backports" || 
           SOURCE == "proposed" ) { 
           print "<<< SOURCE ARG OK"
    
      }
    
       else if ( ACTION != "default"  || ACTION != "help" ) {  
            print "<<< E: SOURCE ARG INCORRECT"; 
            printUsage(); 
            exit 1   }
    
        # static filename to operate on
        ARGV[ARGC++]="/etc/apt/sources.list";
    
        if (ACTION == "enable" ) {
            APPEND="-"SOURCE;
        } else{
            APPEND="";
        }
    
    } # END OF BEGIN
    
    $0~/^deb*/ && $0!~/partner/ && $0!~/extra/ {
    
        if ( ACTION == "enable" ) {
            j++;
            ARRAY[j]=$0
            ENABLED=checkSourceEnabled();
    
            if ( ENABLED ) {
                exit 1
            }
            else {
                j++;
                ARRAY[j]=listStuff();
            }
    
        }
        else if ( ACTION == "disable" ){
            disableSource() ;
        }
        else if ( ACTION == "default" && SOURCE == "default" ) {
            j++;
            defaultsArray[j]=$0;
            j++;
            defaultsArray[j]=listStuff();
        }
    }
    
    END {
        print "<<< Script finished processing" ;
        if ( ACTION =="enable" && ENABLED == 0 ){
         for(i=1;i<=j;i++)
            print ARRAY[i] |  "sort -u > /tmp/sources.list ";
         replaceFile();
         }
         else if ( ACTION == "disable" ) {
           for ( i=1;i<=j;i++  ) print newLines[i] | "sort -u > /tmp/sources.list"
           replaceFile();
         }
         else if (ACTION == "default" ){
            for ( i=1;i<=j;i++  ) print defaultsArray[i] | "sort -i -u > /tmp/sources.list"
            replaceFile();
         }
    }
    
    # END OF MAIN
    

    --

    之前的版本

    github 上的版本#1(带有 AWK 和 SED 的 bash 脚本)

    github 上的版本#2(也是 bash 脚本)

    • 12
  2. xiaodongjie
    2015-11-27T03:12:23+08:002015-11-27T03:12:23+08:00

    I analysed the source of Ubuntu Software Center that written in python.

    After, I wrote following code runs well. aptsources is a python module used by Ubuntu Software Center to manage /etc/apt/sources.list and /etc/apt/sources.list.d.

    #!/usr/bin/python
    
    import aptsources.sourceslist
    from subprocess import Popen, PIPE
    import errno
    
    import os
    
    def _lsb_release():
        """Call lsb_release --idrc and return a mapping."""
        result = {'Codename': 'sid', 'Distributor ID': 'Debian',
                  'Description': 'Debian GNU/Linux unstable (sid)',
                  'Release': 'unstable'}
        try:
            out = Popen(['lsb_release', '-idrc'], stdout=PIPE).communicate()[0]
            # Convert to unicode string, needed for Python 3.1
            out = out.decode("utf-8")
            result.update(l.split(":\t") for l in out.split("\n") if ':\t' in l)
        except OSError as exc:
            if exc.errno != errno.ENOENT:
                logging.warning('lsb_release failed, using defaults:' % exc)
        return result
    
    
    if __name__ == "__main__":
        if len(os.sys.argv) != 3 or \
            os.sys.argv[1] not in ['enable', 'disable'] or \
            os.sys.argv[2] not in ['updates', 'security', 'proposed', 'backports', 'default']:
            print "Usage: apt-add-update <enable|disable> <default|updates|security|proposed|backports>"
            os.sys.exit(0)
    
        release = _lsb_release()
        codename = release['Codename']
    
        sourcelist = aptsources.sourceslist.SourcesList()
    
        template = None
    
        main_uri = ""
        main_comps = []
        main_types = []
        child_comps = []
        child_types = []
    
        for tmpl in sourcelist.matcher.templates:
            if tmpl.name == codename and tmpl.distribution == "Ubuntu":
                template = tmpl
                break
    
        updated = False
    
        for source in sourcelist.list:
            if source.invalid:
                continue
            for comp in source.comps:
                if comp not in child_comps:
                    child_comps.append(comp)
    
            if source.template and source.template.official and source.dist == codename and source.template.name == codename:
                main_uri = source.uri
    
                for comp in source.comps:
                    if comp not in main_comps:
                        main_comps.append(comp)
    
                main_types.append(source.type)
            else:
                child_types.append(source.type)
    
            if source.dist == codename + "-" + os.sys.argv[2]:
                if os.sys.argv[1] == 'enable' and source.type in main_types:
                    source.set_enabled(True)
                if os.sys.argv[1] == 'disable':
                    source.set_enabled(False)
                updated = True
    
            if source.dist == codename and os.sys.argv[2] == "default":
                if os.sys.argv[1] == 'enable' and source.type in child_types:
                    source.set_enabled(True)
                if os.sys.argv[1] == 'disable':
                    source.set_enabled(False)
                updated = True
    
        if not main_uri:
            main_uri = "http://archive.ubuntu.com/ubuntu"
    
        if os.sys.argv[2] == "default" and not main_comps:
            main_comps = child_comps
    
        if not main_comps:
            main_comps = ['main', 'restricted', 'universe', 'multiverse']
    
        if not updated and os.sys.argv[1] != 'disable':
    
            if os.sys.argv[2] == "default":
                uri = main_uri
                if tmpl.base_uri:
                    uri = tmpl.base_uri
    
                tmpl = template
                line = tmpl.type + " " + uri + " " + tmpl.name + " " + " ".join(main_comps)
    
                sourceentry = aptsources.sourceslist.SourceEntry(line)
                sourcelist.list.append(sourceentry)
    
    
            for tmpl in template.children:
                if tmpl.name != codename + "-" + os.sys.argv[2] and \
                    not (os.sys.argv[2] == "default" and tmpl.name == codename):
                    continue
    
                if os.sys.argv[2] == "default" and tmpl.type not in child_types:
                    continue
    
                if os.sys.argv[2] != "default" and tmpl.type not in main_types:
                    continue
    
                uri = main_uri
                if tmpl.base_uri:
                    uri = tmpl.base_uri
                if not uri:
                    continue
    
                line = tmpl.type + " " + uri + " " + tmpl.name + " " + " ".join(main_comps)
    
                sourceentry = aptsources.sourceslist.SourceEntry(line)
                sourcelist.list.append(sourceentry)
    
        sourcelist.save()
    

    Save this code with the file name, /usr/local/bin/apt-add-update. And then run as following.

    $ sudo apt-add-update <enable|disable> <default|updates|security|proposed|backports>
    

    I updated it for the multi distro support, e.g. trusty and wily.

    #!/usr/bin/python
    
    import aptsources.sourceslist
    import os
    
    subdistnames = ['updates', 'security', 'proposed', 'backports']
    
    def get_subdistname(distname):
        rc = "default"
        try:
            rc = distname.split("-")[1]
        except:
            pass
        return rc
    
    def get_distname(distname):
        rc = distname
        try:
            rc = distname.split("-")[0]
        except:
            pass
        return rc
    
    def duplicate_check(entries):
        new_entries = []
        for source in entries:
            for newsource in new_entries:
                if source.type == newsource.type and source.uri == newsource.uri and source.dist == newsource.dist:
                    for comp in newsource.comps:
                        if comp in source.comps:
                            source.comps.remove(comp)
    
            if len(source.comps) > 0:
                new_entries.append(source)
        return new_entries
    
    if __name__ == "__main__":
        if len(os.sys.argv) != 3 or \
            os.sys.argv[1] not in ['enable', 'disable'] or \
            ( os.sys.argv[2] not in subdistnames and os.sys.argv[2] != 'default' ):
            print "Usage: apt-add-update <enable|disable> <default|updates|security|proposed|backports>"
            os.sys.exit(0)
    
        sourcelist = aptsources.sourceslist.SourcesList()
        sourcelist.list = []
        sourcelist.load('/etc/apt/sources.list')
    
        main_entries = []
        child_entries = []
        other_entries = []
    
        distro_names = []
    
        for tmpl in sourcelist.matcher.templates:
            if tmpl.name.find('-') > 0 or tmpl.distribution != "Ubuntu":
                continue
            distro_names.append(tmpl.name)
    
        for source in sourcelist.list:
            if source.invalid or source.disabled:
                continue
            subdistname = get_subdistname(source.dist)
    
            if source.dist in distro_names:
                main_entries.append(source)
            elif subdistname in subdistnames:
                child_entries.append(source)
            else:
                other_entries.append(source)
    
        if os.sys.argv[2] in subdistnames:
            modified = True
            while modified:
                modified = False
                for source in child_entries:
                    if get_subdistname(source.dist) == os.sys.argv[2]:
                        child_entries.remove(source)
                        modified = True
                        continue
    
            if os.sys.argv[1] == "enable":
                for source in main_entries:
                    uri = source.uri
                    if os.sys.argv[2] == "security":
                        uri = "http://security.ubuntu.com/ubuntu"
                    comps = []
                    for i in source.comps:
                        if i in ['main', 'restricted', 'universe', 'multiverse']:
                            comps.append(i)
                    line = source.type + " " + uri + " " + source.dist + "-" + os.sys.argv[2] + " " + " ".join(comps)
                    sourceentry = aptsources.sourceslist.SourceEntry(line)
                    child_entries.append(sourceentry)
    
        else:
            main_entries = []
            if os.sys.argv[1] == "enable":
                for source in child_entries:
                    uri = source.uri
                    if get_subdistname(source.dist) == "security":
                        uri = "http://archive.ubuntu.com/ubuntu"
                    comps = []
                    for i in source.comps:
                        if i in ['main', 'restricted', 'universe', 'multiverse']:
                            comps.append(i)
                    line = source.type + " " + uri + " " + get_distname(source.dist) + " " + " ".join(comps)
                    sourceentry = aptsources.sourceslist.SourceEntry(line)
                    main_entries.append(sourceentry)
    
        main_entries = duplicate_check(main_entries)
        child_entries = duplicate_check(child_entries)
        other_entries = duplicate_check(other_entries)
    
        sourcelist.list = []
        sourcelist.list.extend(main_entries)
        sourcelist.list.extend(child_entries)
        sourcelist.list.extend(other_entries)
    
        sourcelist.save()
    

    Reference URL is https://github.com/dupingping/apt-add-update/tree/master

    • 12
  3. user.dz
    2015-11-30T08:24:31+08:002015-11-30T08:24:31+08:00

    Usage:

    ## testing
    
    apt-add-update  enable|disable  default|security|updates|proposed|backports  [file]
    
    
    ## real
    
    sudo  apt-add-update  enable|disable  default|security|updates|proposed|backports
    

    Here main points:

    I parsed the file because I was looking for some other options myself.

    • Checks if any is a mirror, either official including (old-releases, ports) or other mirrors provided by community loaded from python-apt package (it contains a file with all mirrors).

      /usr/share/python-apt/templates/Ubuntu.mirrors
      
    • Always keep the official URI in the file. So even with all disabled, it will keep a commented line for a persistence setting. It resolves the lines to the minimum with alphabetic sorting type, url, dist, comp.

    • Prints to the stdout if it get an input file as 3rd argument or no permission to write /etc/apt/sources.list

    • Does not support [ options ] like [ arch=amd64 ].
    • 删除disable default了我要求用户指定要禁用的内容。
    • 我不喜欢最后一个选项 (9),因为我自己是故意混合回购的。所以他们应该被视为第 3 方存储库。

    下载:带有完整的测试集。

    https://github.com/sneetsher/au_700860_apt_channels

    脚本:

    #!/usr/bin/python3
    
    import sys,os
    import re
    
    ## official repo's 
    
    #http://ports.ubuntu.com/ubuntu-ports/
    #http://old-releases.ubuntu.com/ubuntu/
    #http://security.ubuntu.com/ubuntu/
    #http://archive.ubuntu.com/ubuntu/
    
    repo_official_uri_re = re.compile(r"\A(http|ftp)://(([a-zA-Z]*.)?archive|security|old-releases|ports).ubuntu.com/ubuntu(-ports)?[/]?\Z")
    
    ## load other mirrors
    
    mirrors=[]
    
    mir_re = re.compile(r"\A(http|ftp)://")
    
    with open("/usr/share/python-apt/templates/Ubuntu.mirrors","r") as f:
        for l in f:
            if mir_re.match(l):
                mirrors.append(l.strip())
    f.close()
    #print(mirrors)
    
    ## system release
    
    with open("/etc/lsb-release","r") as f:
        for l in f:
            k,v=l.split("=")
            if k=="DISTRIB_CODENAME":
                release = v.strip()
                break
    
    #print(release)
    f.close()
    
    ## load sources.list
    
    ##TODO: missing support deb line options like [ arch=whatever ] 
    emp_re  = re.compile(r"\A\s*\Z")
    repo_re = re.compile(r"\A#* *deb(-src)? *(http://|ftp://|file://|cdrom:)")
    com_re  = re.compile(r"\A#")
    repo_details_re = re.compile(r"\A(?P<active>#*) *(?P<type>deb(-src)?) *(?P<uri>(http://|ftp://|file://|cdrom:\[[a-zA-Z0-9 \-_().]*\])?\S*) (?P<dist>[a-zA-Z\-_]*) (?P<comp>[a-zA-Z ]*\Z)")
    
    
    ##example
    sources={
      "http://archive.ubuntu.com/ubuntu/":{
        "active":True,
        "deb":{
          "wily":["universe","multiverse","restricted","main"],
          "wily-security":["main","restricted","universe","multiverse"]
          },
        "deb-src":{
          "wily":["universe","multiverse","restricted","main"]
          },
        "mirror":True    
        }
      }
    
    sources={}
    
    uri=""
    
    ##for testing
    if len(sys.argv)>=4 and os.path.isfile(sys.argv[3]):
        ifile = sys.argv[3]
    else:
        ifile = "/etc/apt/sources.list"
    
    with open(ifile, "r") as f:
        for l in f:
            l=l.strip()
    
            r = emp_re.match(l)
            if r:
                continue
            else:
                #print("raw:",l)
    
                r = repo_re.match(l)
                if r:
                    #print("repository:",l)
                    r = repo_details_re.match(l)
                    #print(r.groupdict())
                    uri=r.group("uri")
                    if uri[-1]!="/":
                        uri += "/"
                    if (uri not in sources):
                        sources[uri] = {"active":False,"deb":{},"deb-src":{},"mirror":False}
                        m = repo_official_uri_re.match(uri)
                        if m or uri in mirrors:
                            sources[uri]["mirror"] = True
                        if r.group("active")=="":
                                sources[uri]["active"]=True
                        sources[uri][r.group("type")][r.group("dist")]=r.group("comp").split()
                    else:
                        if r.group("active")=="" and sources[uri]["active"]==False:
                            sources[uri]["active"]=True
                            sources[uri]["deb"]={}
                            sources[uri]["deb-src"]={}
                            sources[uri][r.group("type")][r.group("dist")]=r.group("comp").split()
                        if (r.group("active")=="")==sources[uri]["active"]:
                            if r.group("dist") not in sources[uri][r.group("type")]:
                                sources[uri][r.group("type")][r.group("dist")]=r.group("comp").split()
                            else:
                                for c in r.group("comp").split():
                                    if c not in sources[uri][r.group("type")][r.group("dist")]:
                                        sources[uri][r.group("type")][r.group("dist")].append(c)
                else:
                    r = com_re.match(l)
                    if r:
                        #print("comment",l)
                        continue
                    else:
                        print("unknown",l)
        #print(sources)
    
    f.close()
    
    ## process argumments
    
    #fallback for default component to be copied from
    comp=[release+"-security",release+"-update",release+"-proposed"]
    found_other_comp=False 
    
    if sys.argv[2]=="default" and sys.argv[1]=="enable":
        for u in sorted(sources.keys()):
            if sources[u]["mirror"]:
                if sources[u]["active"]:
                    for t in ["deb","deb-src"]:
                        if release not in sources[u][t]:
                            for d in range(len(comp)):
                                if comp[d] in sources[u][t]:
                                    other_comp_found=True
                                    for i in range(d):
                                        sources[u][t][comp[i]]=sources[u][t][comp[d]]
                                    sources[u][t][release]=sources[u][t][comp[d]]
    
                            ###don't activate any thing if commented like an empty file.
                            #if not found_other_comp and t=="deb":
                            #   sources[u][t][release]=["main"]
                #else:
                #   sources[u]["active"]=True
                #   sources[u]["deb"]={release:["main"]}
                #   sources[u]["deb-src"]={}
    
        ## carry on enable security
        sys.argv[2] = "security"
    
    if sys.argv[2]=="security" or sys.argv[2]=="updates" or sys.argv[2]=="proposed" or sys.argv[2]=="backports":
        for u in sorted(sources.keys()):
            if sources[u]["mirror"] and sources[u]["active"]:
                if sys.argv[1]=="disable":
                    if len(sources[u]["deb"])+len(sources[u]["deb-src"])>(release+"-"+sys.argv[2] in sources[u]["deb"])+(release+"-"+sys.argv[2] in sources[u]["deb-src"]):
                        if release+"-"+sys.argv[2] in sources[u]["deb"]:
                            del sources[u]["deb"][release+"-"+sys.argv[2]]
                        if release+"-"+sys.argv[2] in sources[u]["deb-src"]:
                            del sources[u]["deb-src"][release+"-"+sys.argv[2]]
                    else:
                        sources[u]["active"] = False
                elif sys.argv[1]=="enable":
                    for t in ["deb","deb-src"]:
                        if release in sources[u][t]:
                            if release+"-"+sys.argv[2] not in sources[u][t]:
                                sources[u][t][release+"-"+sys.argv[2]]=sources[u][t][release]
                            else:
                                for c in sources[u][t][release]:
                                    if c not in sources[u][t][release+"-"+sys.argv[2]]:
                                        sources[u][t][release+"-"+sys.argv[2]].append(c)
    
    ## generate the new list
    data_out=""
    for u in sorted(sources.keys()):
        #print(u)
        for t in ["deb","deb-src"]:
            for d in sorted(sources[u][t].keys()):
                data_out += (not sources[u]["active"])*"#"+" ".join([t,u,d,""])+" ".join(sorted(sources[u][t][d]))+"\n"
    
    if len(sys.argv)>=4 or not os.access("/etc/apt/sources.list", os.W_OK):
        print(data_out)
    else:
        with open("/etc/apt/sources.list","w") as f:
            f.write(data_out)
        f.close()
    
    sys.exit(0)
    
    • 7
  4. Pilot6
    2015-11-24T10:54:20+08:002015-11-24T10:54:20+08:00

    您可以使用add-apt-repository.

    例如,您可以proposed添加

    sudo add-apt-repository "http://archive.ubuntu.com/ubuntu/ $(lsb_release -sc)-proposed restricted universe multiverse main"
    

    它将添加deb和deb-src行到/etc/apt/sources.list. 但源代码行将被注释。

    If you run add-apt-repository with -s parameter, it will not comment out deb-src.

    You can enable security by

    sudo add-apt-repository "http://security.ubuntu.com/ubuntu/ $(lsb_release -sc)-security restricted universe multiverse main"
    
    • 6
  5. Best Answer
    kos
    2015-11-28T10:21:05+08:002015-11-28T10:21:05+08:00

    This does exactly what has been asked;

    I'll update this from time to time if necessary;

    The bleeding edge version can be found at this GitHub repository;

    To install from the GitHub repository:

    • Install git: sudo apt-get install git
    • Clone the repository: git clone https://github.com/kos0/addRemoveDistribution.git

    Synopsis:

    enableDisableDistribution.pl <enable|disable> <default|security|updates|proposed|backports>
    

    s1

    s2

    s3

    #!/usr/bin/perl
    
    sub printUsage {
        print("Usage: enableDisableDistribution.pl \e[4maction\e[0m \e[4mdistribution\e[0m\n\n");
        print("\e[4maction\e[0m must be \e[1menable\e[0m or \e[1mdisable\e[0m\n");
        print("\e[4mdistribution\e[0m must be \e[1mdefault\e[0m, \e[1msecurity\e[0m, \e[1mupdates\e[0m, \e[1mproposed\e[0m or \e[1mbackports\e[0m");
        exit(0);
    }
    
    sub parse {
        open(my $in, "/etc/apt/sources.list") || die("Couldn't open '/etc/apt/sources.list': $!");
        while(<$in>) {
            my $matchDistribution;
            chomp;
            if(/^deb(-src)? +(.*?).ubuntu.com\/ubuntu\/? +(.*?) +(.*?) *(#.*)?$/) {
                my $debSrc = $1 eq "-src";
                my $URI = $2;
                my @split = split("-", $3);
                my @components = sort(split(" ", $4));
                if(($distribution eq "default" && defined($split[1])) || ($distribution ne "default" && $split[1] ne $distribution)) {
                    push(@add, "$debSrc,$URI,$split[0],@components");
                }
                else {
                    $matchDistribution = 1;
                }
            }
            (! $matchDistribution && push(@notMatchDistribution, $_)) || push(@matchDistribution, $_);
        }
        close($in);
    }
    
    sub update {
        while(1) {
            print("Would you like to update the cache? Y-y/N-n: \n");
            my $update = <STDIN>;
            if($update =~ /^y$/i) {
                my $ret = system("apt-get update");
                exit($ret);
            }
            elsif($update =~ /^n$/i) {
                exit(0);
            }
            else {
                print("Please enter Y-y or N-n.\n");
            }
        }
    }
    
    sub rewrite {
        if($action eq "enable") {
            if(@matchDistribution == 0) {
                open(my $out, ">", "/etc/apt/sources.list") || die("Couldn't open '/etc/apt/sources.list': $!");
                foreach(@notMatchDistribution) {
                    print $out ($_ . "\n");
                }
                foreach(@add) {
                    my @x = split(",");
                    my @y = split(" ", $x[3]);
                    my $line = sprintf("deb%s $x[1].ubuntu.com/ubuntu $x[2]%s @y", $x[0] && sprintf("-src"), $distribution ne "default" && sprintf("-$distribution"));
                    if(! grep(/^$line$/, @added)) {
                        print $out ($line . " #Added by enableDisableDistribution\n");
                        push(@added, $line);
                    }
                }
                close($out);
                printf("Added %s %s.\n", scalar(@added), @added == 1 ? sprintf("entry") : sprintf("entries"));
                update;
            }
            else {
                print("$distribution is enabled already. Aborting.\n");
                exit(1);
            }
        }
        else {
            if(@matchDistribution > 0) {
                open(my $out, ">", "/etc/apt/sources.list") || die("Couldn't open '/etc/apt/sources.list': $!");
                foreach my $line (@notMatchDistribution) {
                    print $out ($line . "\n");
                }
                close($out);
                printf("Removed %s %s.\n", scalar(@matchDistribution), @matchDistribution == 1 ? sprintf("entry") : sprintf("entries"));
                update;
            }
            else {
                print("$distribution is disabled already. Aborting.\n");
                exit(1);
            }
        }
    }
    
    if($> != 0) {
        print("You must be root to run enableDisableDistribution.\n");
        exit(1);
    }
    if(@ARGV == 2 && $ARGV[0] =~ /^(enable|disable)$/ && $ARGV[1] =~ /^(default|security|updates|proposed|backports)$/) {
        $action = $ARGV[0];
        $distribution = $ARGV[1];
    }
    else {
        printUsage;
    }
    
    parse;
    rewrite;
    
    exit(0);
    
    • 5

相关问题

  • 如何从命令行仅安装安全更新?关于如何管理更新的一些提示

  • 如何从命令行刻录双层 dvd iso

  • 如何从命令行判断机器是否需要重新启动?

  • 文件权限如何工作?文件权限用户和组

  • 如何在 Vim 中启用全彩支持?

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    如何运行 .sh 脚本?

    • 16 个回答
  • Marko Smith

    如何安装 .tar.gz(或 .tar.bz2)文件?

    • 14 个回答
  • Marko Smith

    如何列出所有已安装的软件包

    • 24 个回答
  • Marko Smith

    无法锁定管理目录 (/var/lib/dpkg/) 是另一个进程在使用它吗?

    • 25 个回答
  • Martin Hope
    Flimm 如何在没有 sudo 的情况下使用 docker? 2014-06-07 00:17:43 +0800 CST
  • Martin Hope
    Ivan 如何列出所有已安装的软件包 2010-12-17 18:08:49 +0800 CST
  • Martin Hope
    La Ode Adam Saputra 无法锁定管理目录 (/var/lib/dpkg/) 是另一个进程在使用它吗? 2010-11-30 18:12:48 +0800 CST
  • Martin Hope
    David Barry 如何从命令行确定目录(文件夹)的总大小? 2010-08-06 10:20:23 +0800 CST
  • Martin Hope
    jfoucher “以下软件包已被保留:”为什么以及如何解决? 2010-08-01 13:59:22 +0800 CST
  • Martin Hope
    David Ashford 如何删除 PPA? 2010-07-30 01:09:42 +0800 CST

热门标签

10.10 10.04 gnome networking server command-line package-management software-recommendation sound xorg

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve