1#!/usr/bin/env python3

2# Copyright 2018 Canonical Ltd.

3# All rights reserved.

4#

5# Written by:

6# Maciej Kisielewski <maciej.kisielewski@canonical.com>

7"""

8 Detect insertion of a new network interface.

9"""

10

11 from pathlib import Path

12 import time

13

14

15 def get_ifaces():

16 return set([i.name for i in Path("/sys/class/net").iterdir()])

17

18

19 def main():

20 print("INSERT NOW")

21 starting_ifaces = get_ifaces()

22 attempts = 20

23 while attempts > 0:

24 now_ifaces = get_ifaces()

25 # check if something disappeared

26 if not starting_ifaces == now_ifaces & starting_ifaces:

27 raise SystemExit(

28 "Interface(s) disappeared: {}".format(

29 ", ".join(list(starting_ifaces - now_ifaces))

30 )

31 )

32 new_ifaces = now_ifaces - starting_ifaces

33 if new_ifaces:

34 print()

35 print(

36 "New interface(s) detected: {}".format(

37 ", ".join(list(new_ifaces))

38 )

39 )

40 return

41 time.sleep(1)

42 print(".", end="", flush=True)

43 attempts -= 1

44 print()

45 raise SystemExit("Failed to detect new network interface")

46

47

48 if __name__ == "__main__":

49 main()