python script to backup installed packages

Giorgos Keramidas keramida at
Thu Feb 11 19:31:30 UTC 2010

On Thu, 11 Feb 2010 10:15:12 -0600, Adam Vande More <amvandemore at> wrote:
> Sometimes you have need to backup installed packages.  I realize most
> port management tools do this automatically, but if you're on a system
> with a lot of packages installed and one port management tool fails
> and you use another to fix it, /usr/ports/packages can become jumbled.
> Anyways, I've written a simple python script which will create a fresh
> snapshot of all installed packages.  These are convenient for backups
> or installing on a new system.
> For anyone interested:
> from subprocess import Popen, PIPE
> import os
> s = Popen('pkg_info -a | grep : | grep
> Information',shell=True,stdout=PIPE).communicate()[0]
> pkg_location = '/data/packages'
> packages = []
> for line in s.split('\n'):
>     info = line.replace('Information for ', '').replace(':','')
>     packages.append(info)
> os.chdir(pkg_location)
> for package in packages:
>     s = Popen('pkg_create -b ' +
> package,shell=True,stdout=PIPE).communicate()[0]

Nice script!

My own version was initially written in sh(1) to avoid having a Python
dependency.  Then I rewrote it in Python too.  FWIW, you can probably
save a few replace() calls and avoid the need for a full array of all
the packages by yielding the package names:

    from subprocess import PIPE, Popen as popen

    def listpackages():
        for l in iter(popen("pkg_info", shell=True, stdout=PIPE).stdout.readline, ""):
            yield l.split()[0]

    for p in listpackages():

My own version groks an os.environ['EXTRA_PKG_CREATE_ARGS'] option too
and inserts the extra options before the ["-b", "package"] arguments of
pkg_create, so that I can run the script for example with:

    env EXTRA_PKG_CREATE_ARGS='-Rvn' ./

This way package dependencies are saved too (-R option), the output of
the `pkg_create -b' command is slightly more verbose, and saving the
same package multiple times doesn't overwrite existing packages of the
same version (-n option).

More information about the freebsd-questions mailing list