Created
August 21, 2015 20:48
-
-
Save clubapplets-server/886589c2071c66100679 to your computer and use it in GitHub Desktop.
This script automatically creates a snapshot of a VirtualBox virtual machine.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#-*- coding: utf8 -*- | |
#!/usr/bin/env python3 | |
""" | |
This script automatically creates a snapshot of a | |
VirtualBox virtual machine. Crontab it if you want | |
to make it every a definite period of time. | |
""" | |
import sys | |
import subprocess | |
import pdb | |
from configparser import ConfigParser | |
from pathlib import Path | |
from datetime import datetime | |
from dateutil.relativedelta import relativedelta | |
_config = ConfigParser() | |
CURRENT_PATH = Path(__file__).parent | |
CONFIG_FILE_PATH = CURRENT_PATH / 'snapshots_config.ini' | |
TIME_FORMAT = '%Y-%m-%d' | |
if not CONFIG_FILE_PATH.exists(): | |
print('ERROR: No configuration file. Please add "snapshots_config.ini" in the script directory.', file=sys.stderr) | |
sys.exit(1) | |
else: | |
_config.read(str(CONFIG_FILE_PATH)) | |
if __name__ == "__main__": | |
vms = _config['snapshot']['vms'].split(',') | |
snapshot_name = datetime.today().strftime(TIME_FORMAT) | |
for vm_name in vms: | |
output_list = subprocess.check_output(['vboxmanage', 'snapshot', vm_name, 'list'], universal_newlines=True).split('\n') | |
uncleaned_names = [item for item in output_list if 'Name:' in item and 'UUID:' in item] | |
cleaned_vm_names = list(map(lambda item: item[item.find(':') + 1:item.find('(')].strip(), uncleaned_names)) | |
for cleaned_name in cleaned_vm_names[2:]: # First two are Base installation and tools configured. | |
snapshot_date = None | |
try: | |
snapshot_date = datetime.strptime(cleaned_name, TIME_FORMAT) | |
except: pass | |
if snapshot_date is not None and snapshot_date <= (datetime.today() - relativedelta(years=1)): | |
subprocess.call(['vboxmanage', 'snapshot', vm_name, 'delete', cleaned_name]) | |
subprocess.call(['vboxmanage', 'snapshot', vm_name, 'take', snapshot_name]) | |
sys.exit(0) | |
__author__ = 'Charles Levesque' | |
__date__ = '2015-06-07' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Configuration file for the automatic_snapshot.py script. | |
[snapshot] | |
# Name of the vms you want to snapshot separated by commas. | |
vms=vm_name_1,vm_name_2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment