1#!/usr/bin/env python3

2

3 import os

4 import re

5 import sys

6 import time

7 import subprocess

8 from datetime import datetime

9

10 try:

11 from subprocess import DEVNULL # >= python3.3

12 except ImportError:

13 DEVNULL = open(os.devnull, "wb")

14

15 IFACE = None

16 TIMEOUT = 30

17

18

19 def main():

20 """

21 Check the time needed to reconnect an active WIFI connection

22 """

23 devices = subprocess.getoutput("nmcli dev")

24 match = re.search(r"(\w+)\s+(802-11-wireless|wifi)\s+connected", devices)

25 if match:

26 IFACE = match.group(1)

27 else:

28 print("No active wifi connection detected", file=sys.stderr)

29 return 1

30

31 try:

32 dev_status = subprocess.check_output(

33 ["nmcli", "-t", "-f", "devices,uuid", "con", "status"],

34 stderr=DEVNULL,

35 universal_newlines=True,

36 )

37 except subprocess.CalledProcessError:

38 dev_status = subprocess.check_output(

39 ["nmcli", "-t", "-f", "device,uuid", "con", "show"],

40 stderr=DEVNULL,

41 universal_newlines=True,

42 )

43 match = re.search(IFACE + ":(.*)", dev_status)

44 uuid = None

45 if match:

46 uuid = match.group(1)

47 else:

48 return 1

49

50 subprocess.call(

51 "nmcli dev disconnect iface %s" % IFACE,

52 stdout=open(os.devnull, "w"),

53 stderr=subprocess.STDOUT,

54 shell=True,

55 )

56

57 time.sleep(2)

58 start = datetime.now()

59

60 subprocess.call(

61 "nmcli con up uuid %s --timeout %s" % (uuid, TIMEOUT),

62 stdout=open(os.devnull, "w"),

63 stderr=subprocess.STDOUT,

64 shell=True,

65 )

66

67 delta = datetime.now() - start

68 print("%.2f Seconds" % delta.total_seconds())

69 return 0

70

71

72 if __name__ == "__main__":

73 sys.exit(main())