File: set_sysctls.py

package info (click to toggle)
linux 6.12.8-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,673,568 kB
  • sloc: ansic: 25,888,630; asm: 268,782; sh: 136,481; python: 64,809; makefile: 55,668; perl: 38,052; xml: 19,270; cpp: 5,893; yacc: 4,923; lex: 2,939; awk: 1,592; sed: 28; ruby: 25
file content (38 lines) | stat: -rwxr-xr-x 1,235 bytes parent folder | download | duplicates (18)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0

"""Sets sysctl values and writes a file that restores them.

The arguments are of the form "<proc-file>=<val>" separated by spaces.
The program first reads the current value of the proc-file and creates
a shell script named "/tmp/sysctl_restore_${PACKETDRILL_PID}.sh" which
restores the values when executed. It then sets the new values.

PACKETDRILL_PID is set by packetdrill to the pid of itself, so a .pkt
file could restore sysctls by running `/tmp/sysctl_restore_${PPID}.sh`
at the end.
"""

import os
import subprocess
import sys

filename = '/tmp/sysctl_restore_%s.sh' % os.environ['PACKETDRILL_PID']

# Open file for restoring sysctl values
restore_file = open(filename, 'w')
print('#!/bin/bash', file=restore_file)

for a in sys.argv[1:]:
  sysctl = a.split('=')
  # sysctl[0] contains the proc-file name, sysctl[1] the new value

  # read current value and add restore command to file
  cur_val = subprocess.check_output(['cat', sysctl[0]], universal_newlines=True)
  print('echo "%s" > %s' % (cur_val.strip(), sysctl[0]), file=restore_file)

  # set new value
  cmd = 'echo "%s" > %s' % (sysctl[1], sysctl[0])
  os.system(cmd)

os.system('chmod u+x %s' % filename)