|
Revision 9397, 1.5 kB
(checked in by haypo, 22 months ago)
|
|
conntrack.py: create checkKernelModule() to load missing kernel modules if needed
|
-
Property svn:eol-style set to
native
-
Property svn:executable set to
*
|
| Line | |
|---|
| 1 | |
|---|
| 2 | |
|---|
| 3 | from pynetfilter_conntrack import Conntrack, NFCT_O_DEFAULT, NFCT_O_XML |
|---|
| 4 | from socket import AF_INET |
|---|
| 5 | import sys |
|---|
| 6 | |
|---|
| 7 | OUTPUT_FORMAT = { |
|---|
| 8 | "list": NFCT_O_DEFAULT, |
|---|
| 9 | "xml": NFCT_O_XML, |
|---|
| 10 | } |
|---|
| 11 | |
|---|
| 12 | def checkKernelModule(module_name, symbol): |
|---|
| 13 | allsyms = open('/proc/kallsyms') |
|---|
| 14 | try: |
|---|
| 15 | for line in allsyms: |
|---|
| 16 | if symbol in line: |
|---|
| 17 | print "Module %s is loaded: symbol %r is present" % (module_name, symbol) |
|---|
| 18 | return |
|---|
| 19 | finally: |
|---|
| 20 | allsyms.close() |
|---|
| 21 | print "Load kernel module %s" % module_name |
|---|
| 22 | exitcode = system('modprobe %s' % module_name) |
|---|
| 23 | if exitcode: |
|---|
| 24 | raise RuntimeError("modprobe error (exit code %s)" % exitcode) |
|---|
| 25 | |
|---|
| 26 | def main(): |
|---|
| 27 | if len(sys.argv) != 2 or sys.argv[1] not in OUTPUT_FORMAT: |
|---|
| 28 | print >>sys.stderr, "usage: %s command" % sys.argv[0] |
|---|
| 29 | print >>sys.stderr |
|---|
| 30 | print >>sys.stderr, "command: list or xml" |
|---|
| 31 | sys.exit(1) |
|---|
| 32 | mode = sys.argv[1] |
|---|
| 33 | output = OUTPUT_FORMAT[mode] |
|---|
| 34 | |
|---|
| 35 | checkKernelModule('nf_conntrack', 'nf_ct_cache') |
|---|
| 36 | checkKernelModule('nf_conntrack_netlink', 'ctnetlink_init') |
|---|
| 37 | try: |
|---|
| 38 | if mode == "xml": |
|---|
| 39 | print '<?xml version="1.0" encoding="ISO-8859-1"?>' |
|---|
| 40 | print '<flows>' |
|---|
| 41 | nf = Conntrack() |
|---|
| 42 | table = nf.dump_table(AF_INET) |
|---|
| 43 | for entry in table: |
|---|
| 44 | print entry.format(output) |
|---|
| 45 | if mode == "xml": |
|---|
| 46 | print '</flows>' |
|---|
| 47 | except RuntimeError, err: |
|---|
| 48 | print "ERROR: %s" % err |
|---|
| 49 | except KeyboardInterrupt: |
|---|
| 50 | print "Interrupted." |
|---|
| 51 | |
|---|
| 52 | if __name__ == "__main__": |
|---|
| 53 | main() |
|---|