1#!/usr/bin/env python3

2# Copyright 2015-2020 Canonical Ltd.

3# All rights reserved.

4#

5# Written by:

6# Authors: Jonathan Cave <jonathan.cave@canonical.com>

7

8"""

9 Script to test if a module is loaded in the running kernel. If not the

10 module will be loaded. This can be disabled using a flag.

11"""

12

13 import argparse

14 import subprocess

15

16

17 class ModuleLoadedTest:

18 """Check if a kernel module is loaded. If not load it."""

19

20 def main(self):

21 parser = argparse.ArgumentParser()

22 parser.add_argument("module", help="Specify the module to test for.")

23 parser.add_argument(

24 "-n",

25 "--no-load",

26 action="store_true",

27 help=("Don't try and load the module just test."),

28 )

29 args = parser.parse_args()

30

31 if self.is_module_loaded(args.module):

32 return

33

34 # module not loaded

35 if args.no_load:

36 raise SystemExit(

37 "ERROR: module {} not loaded in running"

38 " kernel".format(args.module)

39 )

40

41 # attempt a load of the module

42 if not self.load_module(args.module):

43 raise SystemExit(

44 "ERROR: attempt to load module {} failed".format(args.module)

45 )

46

47 def is_module_loaded(self, module):

48 with open("/proc/modules", "r") as modules:

49 for line in modules:

50 if line.split(" ")[0] == module:

51 print("Found kernel module {}".format(module))

52 return True

53 print("Couldn't find kernel module {}".format(module))

54 return False

55

56 def load_module(self, module):

57 if subprocess.call(["modprobe", module]) == 0:

58 print("Module {} was loaded".format(module))

59 return True

60 print("Module {} failed to load".format(module))

61 return False

62

63

64 if __name__ == "__main__":

65 ModuleLoadedTest().main()