How to Backup and Restore phpIPAM

phpIPAM is an awesome IP address management application. I have used it for many years and really like it. In this guide I will show you how you can schedule automatic backups of your IPAM and how you easily can restore the database if something goes wrong.

Schedule automatic backups

  1. Create backup folder
    mkdir /mnt/backups/phpipam/db/
  2. Create a file for your credentials
    This is done to prevent the credentials to be stored in clear text inside crontab.
    touch ~/.msql.cnf
    vim ~/.msql.cnf
    #[mysqldump]
    #user=root
    #password=*yoursupersecretpassword*
  3. Restrict permissions to file
    chmod 600 ~/.msql.cnf
  4. Add to cron – backup the database every day at 23:00
    crontab -e
    0 23 * * * mysqldump --defaults-file=~/.msql.cnf phpipamdb01 > /mnt/backups/phpipam/db/phpipamdb01_$(date +"%F")_bak.sql

Remove old backups

You can easily remove your old backups (30 days+) by running the command below.
find /mnt/backups/phpipam/db/ -ctime +30 -delete

So what you can do is just adding that command to crontab like I showed you in the example above. But I personally don’t like that approach because if someone changes the date/time on your server there is a risk that all of the backups gets removed and you don’t want to risk that. To make sure that the time is configured correctly you can first verify that NTP is synchronized before you remove the old backup files. (This of course assumes that your NTP servers provides you with the correct time) You can create a simple bash script that will verify that NTP is being synchronized and if it’s not synchronized you will get notified by email:

  1. Create the script
    vim rm-old-backups.sh
    # #!/bin/bash
    # #Simple script to remove old phpIPAM backups if NTP i synced.
    # #By: Rickard Carlsson (@tzusec)
    # #IF NTP WORKS THEN REMOVE FILES
    # if (ntpstat | grep -qF "synchronized to NTP server")
    # then
    #_____find /mnt/backups/phpipam/db/ -ctime +30 -delete
    # else
    # ____mail -s "NTP-error - Backups won't be deleted" rickard@tzusec.com <<< 'NTP wasn't synced so no old backups were removed.'
    # fi

  2. Make the script executable
    chmod +x rm-old-backups.sh
  3. Verify that it works as expected
    Manually run the script to make sure that is works as you want.
  4. Add it to cron – remove old backups once every day at 23:30
    crontab -e
    30 23 * * * /root/rm-old-backups.sh

Restore database

  1. Locate the backup you want to use
    ls -l /mnt/backups/phpipam/db/
  2. Restore the database from the backup
    mysql -u root -p phpipamdb01 < /mnt/backups/phpipam/db/phpipamdb01_*DATE*_bak.sql

I hope this guide was useful for you. Reach out to me on twitter @tzusec if you have any questions.

Copyright © 2022