Using a Python socket Management Server

Source: Internet
Author: User

I. Socketserver handle method to process requests

Two. Handle method for instantiating Socketserver

Def funzionedemo (): Server = Threadingserver ((host,port), Handler) Server.serve_forever ()

Three. Create the daemon process

Os.setsid () #该方法做一系列的事: First it makes the process the leader of a new session, and then it transforms the process into the leader of the group of the next process, and finally the process no longer controls the terminal, and when it runs, a process is created and Linux allocates a process number. Then call Os.fork () to create the child process. If Pid>0 is himself, commit suicide. The child process skips the IF statement and becomes a terminal-independent process in Linux via Os.setsid () (not responding to sigint,sighup, etc.)
The role of Umask: #默认情况下的umask值是022 (can be viewed with the umask command), at this time you establish the default permissions of the file is 644 (6-0,6-2,6-2), the default permissions for the established directory is 755 (7-0,7-2,7-2), you can use LS- L Verify it. Now you should know the purpose of umask, it is to control the default permissions, do not make the default files and directories have a full set of

Def createdaemon ():     #脱离父进程     try:         pid = os.fork ()         if pid  > 0:            os._exit (0)      except OSError,error:        print  "fork   #1  failed: %d  (%s)  %  (error.errno, error.strerror)          os._exit (1)      #修改当前的工作目录     os.chdir ('/ ')      #脱离终端     os.setsid ()      #重设文件创建权限      os.umask (0)      #第二次创建进程, disable process reopen terminal file     try:         pid = os.fork ()          if pid > 0:            print  ' Daemon PID %d '  % pid            os._exit (0)      except OSError,error:        print  "fork   #1  failed: %d  (%s)  %  (error.errno, error.strerror)          os._exit (1)     funzionedemo ()

Add:

The script runs on the server and is managed using supervisor to run in the background.

Install supervisor on the server (CENTOS6), and then add the configuration in/etc/supervisor.conf:

[Program:app-monitor]command = Python/root/monitor/app_monitor.pydirectory =/root/monitoruser = root

Then run Supervisord boot supervisor in the terminal.
Run Supervisorctl in the terminal, enter the shell, run status to view the running state of the script.

Supervisor is a set of common process management programs developed with Python that can turn a normal command-line process into a background daemon and monitor the status of the process, which can be restarted automatically when the exception exits.

Four. Run the call daemon method

if __name__ = = "__main__": Createdaemon ()

Five. Start the viewing process

Python s3.py

Netstat-tunlp|grep 1003

Six. General examples

__author__ =  ' Rolin ' # -*- coding: utf-8 -*-from socketserver import  tcpserver,threadingmixin,streamrequesthandlerimport time,os,commands#import rsa#host =   ' 207.198.106.114 ' host =  ' 49.213.70.62 ' Port = 1003def transfertime (ret):     a = filter (Str.isdigit,ret)     a = list (a)      c =  '     for i in range (Len (a)):         c += a[i]        if  i in  (3,5):             c +=   '-'         if i==7:             c +=  '   '         if  i in  (9,11):  &Nbsp;          c +=  ': '     a  = time.mktime (Time.strptime (c, '%y-%m-%d %h:%m:%s '))     return adef  stopjava ():     os.popen (' Pkill java ') Def startjava ():     os.popen ("cd /data/game/pubserver/pubserver/qmrserver && /bin/sh start.sh  >/dev/null 2>&1 ")     os.popen (" Cd /data/game/kuafu/qmrserver  && /bin/sh start.sh >/dev/null 2>&1 ")      Os.popen ("cd /data/game/qmrserver_lianfu_10003/qmrserver && /bin/sh start.sh  >/dev/null 2>&1 ")     os.popen (" Cd /data/game/qmrserver901/qmrserver  && /bin/sh start.sh >/dev/null 2>&1 ")      Os.popen ("Cd /data/game/qmrserver902/qmrserver && /bin/sh start.sh >/dev/null 2>&1 ")      os.popen ("cd /data/game/qmrserver903/qmrserver && /bin/sh start.sh  >/dev/null 2>&1 ")     os.popen (" cd /data/game/qmrserver904/ Qmrserver && /bin/sh start.sh >/dev/null 2>&1 ")      os.popen ("cd /data/game/qmrserver10002/qmrserver && /bin/sh start.sh  >/dev/null 2>&1 ") Def updatejava ():     os.popen2 (' RSYNC -CZRTOPG  --timeout=10 --password-file=/root/pass.pwd [email protected]::qmrserver /data/game/ Qmrserver10002/qmrserver > /dev/null 2>&1 ')     os.popen2 (' Rsync  -czrtopg --timeout=10 --password-file=/root/pass.pwd [email protected]::qmrserver  /data/game/qmrserver901/qmrserVer > /dev/null 2>&1 ')     os.popen2 (' rsync -czrtopg -- timeout=10 --password-file=/root/pass.pwd [email protected]::qmrserver /data/game/ Qmrserver902/qmrserver > /dev/null 2>&1 ')     os.popen2 (' Rsync  -czrtopg --timeout=10 --password-file=/root/pass.pwd [email protected]::qmrserver  /data/game/qmrserver903/qmrserver > /dev/null 2>&1 ')      Os.popen2 (' rsync -czrtopg --timeout=10 --password-file=/root/pass.pwd [email  Protected]::qmrserver /data/game/qmrserver904/qmrserver > /dev/null 2>&1 ')      os.popen2 (' rsync -czrtopg --timeout=10 --password-file=/root/pass.pwd [ Email protected]::qmrserver /data/game/kuafu/qmrserver > /dev/null 2>&1 ')     os.popen2 (' rsync -czrtopg --timeout=10 --password-file=/root/pass.pwd [email protected]::qmrserver  /data/game/qmrserver_lianfu_10003/qmrserver > /dev/null 2>&1 ')      os.popen2 (' Rsync -czrtopg --timeout=10 --password-file=/root/pass.pwd [email  protected]::qmrserver /var/ftp/qmrserver ') #    time.sleep (3) #     os.popen (' sh /var/ftp/qmrserver/s.sh > /dev/null 2>&1 ') logfile =  open (' Name1.txt ', ' a ') Def log (msg):     datenow = time.strftime ('%Y-%m- %d %h:%m:%s ', Time.localtime ())     logstr =  '%s : %s \n '  % (datenow, msg)      #print (LOGSTR)     logfile.write (LOGSTR) Class server (Threadingmixin,tcpserver):     passclass threadingserver ( Threadingmixin,tcpserver):   &nbsP; allow_reuse_address = trueclass handler (Streamrequesthandler):     Def handle (self):        while true:             try:                 ip = self.client_address[0]#                 print ip                 RET = SELF.REQUEST.RECV (2048). Strip () print ret                 log (' ret %s '  % ret)                  if ip ==  ' 221.237.152.208 '  or ip ==  ' 221.237.152.108 '  or ip ==  ' 127.0.0.1 '  or ip ==  ' 125.71.211.205 ':                     if ret ==  ' Reboot ':                         self.request.send (' request received, successfully processed ... ')                           stopjava ()                          time.sleep (       )                   Startjava ()                      elif ret ==  ' Banben ':                         self.request.send (' request received, successfully processed ')                           updatejava ()                      elif ret ==  ' Time ':                          shijian = os.popen (' date + '%y-%m-%d %h:%m:%s '). Read ()                           self.request.send (Shijian)                      elif not ret:#                         print  ' no data '                           break                     else:                         self.request.send (' Request to receive, successfully process .... ')                          try:                              global time1                             time1 = transfertime (ret)                               timett = commands.getoutput (' date  ' +%Y-%m-%d %H: %m:%s "')                              time2 = transfertime (Timett)                           except Exception,e:                              print e                             log (' Time format error ')                               self.request.send (' Time format error ')                          if int (time1)   > int (time2):    print ret                              os.popen (' date -s  '%s '  % ret). Read ()                               self.request. Send (' time modified successfully ')                          else:    print ret                              self.request.send (' has received the request, successfully processed ... ')                               stopjava ()                               Time.sleep (                )             os.popen (' date -s  '%s "'  % ret). Read ()                              startjava ()                               time.sleep (Ten)                  else:                     log (' The source is wrong ')                      pass             except KeyboardInterrupt:                 log (' keyboard error ') #server  = server ( (Host,port), Handler) Def&nbsP;funzionedemo ():     server = threadingserver ((Host,port), Handler)      server.serve_forever () Def createdaemon ():     #脱离父进程      try:        pid = os.fork ()          if pid > 0:             os._exit (0)     except OSError,error:         print  "fork  #1  failed: %d  (%s)"  %  (error.errno,  Error.strerror)         os._exit (1)      #修改当前的工作目录     os.chdir ('/')      #脱离终端     os.setsid ()       #重设文件创建权限     os.umask (0)      #第二次创建进程, disable process reopen terminal file     try: &Nbsp;      pid = os.fork ()          if pid > 0:             print  ' daemon pid %d '  % pid             os._exit (0)     except OSError,error:         print  "fork  #1  failed: %d  (%s)"  %  (error.errno,  Error.strerror)         os._exit (1)     funzionedemo () if __name__ ==  "__main__":     createdaemon ()

Seven. Client request effect



This article is from the "Automation Rolin" blog, so be sure to keep this source http://luoguoling.blog.51cto.com/1568501/1616616

Using a Python socket Management Server

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.