Last Updated: February 25, 2016
·
10.73K
· pilt

Increase open files limit and drop privileges in Python

setlimit.py:

import resource
import subprocess
import os
import pwd

print "getrlimit before:", resource.getrlimit(resource.RLIMIT_NOFILE)
resource.setrlimit(resource.RLIMIT_NOFILE, (131072, 131072))
print "getrlimit:", resource.getrlimit(resource.RLIMIT_NOFILE)
print "subprocess:", subprocess.check_output("whoami; ulimit -n", shell=True)

user = "someuser"
pwnam = pwd.getpwnam(user)
os.setgid(pwnam.pw_gid)
os.setuid(pwnam.pw_uid)
print "getrlimit:", resource.getrlimit(resource.RLIMIT_NOFILE)
print "subprocess:", subprocess.check_output("whoami; ulimit -n", shell=True)

Output:

$ sudo python setlimit.py 
getrlimit before: (1024, 4096)
getrlimit: (131072, 131072)
subprocess: root
131072

getrlimit: (131072, 131072)
subprocess: someuser
131072