summaryrefslogtreecommitdiff
path: root/openvpn_otp.py
blob: f673c8fe1c4f861f52e190d70447f05ee1ed83d5 (about) (plain)
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
#!/usr/bin/env python3

"""OpenVPN wrapper with OTP authentication."""

import os
import sys
from pathlib import Path

import mintotp
import pexpect


def main():
    """Entrypoint."""
    child = pexpect.spawn(f"openvpn --config {os.environ['OPENVPN_CONFIG_FILE']}")
    child.logfile = sys.stdout.buffer
    child.expect("CHALLENGE: Verification code:")
    child.sendline(
        mintotp.totp(Path(os.environ["OPENVPN_OTP_SECRET_FILE"]).read_text().strip())
    )
    # macos - python script: pexpect hangs on child.wait()? - Stack Overflow
    # https://stackoverflow.com/questions/58751357/python-script-pexpect-hangs-on-child-wait
    while True:
        try:
            child.read_nonblocking()
        except Exception:
            break
    if child.isalive():
        child.wait()


if __name__ == "__main__":
    main()