Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python show all installed packages

Is there a way for python to show all apt/yum packages installed on a server? I have a program that can only grab one package that I specify but I'd like to know if there is a apt-show-versions/yum check-update like module in python since python-yum and python-apt only do single packages.

Thanks.

EDIT:

Here is the code I have currently:

# For finding the package version and using the package name -i
def aptpkg(package_name):
    cache = apt.Cache()
    pkg = cache[package_name]
    host = subprocess.Popen('hostname', stdout=subprocess.PIPE, universal_newlines=True).stdout.read().strip()
    if pkg.is_installed:
        print host
        print 'Current ' + package_name + ' installed:', pkg.installed.version
        con.execute("insert into ansible_packagelist(date, host, package_name, installed_version) values (current_timestamp,%s,%s,%s)", (host, package_name, pkg.installed.version,))
    else:
        print host, package_name + ' is not installed on this system.\n'
    if pkg.is_upgradable:
        print 'Upgradeable version of ' + package_name + ' :', pkg.candidate.version
        con.execute("update ansible_packagelist set upgradeable_version = %s where package_name = %s", (pkg.candidate.version, package_name))
    db.commit()
like image 536
Nvasion Avatar asked Dec 06 '22 00:12

Nvasion


2 Answers

This is the pythonic way:

import apt
cache = apt.Cache()

for mypkg in cache:
    if cache[mypkg.name].is_installed:
        print mypkg.name

For yum, I need first to login to RH/Centos system. But you can have a look to the yum library and you'll find something like 'rpmdb.searchNevra'

like image 62
maxadamo Avatar answered Dec 10 '22 12:12

maxadamo


Use subprocess to run a shell command.

from subprocess import call

for apt: call(["dpkg", "-l"])

for yum : call(["yum list installed"])

like image 31
Abhishek Pathak Avatar answered Dec 10 '22 11:12

Abhishek Pathak