]> gitweb.michael.orlitzky.com - untangle-https-backup.git/blob - src/untangle-https-backup.py
Initial commit, skeleton of a project.
[untangle-https-backup.git] / src / untangle-https-backup.py
1 #!/usr/bin/python3
2 #
3 # Back up customer Untangle boxes over HTTPS.
4 #
5
6 import configparser
7 import http.cookiejar
8 import ssl
9 import sys
10 import urllib.parse
11 import urllib.request
12
13
14 class Untangle:
15
16 def __init__(self, s):
17 """
18 Initialize this Untangle object with a ConfigParser section.
19 """
20 self.name = s.name
21 self.host = s['host']
22 self.username = s['username']
23 self.password = s['password']
24 self.version = int(s['version'])
25
26 # Create an opener object that we'll use to make HTTP requests.
27 cj = http.cookiejar.CookieJar()
28
29 # SSL mumbo jumbo to make it ignore the certificate's hostname.
30 ssl_ctx = ssl._create_unverified_context()
31 https_handler = urllib.request.HTTPSHandler(context=ssl_ctx)
32
33 # Tell it to use our cookie jar.
34 cookie_proc = urllib.request.HTTPCookieProcessor(cj)
35 self.opener = urllib.request.build_opener(https_handler, cookie_proc)
36
37 # Also set the base URL which will never change.
38 self.base_url = 'https://' + self.host + '/'
39
40
41 def login(self):
42 login_path = 'auth/login?url=/setup/welcome.do&realm=Administrator'
43 url = self.base_url + login_path
44 post_vars = {'username': self.username, 'password': self.password }
45 post_data = urllib.parse.urlencode(post_vars).encode('ascii')
46 self.opener.open(url, post_data)
47
48
49 def get_backup(self):
50 if self.version == 9:
51 return self.get_backup_v9()
52 elif self.version == 11:
53 return self.get_backup_v11()
54
55
56 def get_backup_v9(self):
57 url = self.base_url + '/webui/backup'
58 post_vars = {'action': 'requestBackup'}
59 post_data = urllib.parse.urlencode(post_vars).encode('ascii')
60 self.opener.open(url, post_data)
61
62 url = self.base_url + 'webui/backup?action=initiateDownload'
63 with self.opener.open(url) as response:
64 return response.read()
65
66
67 def get_backup_v11(self):
68 url = self.base_url + '/webui/download?type=backup'
69 post_vars = {'type': 'backup'}
70 post_data = urllib.parse.urlencode(post_vars).encode('ascii')
71 with self.opener.open(url, post_data) as response:
72 return response.read()
73
74
75
76 config = configparser.ConfigParser()
77 config.read('untangle-backup.ini')
78
79 for section in config.sections():
80 untangle = Untangle(config[section])
81 try:
82 untangle.login()
83 backup = untangle.get_backup()
84 filename = untangle.name + '.backup'
85 with open(filename, 'wb') as f:
86 f.write(backup)
87 except urllib.error.URLError as e:
88 msg = 'Connection error (' + str(e.reason) + ')'
89 msg += ' from ' + untangle.host + '.'
90 print(msg, file=sys.stderr)
91 except urllib.error.HTTPError as e:
92 msg = 'HTTP error ' + str(e.code) + ' from ' + untangle.host + '.'
93 print(msg, file=sys.stderr)