]> gitweb.michael.orlitzky.com - untangle-https-backup.git/blob - bin/untangle-https-backup
Rearrange a comment.
[untangle-https-backup.git] / bin / untangle-https-backup
1 #!/usr/bin/python3
2 """
3 Back up Untangle configurations via the web admin UI.
4 """
5
6 from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser
7 import configparser
8 from http.client import HTTPException
9 from os import chmod
10 from urllib.error import HTTPError, URLError
11 from sys import stderr
12
13 from untangle.untangle import Untangle
14
15 # Define a few exit codes.
16 EXIT_OK = 0
17 EXIT_BACKUPS_FAILED = 1
18
19 # Create an argument parser using our docsctring as its description.
20 parser = ArgumentParser(description = __doc__,
21 formatter_class = ArgumentDefaultsHelpFormatter)
22
23 parser.add_argument('-c',
24 '--config-file',
25 default='/etc/untangle-https-backup.ini',
26 help='path to configuration file')
27
28 args = parser.parse_args()
29
30 # Default to success, change it if anything fails.
31 status = EXIT_OK
32
33 # Parse the configuration file...
34 config = configparser.ConfigParser()
35 config.read(args.config_file)
36
37 # And loop through each section.
38 for section in config.sections():
39 # For each section, we create an Untangle object based on that
40 # section's configuration.
41 u = Untangle(config[section])
42 try:
43 # And then try to log in and retrieve a backup.
44 u.login()
45 backup = u.get_backup()
46
47 # If that worked, we save the backup file and make it
48 # accessible only to its owner.
49 filename = u.name + '.backup'
50 with open(filename, 'wb') as f:
51 f.write(backup)
52 chmod(filename, 0o600)
53
54 # If it didn't work, but in a predictable way (some host is down),
55 # then we report that error and keep going.
56 except URLError as e:
57 tpl = '{:s}: {:s} from {:s}'
58 msg = tpl.format(u.name, str(e.reason), u.host)
59 print(msg, file=stderr)
60 status = EXIT_BACKUPS_FAILED
61 except HTTPError as e:
62 tpl = '{:s}: HTTP error {:s} from {:s}'
63 msg = tpl.format(u.name, str(e.code), u.host)
64 print(msg, file=stderr)
65 status = EXIT_BACKUPS_FAILED
66 except HTTPException as e:
67 # At least one sort of HTTPException (BadStatusLine) is not
68 # translated by urllib into an HTTPError, so we catch
69 # HTTPExceptions too.
70 tpl = '{:s}: HTTP exception {:s} from {:s}'
71 msg = tpl.format(u.name, repr(e), u.host)
72 print(msg, file=stderr)
73 status = EXIT_BACKUPS_FAILED
74
75 exit(status)