-
Notifications
You must be signed in to change notification settings - Fork 90
/
vultr_check.py
2964 lines (2572 loc) · 127 KB
/
vultr_check.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#/usr/bin/env python
from bs4 import BeautifulSoup
import MySQLdb
import os
import sys
import paramiko
import json
import random
import requests
import json
import logging
import stripe
import string
import datetime, timedelta
import time
import re
import urllib
import smtplib
from email.mime.text import MIMEText
from pyzabbix import ZabbixAPI
unifi_site_list = 'a'
live_mode = True
log = logging.getLogger(__name__)
PYTHON_VERSION = sys.version_info[0]
pid = str(os.getpid())
pidfile = "/tmp/mydaemon.pid"
if os.path.isfile(pidfile):
print "%s already exists, exiting" % pidfile
sys.exit()
file(pidfile, 'w').write(pid)
def pw_gen(size=16, chars=string.ascii_uppercase + string.digits + string.ascii_lowercase):
return ''.join(random.choice(chars) for _ in range(size))
def user_gen(size=4, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
try:
# Ugly hack to force SSLv3 and avoid
# urllib2.URLError: <urlopen error [Errno 1] _ssl.c:504:
# error:14077438:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert internal error>
import _ssl
_ssl.PROTOCOL_SSLv23 = _ssl.PROTOCOL_TLSv1
except:
pass
try:
# Updated for python certificate validation
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
except:
pass
import sys
PYTHON_VERSION = sys.version_info[0]
if PYTHON_VERSION == 2:
import cookielib
import urllib2
elif PYTHON_VERSION == 3:
import http.cookiejar as cookielib
import urllib3
import ast
log = logging.getLogger(__name__)
class Cloudflare_DNS(object):
def __init__(self, zone, email, api_key, dns_type, dns_name, content, delete_id):
self.dns_type = dns_type
self.dns_name = dns_name
self.zone = zone
self.email = email
self.api_key = api_key
self.content = content
self.delete_id = delete_id
self.url = 'https://api.cloudflare.com/client/v4/zones/' + self.zone + '/dns_records'
self.headers = {'Content-Type': 'application/json', 'X-Auth-Key': self.api_key, 'X-Auth-Email': self.email}
def get_records(self):
r = requests.get(self.url + '/', headers=self.headers, params={'per_page':1000})
json_data = json.loads(r.text)
return json_data
def create_record(self):
self.payload = {'type': self.dns_type, 'name': self.dns_name, 'content': self.content}
r = requests.post(self.url, data=json.dumps(self.payload), headers=self.headers)
json_data = json.loads(r.text)
try:
if json_data["result"]["id"]:
print "success"
# I store the ID in a database so that I can retrieve it later when I want to delete it
except:
print "fail"
print json_data
def delete_record(self):
r = requests.delete(self.url + '/' + self.delete_id, headers=self.headers)
json_data = json.loads(r.text)
if json_data["success"] == True:
print "success"
else:
print "fail"
print json_data
class APIError(Exception):
pass
class Controller:
"""Interact with a UniFi controller.
Uses the JSON interface on port 8443 (HTTPS) to communicate with a UniFi
controller. Operations will raise unifi.controller.APIError on obvious
problems (such as login failure), but many errors (such as disconnecting a
nonexistant client) will go unreported.
>>> from unifi.controller import Controller
>>> c = Controller('192.168.1.99', 'admin', 'p4ssw0rd')
>>> for ap in c.get_aps():
... print 'AP named %s with MAC %s' % (ap['name'], ap['mac'])
...
AP named Study with MAC dc:9f:db:1a:59:07
AP named Living Room with MAC dc:9f:db:1a:59:08
AP named Garage with MAC dc:9f:db:1a:59:0b
"""
def __init__(self, host, username, password, port=8443, version='v4', site_id='default'):
"""Create a Controller object.
Arguments:
host -- the address of the controller host; IP or name
username -- the username to log in with
password -- the password to log in with
port -- the port of the controller host
version -- the base version of the controller API [v2|v3|v4]
site_id -- the site ID to connect to (UniFi >= 3.x)
"""
self.host = host
self.port = port
self.version = version
self.username = username
self.password = password
self.site_id = site_id
self.url = 'https://' + host + ':' + str(port) + '/'
self.api_url = self.url + self._construct_api_path(version)
log.debug('Controller for %s', self.url)
cj = cookielib.CookieJar()
if PYTHON_VERSION == 2:
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
elif PYTHON_VERSION == 3:
self.opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
self._login(version)
def __del__(self):
if self.opener != None:
self._logout()
def _jsondec(self, data):
if PYTHON_VERSION == 3:
data = data.decode()
obj = json.loads(data)
if 'meta' in obj:
if obj['meta']['rc'] != 'ok':
raise APIError(obj['meta']['msg'])
if 'data' in obj:
return obj['data']
return obj
def _read(self, url, params=None):
if PYTHON_VERSION == 3:
if params is not None:
params = ast.literal_eval(params)
#print (params)
params = urllib.parse.urlencode(params)
params = params.encode('utf-8')
res = self.opener.open(url, params)
else:
res = self.opener.open(url)
elif PYTHON_VERSION == 2:
res = self.opener.open(url, params)
return self._jsondec(res.read())
def _construct_api_path(self, version):
"""Returns valid base API path based on version given
The base API path for the URL is different depending on UniFi server version.
Default returns correct path for latest known stable working versions.
"""
V2_PATH = 'api/'
V3_PATH = 'api/s/' + self.site_id + '/'
if(version == 'v2'):
return V2_PATH
if(version == 'v3'):
return V3_PATH
if(version == 'v4'):
return V3_PATH
else:
return V2_PATH
def _login(self, version):
log.debug('login() as %s', self.username)
params = {'username': self.username, 'password': self.password}
login_url = self.url
if version == 'v4':
login_url += 'api/login'
params = json.dumps(params)
else:
login_url += 'login'
params.update({'login': 'login'})
if PYTHON_VERSION is 2:
params = urllib.urlencode(params)
elif PYTHON_VERSION is 3:
params = urllib.parse.urlencode(params)
if PYTHON_VERSION is 3:
params = params.encode("UTF-8")
time_check = 0
while time_check < 10:
time_check += 1
try:
self.opener.open(login_url, params).read()
except Exception as e:
print e
print login_url
print "trying to log in again"
time.sleep(1)
def _logout(self):
log.debug('logout()')
try:
self.opener.open(self.url + 'logout').read()
except:
print "couldnt log out... oh well"
def get_alerts(self):
"""Return a list of all Alerts."""
return self._read(self.api_url + 'list/alarm')
def get_alerts_unarchived(self):
"""Return a list of Alerts unarchived."""
js = json.dumps({'_sort': '-time', 'archived': False})
params = urllib.urlencode({'json': js})
return self._read(self.api_url + 'list/alarm', params)
def get_statistics_last_24h(self):
"""Returns statistical data of the last 24h"""
return self.get_statistics_24h(time())
def get_statistics_24h(self, endtime):
"""Return statistical data last 24h from time"""
js = json.dumps(
{'attrs': ["bytes", "num_sta", "time"], 'start': int(endtime - 86400) * 1000, 'end': int(endtime - 3600) * 1000})
params = urllib.urlencode({'json': js})
return self._read(self.api_url + 'stat/report/hourly.system', params)
def get_events(self):
"""Return a list of all Events."""
return self._read(self.api_url + 'stat/event')
def get_aps(self):
"""Return a list of all AP:s, with significant information about each."""
#Set test to 0 instead of NULL
params = json.dumps({'_depth': 2, 'test': 0})
return self._read(self.api_url + 'stat/device', params)
def get_clients(self):
"""Return a list of all active clients, with significant information about each."""
return self._read(self.api_url + 'stat/sta')
def get_users(self):
"""Return a list of all known clients, with significant information about each."""
return self._read(self.api_url + 'list/user')
def get_user_groups(self):
"""Return a list of user groups with its rate limiting settings."""
return self._read(self.api_url + 'list/usergroup')
def get_wlan_conf(self):
"""Return a list of configured WLANs with their configuration parameters."""
return self._read(self.api_url + 'list/wlanconf')
def _run_command(self, command, params={}, mgr='sitemgr'):
log.debug('_run_command(%s)', command)
params.update({'cmd': command})
if PYTHON_VERSION == 2:
return self._read(self.api_url + 'cmd/' + mgr, urllib.urlencode({'json': json.dumps(params)}))
elif PYTHON_VERSION == 3:
return self._read(self.api_url + 'cmd/' + mgr, urllib.parse.urlencode({'json': json.dumps(params)}))
def _mac_cmd(self, target_mac, command, mgr='stamgr'):
log.debug('_mac_cmd(%s, %s)', target_mac, command)
params = {'mac': target_mac}
self._run_command(command, params, mgr)
def block_client(self, mac):
"""Add a client to the block list.
Arguments:
mac -- the MAC address of the client to block.
"""
self._mac_cmd(mac, 'block-sta')
def unblock_client(self, mac):
"""
Remove a client from the block list.
Arguments:
mac -- the MAC address of the client to unblock.
"""
self._mac_cmd(mac, 'unblock-sta')
def disconnect_client(self, mac):
"""Disconnect a client.
Disconnects a client, forcing them to reassociate. Useful when the
connection is of bad quality to force a rescan.
Arguments:
mac -- the MAC address of the client to disconnect.
"""
self._mac_cmd(mac, 'kick-sta')
def restart_ap(self, mac):
"""Restart an access point (by MAC).
Arguments:
mac -- the MAC address of the AP to restart.
"""
self._mac_cmd(mac, 'restart', 'devmgr')
def restart_ap_name(self, name):
"""Restart an access point (by name).
Arguments:
name -- the name address of the AP to restart.
"""
if not name:
raise APIError('%s is not a valid name' % str(name))
for ap in self.get_aps():
if ap.get('state', 0) == 1 and ap.get('name', None) == name:
self.restart_ap(ap['mac'])
def archive_all_alerts(self):
"""Archive all Alerts
"""
js = json.dumps({'cmd': 'archive-all-alarms'})
params = urllib.urlencode({'json': js})
answer = self._read(self.api_url + 'cmd/evtmgr', params)
def create_backup(self):
"""Ask controller to create a backup archive file, response contains the path to the backup file.
Warning: This process puts significant load on the controller may
render it partially unresponsive for other requests.
"""
js = json.dumps({'cmd': 'backup'})
params = urllib.urlencode({'json': js})
answer = self._read(self.api_url + 'cmd/system', params)
return answer[0].get('url')
def get_backup(self, target_file='unifi-backup.unf'):
"""Get a backup archive from a controller.
Arguments:
target_file -- Filename or full path to download the backup archive to, should have .unf extension for restore.
"""
download_path = self.create_backup()
opener = self.opener.open(self.url + download_path)
unifi_archive = opener.read()
backupfile = open(target_file, 'w')
backupfile.write(unifi_archive)
backupfile.close()
def authorize_guest(self, guest_mac, minutes, up_bandwidth=None, down_bandwidth=None, byte_quota=None, ap_mac=None):
"""
Authorize a guest based on his MAC address.
Arguments:
guest_mac -- the guest MAC address : aa:bb:cc:dd:ee:ff
minutes -- duration of the authorization in minutes
up_bandwith -- up speed allowed in kbps (optional)
down_bandwith -- down speed allowed in kbps (optional)
byte_quota -- quantity of bytes allowed in MB (optional)
ap_mac -- access point MAC address (UniFi >= 3.x) (optional)
"""
cmd = 'authorize-guest'
js = {'mac': guest_mac, 'minutes': minutes}
if up_bandwidth:
js['up'] = up_bandwidth
if down_bandwidth:
js['down'] = down_bandwidth
if byte_quota:
js['bytes'] = byte_quota
if ap_mac and self.version != 'v2':
js['ap_mac'] = ap_mac
return self._run_command(cmd, params=js)
def unauthorize_guest(self, guest_mac):
"""
Unauthorize a guest based on his MAC address.
Arguments:
guest_mac -- the guest MAC address : aa:bb:cc:dd:ee:ff
"""
cmd = 'unauthorize-guest'
js = {'mac': guest_mac}
return self._run_command(cmd, params=js)
def create_super_admin(self, username, email, password):
cmd = 'create-admin'
js = {"email": email, "name": username, "requires_new_password": "true",
"role": "admin", "x_password": password, "permissions": []}
r = self._run_command(cmd, params=js)
print r
print r[0]["_id"]
admin_id = r[0]["_id"]
cmd = 'grant-super-admin'
js = {"admin": admin_id}
return self._run_command(cmd, params=js)
def get_admins(self):
cmd = 'get-admins'
r = self._run_command(cmd)
return r
def create_site_and_admin(self, desc, username, email, password):
cmd = 'add-site'
js = {"desc": desc}
r = self._run_command(cmd, params=js)
print r
print r[0]["_id"]
site_id = r[0]["_id"]
site_name = r[0]["name"]
site_list = [site_id, site_name]
cmd = 'create-admin'
js = {"email": email, "name": username, "requires_new_password": True,
"role": "admin", "x_password": password, "permissions": ["API_DEVICE_ADOPT", "API_DEVICE_RESTART"]}
log.debug('_run_command(%s)', cmd)
js.update({'cmd': cmd})
time_check = 0
while time_check < 30:
time_check += 1
try:
this_url = self.url + 'api/s/' + site_name + '/cmd/sitemgr'
print this_url
print json.dumps(js)
res = self._read(this_url, urllib.urlencode({'json': json.dumps(js)}))
time.sleep(1)
print res
break
except Exception as e:
print e
print "failed to load admin creation page"
time.sleep(1)
data = res
admin_id = data[0]["_id"]
cmd = 'grant-super-admin'
print admin_id
print "ADMIN ID !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
js = {"admin": admin_id,"role":"nobody","permissions":["API_STAT_DEVICE_ACCESS_SUPER_SITE_PENDING"]}
log.debug('_run_command(%s)', cmd)
js.update({'cmd': cmd})
time_check = 0
while time_check < 10:
time.sleep(1)
time_check += 1
try:
this_url = self.url + 'api/s/' + site_name + '/cmd/sitemgr'
print this_url
print json.dumps(js)
res = self._read(this_url, urllib.urlencode({'json': json.dumps(js)}))
print res
return site_list
break
except Exception as e:
print e
print "failed to load admin creation page"
time.sleep(1)
def delete_admin(self, admin_id):
cmd = 'revoke-admin'
js = {"admin": admin_id}
r = self._run_command(cmd, params=js)
return r
def delete_site(self, site_id):
cmd = 'delete-site'
js = {"site": site_id}
r = self._run_command(cmd, params=js)
return r
try:
# Open database connection
db = MySQLdb.connect("localhost","redacted","redacted","redacted" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
###
### Begin creating new packages:
###
sql = "SELECT * FROM vultr_check"
vultr_check = []
try:
# Execute the SQL command
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
this_list = []
id_no = int(row[0])
customer_id = int(row[1])
product_id = int(row[2])
status = str(row[3])
wp_edd_sub_id = int(row[4])
server_ip = row[5]
server_name = row[6]
admin_pw = row[7]
site_id = row[8]
site_name = row[9]
zabbix_host_id = row[15]
this_list.append(id_no)
this_list.append(customer_id)
this_list.append(product_id)
this_list.append(status)
this_list.append(wp_edd_sub_id)
this_list.append(server_ip)
this_list.append(server_name)
this_list.append(admin_pw)
this_list.append(site_id)
this_list.append(site_name)
this_list.append(zabbix_host_id)
vultr_check.append(this_list)
except Exception as e:
print "Error: " + str(e)
print vultr_check
sql = "SELECT * FROM wp_edd_subscriptions where status = 'active'"
wp_edd_subscriptions = []
try:
# Execute the SQL command
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
this_list = []
id_no = int(row[0])
customer_id = int(row[1])
product_id = int(row[8])
this_list.append(id_no)
this_list.append(customer_id)
this_list.append(product_id)
wp_edd_subscriptions.append(this_list)
except Exception as e:
print "Error: " + str(e)
for active_sub in wp_edd_subscriptions:
end_flag = 0
for vultr_created in vultr_check:
if active_sub[0] == vultr_created[4]:
print active_sub
print "Already built!"
# This particular subscription has already been built, so skip it
end_flag = 1
break
if end_flag != 1:
# If the subscription has not already been built, do this:
# Check to see what type of sub it is, if it is a multi-site then build it, else if it is a micro/single, check it:
if active_sub[2] == 5948:
# Build a new UniFi Video server
print "Building a server for "
print active_sub
# Get number to append to hostname aka v0xxx.hostifi.net
sql = "SELECT * FROM vultr_options where id = 1"
try:
# Execute the SQL command
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
last_vps_no = int(row[3])
except Exception as e:
print "Error: " + str(e)
vps_no = last_vps_no + 1
server_name = "v0" + str(vps_no)
# Now update VPS number to +=1
sql = "UPDATE vultr_options SET last_vps_number = last_vps_number + 1 WHERE id = 1"
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# Vultr - create new Debian 9 server
url = 'https://api.vultr.com/v1/server/create'
payload = {'hostname': server_name + '.hostifi.net', 'label': server_name + '.hostifi.net', 'DCID': '1',
'VPSPLANID': 'redacted', 'OSID': '244',
'SSHKEYID': 'redacted,redacted'}
r = requests.post(url, data=payload, headers={"API-Key": "redacted"})
print r.text
print r.status_code
json_obj = json.loads(r.text)
subid = json_obj["SUBID"]
time_check = 0
server_success = 0
# Checking if setup was successful
while time_check < 500:
time_check += 1
url = 'https://api.vultr.com/v1/server/list'
r = requests.get(url, headers={"API-Key": "redacted"})
json_obj = json.loads(r.text)
if json_obj[subid]:
print r.text
server_success = 1
break
else:
time.sleep(1)
if server_success == 1:
print "Server setup successfully"
else:
print "Server setup failed for " + str(subid)
time_check = 0
server_status = 0
# Checking if server has finished being provisioned
while time_check < 500:
time_check += 1
url = 'https://api.vultr.com/v1/server/list'
r = requests.get(url, headers={"API-Key": "redacted"})
json_obj = json.loads(r.text)
print json_obj[subid]["status"]
if json_obj[subid]["status"] == "active":
print r.text
server_status = 1
break
else:
time.sleep(1)
if server_status == 1:
print "Server is running"
else:
print "Server never started running for " + str(subid)
# Sleep for a bit just to make sure the server is really done setting up before SSHing in
time.sleep(60)
# Get IP of our new server
url = 'https://api.vultr.com/v1/server/list'
r = requests.get(url, headers={"API-Key": "redacted"})
json_obj = json.loads(r.text)
print json_obj
server_ip = json_obj[subid]["main_ip"]
# Set A record at Cloudflare
zone_id = 'redacted'
account_email = 'redacted'
account_api = 'redacted'
cf = Cloudflare_DNS(zone_id, account_email, account_api, "A", server_name + ".hostifi.net", server_ip,
'this-doesnt-matter-but-must-be-set')
r = cf.create_record()
# SSH in and install UniFi Controller
k = paramiko.RSAKey.from_private_key_file("redacted", password="redacted")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
times_tried = 0
while times_tried < 10:
try:
c.connect(hostname=server_ip, username="root", pkey=k)
break
except Exception as e:
print e
time.sleep(3)
times_tried += 1
print "Try again .."
log_file = "/var/log/unifi/unifi_lets_encrypt.log"
domain = server_name + ".hostifi.net"
domain_prefix = server_name
script_name = "unifi-video-ssl.sh"
unifi_install_dir = "/var/lib/unifi"
num_digits = 32
myhex = os.urandom(num_digits / 2).encode('hex')
print "PSK:"
print myhex
commands = [
'wget https://dl.ubnt.com/firmwares/ufv/v3.9.9/unifi-video.Debian7_amd64.v3.9.9.deb', 'dpkg -i unifi-video.Debian7_amd64.v3.9.9.deb', 'apt --fix-broken install -y',
"apt-get update -y", "apt-get install ncdu -y",
"apt-get upgrade -y", 'apt --fix-broken install -y', 'domain=' + server_name + ".hostifi.net",
'touch /var/swap.img', 'chmod 600 /var/swap.img', 'dd if=/dev/zero of=/var/swap.img bs=1024k count=1024', 'mkswap /var/swap.img', 'swapon /var/swap.img',
'echo "/var/swap.img none swap sw 0 0" >> /etc/fstab', 'apt-get install -y apache2', 'echo "deb http://ftp.debian.org/debian stretch-backports main" | tee -a /etc/apt/sources.list',
'apt-get update -y', 'apt-get install python-certbot-apache -t stretch-backports -y', 'certbot --apache --email [email protected] --agree-tos --no-eff-email --domain ' + server_name + ".hostifi.net" + ' --no-redirect',
'crontab -l | { cat; echo "0 4 * * * /usr/bin/certbot renew"; } | crontab -', "update-rc.d apache2 disable", "service apache2 stop",
'echo "ufv.custom.certs.enable=true" >> /var/lib/unifi-video/system.properties',"""cat <<EOM >/root/unifi-video-ssl.sh #!/bin/bash
service unifi-video stop
openssl pkcs12 -export -in /etc/letsencrypt/live/""" + domain + """/fullchain.pem -inkey /etc/letsencrypt/live/""" + domain + """/privkey.pem -out /etc/letsencrypt/live/""" + domain + """/cert_and_key.p12 -name newcert -CAfile /etc/letsencrypt/live/""" + domain + """/chain.pem -caname root -password pass:ubiquiti;
keytool -importkeystore -destkeystore /var/lib/unifi-video/keystore -deststorepass ubiquiti -srckeystore /etc/letsencrypt/live/""" + domain + """/cert_and_key.p12 -srcstorepass ubiquiti -srcstoretype PKCS12
keytool -delete -keystore /var/lib/unifi-video/keystore -storepass ubiquiti -alias airvision
keytool -changealias -keystore /var/lib/unifi-video/keystore -storepass ubiquiti -alias newcert -destalias airvision
service unifi-video restart
EOM""", "chmod +x /root/unifi-video-ssl.sh", "/bin/bash /root/unifi-video-ssl.sh", "apt-get install zabbix-agent -y", 'echo "Hostname=' + domain + '" > /etc/zabbix/zabbix_agentd.conf',
'echo "LogFileSize=10" >> /etc/zabbix/zabbix_agentd.conf', 'crontab -l | { cat; echo "0 4 * * * /bin/bash /root/unifi-video-ssl.sh"; } | crontab -', 'echo "LogFile=/var/log/zabbix-agent/zabbix_agentd.log" >> /etc/zabbix/zabbix_agentd.conf', 'echo "PidFile=/var/run/zabbix/zabbix_agentd.pid" >> /etc/zabbix/zabbix_agentd.conf', 'echo "ServerActive=zabbix.locklinnetworks.com" >> /etc/zabbix/zabbix_agentd.conf', 'echo "Server=127.0.0.1,zabbix.locklinnetworks.com" >> /etc/zabbix/zabbix_agentd.conf', 'echo "TLSConnect=psk" >> /etc/zabbix/zabbix_agentd.conf', 'echo "TLSAccept=psk" >> /etc/zabbix/zabbix_agentd.conf', 'echo "TLSPSKIdentity=' + domain_prefix + '-psk01" >> /etc/zabbix/zabbix_agentd.conf', 'echo "TLSPSKFile=/etc/zabbix/zabbix_agentd.psk" >> /etc/zabbix/zabbix_agentd.conf', 'echo "' + myhex + '" >> /etc/zabbix/zabbix_agentd.psk', 'systemctl start zabbix-agent',
'systemctl enable zabbix-agent', 'reboot']
time.sleep(5)
for command in commands:
time.sleep(1)
print command
print "Executing {}".format(command)
stdin, stdout, stderr = c.exec_command(command)
print stdout.read()
print "Errors"
print stderr.read()
c.close()
unifi_status = 0
time_check = 0
# Sleep while UniFi Video finishes installing
while time_check < 500:
try:
url = 'https://' + server_ip + ':7443'
r = requests.get(url, verify=False)
print r.status_code
if r.status_code == 200:
if "starting up" not in r.text:
print r.text
print r.status_code
unifi_status = 1
break
else:
time.sleep(1)
time_check += 1
else:
print "waiting"
time_check += 1
time.sleep(1)
except Exception as e:
print e
print "Failed to load"
time.sleep(1)
if unifi_status == 1:
print "UniFi Video installed successfully"
else:
print "UniFi Video install failed"
time.sleep(30)
# Kill the wizard
time_check = 0
headers = {'content-type':'application/json'}
session = requests.Session()
# Create super admin for the user
# Get username and email address for this subscription:
customer_id = active_sub[1]
# Get WP user id
sql = "SELECT * FROM wp_edd_customers where id = %s"
try:
# Execute the SQL command
cursor.execute(sql, [customer_id])
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
wp_user_id = row[1]
except Exception as e:
print "Error: " + str(e)
user_id = wp_user_id
# Get Stripe customer id
sql = "SELECT * FROM wp_edd_customermeta where customer_id = %s"
is_broken = 0
try:
# Execute the SQL command
cursor.execute(sql, [customer_id])
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
print "ROW @@@@@@@@@@@@@@@@@@@"
print row
if "cus" in row[3]:
customer_email_id = row[3]
else:
print "something broke here !"
continue
except Exception as e:
print "Error: " + str(e)
if is_broken == 1:
continue
if live_mode == True:
stripe.api_key = "redacted"
else:
stripe.api_key = "redacted"
try:
wp_email = stripe.Customer.retrieve(customer_email_id)["email"]
except:
# Get Stripe customer id
sql = "SELECT * FROM wp_users where id = %s"
is_broken = 0
# Execute the SQL command
cursor.execute(sql, [user_id])
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
print "ROW @@@@@@@@@@@@@@@@@@@"
print row
wp_email = row[4]
print wp_email
if not wp_email:
wp_email = "[email protected]"
# Get WP user id
sql = "SELECT * FROM wp_edd_customers where id = %s"
try:
# Execute the SQL command
cursor.execute(sql, [customer_id])
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
wp_user_id = row[1]
except Exception as e:
print "Error: " + str(e)
# Get WP username
sql = "SELECT * FROM wp_users where id = %s"
try:
# Execute the SQL command
cursor.execute(sql, [wp_user_id])
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
wp_username = row[3]
wp_username = re.sub(r'\W+', '', wp_username)
wp_username = re.sub(r'_', '', wp_username)
# Truncate to 20 charz
wp_username = (wp_username[:20]) if len(wp_username) > 20 else wp_username
except Exception as e:
print "Error: " + str(e)
unifi_pw = pw_gen()
print "made it here"
print wp_username
print unifi_pw
while time_check < 500:
try:
url = 'https://' + server_ip + ':7443/api/2.0/wizard'
payload = {"mode":"MASTER","systemName":"NVR","language":"English","timezone":"America/New_York","name": wp_username,"username": wp_username,"email": wp_email, "password": unifi_pw,"cameraPassword":""}
print payload
print "payload^"
# POST with JSON
r = session.post(url, data=json.dumps(payload), headers=headers, verify=False)
# Response, status etc
if r.status_code == 200:
if "starting up" not in r.text:
print r.text
print r.status_code
break
else:
print "sleeping 1 zxzx"
time.sleep(1)
time_check += 1
else:
print "sleeping 1"
print r.text
print r.status_code
time.sleep(1)
time_check += 1
except:
time_check += 1
print "Failed to kill the wizard"
time.sleep(1)
time.sleep(30)
# Login
time_check = 0
while time_check < 500:
time_check += 1
try:
url = 'https://' + server_ip + ':7443/api/2.0/login'
payload = {"email": wp_email,"password": unifi_pw}
# POST with JSON
r = session.post(url, data=json.dumps(payload), headers=headers, verify=False)
# Response, status etc
if r.status_code == 200:
print r.text
print r.status_code
break
else:
print "sleeping xxx +1"
time_check +=1
time.sleep(1)
except:
print "Failed"
time.sleep(1)
time.sleep(1)
# Get "bootstrap" settings
time_check = 0
while time_check < 500:
time_check += 1
try:
url = 'https://' + server_ip + ':7443/api/2.0/bootstrap'
# POST with JSON
r = session.get(url, headers=headers, verify=False)
# Response, status etc
if r.status_code == 200:
print "Bootstrap info: "
print r.text
print r.status_code
json_data = r.json()
print "server id"
server_id = json_data["data"][0]["settings"]["_id"]
print server_id
print "admin id"
admin_id = json_data["data"][0]["adminUserGroupId"]
print admin_id
break
else:
time.sleep(1)
time_check += 1
except:
print "Failed to load bootstrap"
time.sleep(1)