Python编写的memcached启动脚本

Python编写memcached启动脚本

一、rc 脚本的start、stop、restart、status方法

#/usr/bin/env python
# -*- coding:utf-8 -*-
# @time   :2018/1/12 19:11
# @Author :FengXiaoqing
# @file   :rc.py
import os
import sys
from subprocess import Popen,PIPE
class Process(object):
    '''memcached rc script'''
    def __init__(self,name,program,args,workdir):
        self.name = name
        self.program = program
        self.args = args
        self.workdir = workdir
    def _init(self):
        '''/var/tmp/memcached'''
        if not os.path.exists(self.workdir):
            os.mkdir(self.workdir)
            os.chdir(self.workdir)
    def _pidFile(self):
        '''/var/tmp/memcached/memcached.pid'''
        return os.path.join(self.workdir,"%s.pid" % self.name)
    def _writhPid(self):
        if self.pid:
            with open(self._pidFile(),'w') as fd:
                fd.write(str(self.pid))
    def start(self):
        pid = self._getPid()
        if pid:
            print "%s is already runnig..." % self.name
            sys.exit()
        self._init()
        cmd = self.program + ' ' + self.args
        p = Popen(cmd,stdout=PIPE,shell=True)
        self.pid = p.pid
        self._writhPid()
        print "%s start Sucessful.." % self.name
    def _getPid(self):
        p = Popen(['pidof',self.name],stdout = PIPE)
        pid = p.stdout.read().strip()
        return pid
    def stop(self):
        pid = self._getPid()
        if pid:
            os.kill(int(pid),15)
            if os.path.exists(self._pidFile()):
                os.remove(self._pidFile())
            print ("%s is stopped .") % self.name
    def restart(self):
        self.stop()
        self.start()
    def status(self):
        pid = self._getPid()
        if pid:
            print "%s is already running..." % self.name
        else:
            print "%s is not running..." % self.name
    def _help(self):
        print ("Usage: %s {start|stop|status|restart}") % __file__
def main():
    name = 'memcached'
    prog = '/usr/bin/memcached'
    args = '-u nobody -p 11211 -c 1024 -m 64'
    wd = '/var/tmp/memcached'
    pm = Process(name = name,
                 program=prog,
                 args=args,
                 workdir=wd)
    try:
        cmd = sys.argv[1]
    except IndexError,e:
        print ("Option  error")
        sys.exit()
    if cmd == 'start':
        pm.start()
    elif cmd == 'stop':
        pm.stop()
    elif cmd == 'restart':
        pm.restart()
    elif cmd == 'status':
        pm.status()
    else:
pm._help()
if __name__ == '__main__':
    main()

二、rc脚本的(以daemon方式启动)

#/usr/bin/env python
# -*- coding:utf-8 -*-
# @time   :2018/1/12 21:18
# @Author :FengXiaoqing
# @file   :rc-d.py
import os
import sys
from subprocess import Popen,PIPE
class Process(object):
    '''memcached rc script'''
    args = {'USER':'memcached',
            'PORT':11211,
            'MAXCONN':1024,
            'CACHESIZE':64,
            'OPTIONS': ''}
    def __init__(self,name,program,workdir):
        self.name = name
        self.program = program
        self.workdir = workdir
    def _init(self):
        '''/var/tmp/memcached'''
        if not os.path.exists(self.workdir):
            os.mkdir(self.workdir)
            os.chdir(self.workdir)
    def _pidFile(self):
        '''/var/tmp/memcached/memcached.pid'''
        return os.path.join(self.workdir,"%s.pid" % self.name)
    def _writhPid(self):
        if self.pid:
            with open(self._pidFile(),'w') as fd:
                fd.write(str(self.pid))
    def _readConf(self,f):
        with open(f) as fd:
            lines = fd.readlines()
            return dict([i.strip().replace('"','').split('=') for i in lines])
    def _parseArgs(self):
        conf = self._readConf('/etc/sysconfig/memcached')
        if 'USER' in conf:
            self.args['USER'] = conf['USER']
        if 'PORT' in conf:
            self.args['PORT'] = conf['PORT']
        if 'MAXCONN' in conf:
            self.args['MAXCONN'] = conf['MAXCONN']
        if 'CACHESIZE' in conf:
            self.args['CACHESIZE'] = conf['CACHESIZE']
        options = ['-u',self.args['USER'],
                   '-p',self.args['PORT'],
                   '-m',self.args['MAXCONN'],
                   '-c',self.args['CACHESIZE']] 
        return options
    def start(self):
        pid = self._getPid()
        if pid:
            print "%s is already runnig..." % self.name
            sys.exit()
        self._init()
        cmd = [self.program]+self._parseArgs()+['-d','-P',self._pidFile()]
        p = Popen(cmd,stdout=PIPE)
        print "%s start Sucessful.." % self.name
    def _getPid(self):
        p = Popen(['pidof',self.name],stdout = PIPE)
        pid = p.stdout.read().strip()
        return pid
    def stop(self):
        pid = self._getPid()
        if pid:
            os.kill(int(pid),15)
            if os.path.exists(self._pidFile()):
                os.remove(self._pidFile())
            print ("%s is stopped .") % self.name
    def restart(self):
        self.stop()
        self.start()
    def status(self):
        pid = self._getPid()
        if pid:
            print "%s is already running..." % self.name
        else:
            print "%s is not running..." % self.name
    def help(self):
        print ("Usage: %s {start|stop|status|restart}") % __file__
def main():
    name = 'memcached'
    prog = '/usr/bin/memcached'
    wd = '/var/tmp/memcached'
    pm = Process(name = name,
                 program=prog,
                 workdir=wd)
    try:
        cmd = sys.argv[1]
    except IndexError,e:
        print ("Option  error")
        sys.exit()
    if cmd == 'start':
        pm.start()
    elif cmd == 'stop':
        pm.stop()
    elif cmd == 'restart':
        pm.restart()
    elif cmd == 'status':
        pm.status()
    else:
        pm.help()
if __name__ == '__main__':
    main()

原文地址:http://blog.51cto.com/fengyunshan911/2060427

时间: 2024-12-12 06:39:37

Python编写的memcached启动脚本的相关文章

Python - 利用python编写的memcached启动脚本

memcached作为缓存文件服务,默认是操作系统里面是可以直接yum -y install memcached进行安装的. /etc/init.d/memcached 是属于系统shell编写的管理脚本,下面这个脚本是python脚本编写出来的memcached管理脚本,和shell编写的脚本实现的效果一样. #!/usr/bin/python import sys import os from subprocess import Popen,PIPE class Process(object

Python中的类方法及属性总结举例,编写memcached启动脚本举例

1.类的属性总结类属性,也是公有属性, 类的私有属性, 对象的共有属性, 对象的私有属性, 内置属性, 函数的局部变量, 全局变量, #/usr/bin/env python # -*- coding:utf-8 -*- class MyClass(object): var1 = '类属性,类的公有属性 var1' __var2 = '类的私有属性 __var2' def func1(self): self.var3 = '对象的公有属性 var3' self.__var4 = '对象的私有属性

python—memcached启动脚本

一.一般模式 启动选项:start.stop.restart.status #!/usr/bin/env python #encoding:utf-8 import sys import os from subprocess import Popen, PIPE class Process(object):     '''memcached rc script'''     def __init__(self,name,program,argv,workdir):  # 初始化类,包含:self

Memcached启动脚本

假设memcached安装在/home/www/memcached目录 # cd /home/www/memcached # vi start.sh start.sh内容如下: bin/memcached -d -m 10240 -p 11211 -l 192.168.20.102  -c 1024 -u root -P /home/www/memcached/memcached.pid #chmod 755 start.sh 用脚本启动nginx # cd /home/www/memcache

使用python编写批量ping主机脚本

通过使用python,编写脚本批量ping主机,验证主机是否处于活动状态 #!/usr/bin/python #auther: Jacky #date: 2016-08-01 #filename: ping_ip.py import os,sys import subprocess,cmd def subping():     f = open("ip_list.txt","r")     lines = f.readlines()     for line in 

Memcached 启动脚本

#!/usr/bin/env python import sys import os from subprocess import Popen, PIPE class Process(object): '''memcached rc script''' args = {'USER': 'memcached', 'PORT': 11211, 'MAXCONN': 1024, 'CACHESIZE': 64, 'OPTIONS': ''} def __init__(self, name, progr

利用Python编写linux自动备份脚本

题目: 周末的时候帮朋友写了一个备份需求的脚本,现在整理一下,分享出来使用Python语言的Fabric模块,这里就不扫盲了,运维必用的Python模块: 大概要求: 公司需求,每天凌晨2点备份数据(数据量不大,每天全备),拷贝至备份服务器,通过md5对比备份文件(本机备份文件和备份服务器文件对比),并将备份情况通知运维组同学. 备份思路: (1.每天凌晨2点在服务器本地使用tar打包备份文件: (2.备份成功以后,推送至备份服务器: (3.校验本地备份文件和备份服务器文件的完整性和一致性: (

python编写Mysql自动备份脚本

#!/usr/bin/env python # -*- coding: utf-8 -*-  # filename: mysql_dump.py import os import time import string ''' defined variable ''' databases='--database kbss_kcas reportdb koacif sequence infocenter' sql_user='root' sql_pwd='123456' ''' Defining t

python编写调用shell命令脚本

os.listdir("/")==ls shutil.copy(src,dest)==cp  src指源文件 shutil.copy2(src,dest)  copy2copy2还会复制最后存取时间和最后更新时间. shutil.copytree(src,dst[,symlinks])   复制目录,symlinks,它是一个布尔值,如果是True的话就创建符号链接. shutil.move(src,dst)  ==mv os.chdir(dirname)把当前工作目录切换到dirna