Ticket #284: ovpn-management-sanitized

File ovpn-management-sanitized, 1.2 KB (added by lavacano201014, 4 years ago)

lavacano-ovpn-management.py

Line 
1#!/usr/bin/env python3
2# vim: ft=python :
3
4import datetime
5import re
6import sys
7import telnetlib
8import time
9import traceback
10
11def retry_telnet_obj():
12    try:
13        return telnetlib.Telnet("localhost", 5194)
14    except ConnectionRefusedError:
15        time.sleep(5)
16        return retry_telnet_obj()
17
18tel = retry_telnet_obj()
19
20def management_loop():
21    should_die = False
22    while not should_die:
23        try:
24            result = tel.expect([b">HOLD:Waiting"])
25            if result[0] != -1:
26                print(datetime.datetime.now().strftime("%H:%M"), "openvpn is waiting on a hold release")
27                raise Exception("Replace this line with whatever you need to run as pre-connect code (use subprocess.call() to run external programs)")
28                tel.write(b"hold release\n")
29                print(datetime.datetime.now().strftime("%H:%M"), "right, off you go")
30        except Exception as err:
31            if not isinstance(err, EOFError):
32                traceback.print_exception(err)
33            should_die = True
34
35try:
36    while True:
37        management_loop()
38        tel.close()
39        tel = retry_telnet_obj()
40except KeyboardInterrupt:
41    tel.close()
42    sys.exit()