cli.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import argparse
  2. from ocma import connect
  3. def run() -> None:
  4. parser = argparse.ArgumentParser(description="openconnect-microsoft-authenticator")
  5. # add argument
  6. parser.add_argument(
  7. "-u",
  8. "--username",
  9. metavar="username",
  10. type=str,
  11. help="MS Account username",
  12. required=True,
  13. )
  14. parser.add_argument(
  15. "-p",
  16. "--password",
  17. metavar="password",
  18. type=str,
  19. help="MS Account password",
  20. required=True,
  21. )
  22. parser.add_argument(
  23. "-m",
  24. "--mfa",
  25. metavar="secret",
  26. type=str,
  27. help="TOTP secret. Required, if you have set up 2FA with your MS account (only TOTP)",
  28. required=False,
  29. )
  30. parser.add_argument(
  31. "--vpn_url",
  32. nargs="?",
  33. metavar="url",
  34. type=str,
  35. help="Login URL",
  36. default="https://vpn.fhnw.ch",
  37. )
  38. parser.add_argument(
  39. "--show-head",
  40. action="store_false",
  41. help="If the browser window should be shown during the authentication process",
  42. )
  43. parser.add_argument(
  44. "--print-to-stdout",
  45. action="store_true",
  46. help="""If the vpn host and cookie should be printed to the stdout. To be used like:\n
  47. \n
  48. eval $( python ocma/cli.py -u [username] -p [password] --print-to-stdout ); \n
  49. [ -n $VPN_COOKIE ] && echo $VPN_COOKIE | sudo openconnect --cookie-on-stdin $VPN_HOST
  50. """,
  51. )
  52. # parse the arguments from standard input
  53. args = parser.parse_args()
  54. username: str = args.username
  55. password: str = args.password
  56. mfa_secret: str = args.mfa
  57. vpn_url: str = args.vpn_url
  58. headless: bool = args.show_head
  59. print_to_stdout: bool = args.print_to_stdout
  60. if username is None or password is None:
  61. raise ValueError("Username and password must be specified!")
  62. if mfa_secret is not None:
  63. try:
  64. connect.get_mfa_code(mfa_secret)
  65. except ValueError as e:
  66. raise ValueError(f"Your MFA secret '{mfa_secret}' is invalid!") from e
  67. cookie = connect.login(
  68. username=username,
  69. password=password,
  70. mfa_secret=mfa_secret,
  71. vpn_site=vpn_url,
  72. headless=headless,
  73. )
  74. if print_to_stdout:
  75. print(f"VPN_HOST={cookie.domain}")
  76. print(f"VPN_COOKIE={cookie.cookie}")
  77. if __name__ == "__main__":
  78. run()