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