python 使用apt模块安装软件包

  最近开始学习python,看到python在系统管理,尤其是自动化管理方面很有用武之地并且已经成绩斐然(例如Ansible)。结合最新的实际情况,学些python如何管理linux上的软件包,具体到ubuntu上就是python的apt模块。
  直接上代码,然后再简单解释。

#!/usr/bin/python
# -*- coding: UTF-8 -*-
#created by yqbjtu on 2018/01/27
'''
fyi
https://apt.alioth.debian.org/python-apt-doc/library/index.html
https://apt.alioth.debian.org/python-apt-doc/library/apt_pkg.html
'''
import string
import sys
import apt
import apt_pkg


#this program will show how to install or query by python apt module

def checkPackage(pkgname):
    cache = apt.Cache()

    my_apt_pkg = cache[pkgname] #apt.package.Package object
    ll_pkg = cache._cache[pkgname]  # the low-level package object, apt_pkg.Package object

    #
    if ll_pkg.current_state !=  apt_pkg.CURSTATE_NOT_INSTALLED:
        #https://apt.alioth.debian.org/python-apt-doc/library/apt_pkg.html#curstates

        print "pkgName:" +  ll_pkg.get_fullname() +  ", version: " + ll_pkg.current_ver.ver_str + ",DescLang:"+ ll_pkg.current_ver.translated_description.language_code + ",State:%d" % (ll_pkg.current_state)
        print "this package info in Cache:"
        print ll_pkg.version_list 
    else:
        print "pkg:" +  pkgname +  " is not installed."


    if my_apt_pkg.is_installed:
        print "{pkg_name} already is installed".format(pkg_name=pkgname)
    else:
        my_apt_pkg.mark_install()

        try:
            cache.commit()
        except Exception, arg:
            print >> sys.stderr, "Sorry, package installation failed [{err}]".format(err=str(arg))
    print "End."
    #end of checkPackage function

if len(sys.argv)==2:
    pkgname =  sys.argv[1]
    checkPackage(pkgname)
else:
print "Usage:%s softwareName" % (sys.argv[0])

第一步,就是这一段代码的基本使用python aptDeme.py xxxx , 注意,这里的xxxx就是你要安扎un个或者查询的软件包,例如wget、nginx等等

第二步,就是通过apt.Cache()获取现在的整个安装包的情况,我们可以在cache中查询软件包是否已经安装,或者是否在cache,如果不在cache中需要添加或者修改repo,然后apt update,再次执行本程序。

第三步,就是根据查询的软件包实际情况,install或者打印软件的信息。
特别注意的是这两句,cache中可能包该软件的多个版本
print “this package info in Cache:”
print ll_pkg.version_list

当wget没有安装时,执行该程序
截图1:
这里写图片描述

当wget安装后,执行该程序。
截图2:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/russle/article/details/79182926