使用python写一个管理memcached启动脚本
命令行启动:memcached -u nobody -p 11211 -c 1024 -m 64
使用方法:
判断目录是否存在:
os.path.exists(’/opt/1.py’)
返回True
创建目录:
os.mkdir(’/opt/test’)
进入这个目录。类似cd :
In [6]: os.chdir(’/opt/test’)
执行shell命令需要加载模块:
In [1]: from subprocess import Popen, PIPE
stdout=PIPE 参数相当于管道
运行shell启动命令:
p =Popen(‘memcached -u nobody -p 11211 -c 1024 -m 64’, shell=True)
显示pid:
In [5]: p.pid
Out[5]: 2256
利用pidof命令获取Pid:
p=Popen([‘pidof’,‘memcached’],stdout=PIPE)
In [7]: p.stdout.read()
Out[7]: ‘2329\n
去掉回车可以:
n [16]: p.stdout.read().strip()
Out[16]: ‘2329’
杀进程:15代表正常杀死,9是强制杀死
In [18]: os.kill(2329,15)
读取配置文件:
f=open(’/etc/sysconfig/memcached’)
In [2]: lines=f.readlines()
In [3]: lines
Out[3]:
[‘PORT=“11211”\n’,
‘USER=“memcached”\n’,
‘MAXCONN=“1024”\n’,
‘CACHESIZE=“64”\n’,
‘OPTIONS=""\n’]
去掉\n,将”t替换为空,按=分割
In [7]: [i.strip().replace(’"’,’’).split(’=’) for i in lines]
Out[7]:
[[‘PORT’, ‘11211’],
[‘USER’, ‘memcached’],
[‘MAXCONN’, ‘1024’],
[‘CACHESIZE’, ‘64’],
[‘OPTIONS’, ‘’]]
rc脚本代码:
[root@server2 rc]# cat rc_mem.py
#!/usr/bin/env python
#coding:utf8
import sys
import os
from subprocess import Popen,PIPE
class process(object):
'''memcached 启动脚本'''
args = {'USER': 'memcached',
' PORT': '11211',
'MAXCONN': '1024',
'CACHESIZE': '64',
'OPTIONS': "",
}
def __init__(self,name,program,workdir):
self.name = name
self.program = program
# self.args = args
self.workdir = workdir
def _init(self):
'''判断pid文件是否有'''
'''判断是有有文件夹/var/tmp/memcached'''
if not os.path.exists(self.workdir):
#创建和cd到目录
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 _withPid(self):
if self.pid:
with open(self._pidFile(),'w') as fd:
fd.write(str(self.pid))
def getPid(self):
p = Popen(['pidof',self.name],stdout=PIPE)
pid = p.stdout.read().strip()
return 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['CACHESIZE'],
'-c',self.args['MAXCONN'],
]
os.system("chown %s %s" %(self.args['USER'],self.workdir))
return options
def start(self):
pid = self.getPid()
if pid:
print ("%s is running..." % self.name)
sys.exit()
self._init()
cmd = [self.program]+ self._parseArgs()+['-d','-P',self._pidFile()]
#执行shell命令
p=Popen(cmd,stdout=PIPE)
#self.pid=p.pid
#self._withPid()
print ("%s start Sucessful" % self.name)
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 stopdded" %self.name )
def restart(self):
self.stop()
self.start()
def status(self):
pid = self.getPid()
if pid:
print ("%s is alread 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'
cm = process(name=name,program=prog,workdir=wd)
try:
cmd = sys.argv[1]
except IndexError,e:
print "Option error"
sys.exit()
if cmd == 'start':
cm.start()
elif cmd == 'stop':
cm.stop()
elif cmd == 'restart':
cm.stop()
cm.start()
elif cmd == 'status':
cm.status()
else:
cm.help()
if __name__ == '__main__':
main()
测试下运行脚本:
[root@server2 rc]# python rc_mem.py start
memcached start Sucessful
#测试进程是否起来:
[root@server2 rc]# ps aux |grep mem
493 21945 0.0 0.0 330844 980 ? Ssl 16:41 0:00 /usr/bin/memcached -u memcached -p 11211 -m 64 -c 1024 -d -P /var/tmp/memcached/memcached.pid
root 21952 0.0 0.0 103324 888 pts/0 S+ 16:41 0:00 grep mem
[root@server2 rc]# python rc_mem.py restart
memcached is stopdded
memcached start Sucessful
[root@server2 rc]# python rc_mem.py stop
memcached is stopdded
[root@server2 rc]# python rc_mem.py status
memcached is not running...
[root@server2 rc]# python rc_mem.py help
Usage: rc_mem.py {start|stop|status|restart}
其中用到的配置文件:(需要改配置可以直接更改此文件)
[root@localhost opt]# cat /etc/sysconfig/memcached
PORT=“11211”
USER=“memcached”
MAXCONN=“1024”
CACHESIZE=“64”
OPTIONS=""