set_sysctls.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: GPL-2.0
  3. """Sets sysctl values and writes a file that restores them.
  4. The arguments are of the form "<proc-file>=<val>" separated by spaces.
  5. The program first reads the current value of the proc-file and creates
  6. a shell script named "/tmp/sysctl_restore_${PACKETDRILL_PID}.sh" which
  7. restores the values when executed. It then sets the new values.
  8. PACKETDRILL_PID is set by packetdrill to the pid of itself, so a .pkt
  9. file could restore sysctls by running `/tmp/sysctl_restore_${PPID}.sh`
  10. at the end.
  11. """
  12. import os
  13. import subprocess
  14. import sys
  15. filename = '/tmp/sysctl_restore_%s.sh' % os.environ['PACKETDRILL_PID']
  16. # Open file for restoring sysctl values
  17. restore_file = open(filename, 'w')
  18. print('#!/bin/bash', file=restore_file)
  19. for a in sys.argv[1:]:
  20. sysctl = a.split('=')
  21. # sysctl[0] contains the proc-file name, sysctl[1] the new value
  22. # read current value and add restore command to file
  23. cur_val = subprocess.check_output(['cat', sysctl[0]], universal_newlines=True)
  24. print('echo "%s" > %s' % (cur_val.strip(), sysctl[0]), file=restore_file)
  25. # set new value
  26. cmd = 'echo "%s" > %s' % (sysctl[1], sysctl[0])
  27. os.system(cmd)
  28. os.system('chmod u+x %s' % filename)