In the previous article, we talked about how to write a daemon in Python on Linux. The main principle is to use the Linux fork function to create a process, and then exit the parent process to run, the resulting child process will become a daemon. Careful observation may find that the daemon's running identity is the user who executes the program, and if the daemon is added to the system's service item, the daemon's execution identity should be root.
A situation appears, root permissions are relatively large, if through this root identity daemon to operate, the risk is relatively large. A good idea is to generate a master process with an identity of root to accept requests and generate several Woker processes to process requests so that there is no problem with the permissions being too large. In fact, a lot of software, nginx,mysql,apache,vsftpd and so on, are almost always doing this.
So how do you change the running identity of a subprocess in Linux? , actually Linux provides such a function to take a look at the Python code:
#!/usr/bin/env python import time,os,pwd,sys,signal logfile= "/tmp/d2.log" #step one, get t He username your want to running with Try:user=sys.argv[1] except:user=raw_input (' Please input a username in this Machine you want to run this program: ') If user== "": Sys.exit ( -1) try:uid=pwd.getpwnam (user) Uid=uid.pw_uid Exce
Pt:print "Uer not exists!" Sys.exit ( -1) #step two:generation of Daemon pid=os.fork () if (PID): Sys.exit (0) Os.setsid () Os.chdir ("/") Os.umask (0) # Step Three:fork again Pid=os.fork () if (pid==0): Os.setuid (UID) os.setsid () Os.chdir ("/") Os.umask (0) log=
Open (LogFile, ' a ') log.write (' Daemon start up at%s\n '% (time.strftime ('%y:%m:%d ', Time.localtime (Time.time ()))) Log.close () def reload (a,b): Log=open (logfile, ' a ') log.write (' Daemon reload at%s\n '% (' time.strftime ',%y:%m:%d Ocaltime (Time.time ()))) Log.close () while True:signal.signal (signal. Sighup,reload) Time.sleep (2)
Run this program, enter Nginx (Nginx for users already added to the system), and then use PS Aux|grep python to view the Python programs running in the system, and you can see that the identity of a woker process has changed to be nginx:
[Root@home ~]# ps aux|grep python
root 1139 0.0 0.5-5288 ? Ss 22:40 0:00 python./d2.py nginx
nginx 1140 0.0 0.5 5288? S 22:40 0:00 python./d2.py nginx
Root 1151 0.0 0.1 2336 648 pts/0 s+ 22:50 0:00 grep python
Because the identity of the nginx process is used to process the request, then some of the rights belong to the root will not be called by the process, you can set the permissions of the file, the process to operate a single file limit, to achieve better control of the effect of authority to reduce security risks.