How to use dpkg to compare two Linux servers

While we mainly install, remove, update and otherwise manage software on Debian and Ubuntu based systems using apt-get, the lower level packaging system that apt-get actually relies on is dpkg.

You can use dpkg to list all of the installed packages on the current system. Do this by passing the –get-selections option. The following is the command that would get all of the packages, sort them, and list them into an installed-packages file.

dpkg --get-selections|sort > installed-packages

Now you can do the same on your second Debian or Ubuntu server except you might want to name your file something like installed-packages2.

With those two files ready you can now compare them. Copy over the first file to the second system (or vice versa) and run the diff command to see the differences.

diff -u installed-packages installed-packages2 > compare-servers

This would compare the two lists and throw the results into compare-servers text file. Name it whatever you like. The -u option makes the results a little more readable, but you can alternatively use the -y option which will format the results in two columns, first representing the first file, and second representing the second file.

Studying the differences between package lists can help you figure out what the differences are between two server setups in terms of installed software, what does one have that the other doesn't. If you want to replicate installed packages of one system to another, or in other words, install all of the packages which are installed on the first system to the second system, you can do that with dpkg and apt-get.

First run the following to get dpkg to select packages to install, marking them for installation:

dpkg --set-selections < installed-packages 

And then run this apt-get command to get those packages installed:

apt-get dselect-upgrade

This also allows you to quickly and easily restore a given system after a fresh install, if you've saved the list of installed packages from a previous system before you deleted it. It is also possible to compare and restore system settings from the /etc directory, but that is beyond the scope of this post.