【www.bbyears.com--python】
虽然是用python实现的,其实可以是任何服务端脚本。svn的钩子功能非常的好用,git也是可以实现钩子功能,只不过因为其实分布式的特征,我们如果想让某个服务器更新提交代码,我们通过远程库通知目标服务器,目标服务器接到通知,执行git pull即可。
第一种实现:
这种方式是使用中间文件,两种脚本实现的
1、首先,一般的远程版本库,我使用的github,都是有个webhooks功能,github就在版本库的设置选项中,他可以设置一个Payload URL,这里可以根据自己的需要,选择,填写自己的通知地址,我是在各版本库push的时候执行通知,通知自己的一个url,这个url是用php写的。
代码:
PHP
if(@$_POST["payload"]){
$p = json_decode($_POST["payload"],true);
if("update" == $p["commits"][0]["message"]){
file_put_contents("/data/log/git.log","1111");
}
}
?>
这里我写的很简单,接收通知,但是我只是让git提交备注填写update的时候,去写入中间文件,这样就可以自己控制web的更新,
2、python脚本:
Python
#!/usr/bin/python2.6
#coding=utf-8
import os
import time
dir = "/data/www/www.111cn.net/"
file = "/data/log/git.log"
nowfile = os.getcwd()+"/"+__file__
stime = os.stat(nowfile).st_mtime
#修改时间变化退出
while stime == os.stat(nowfile).st_mtime:
log = os.popen("cat "+file).read().strip()
if "" != log:
os.system("echo "" > "+file)
os.system("cd "+dir+";git pull origin master 1>/dev/null 2>&1")
os.system("echo "git update" | mail -s "web update" zhangcunchao_cn@163.com")
time.sleep(1)
else:
os.system("echo "python git pull Process end" | mail -s "process check" zhangcunchao_cn@163.com")
这个脚本就是监控这个中间脚本,当有更新的时候,执行git pull操作,并通知我
原理是非常简单的,这个脚本再加入上篇文章中写的那个进程监控脚本中,即可。
第二种实现:
直接使用web.py,python做web服务器,直接提供对应地址即可
代码:
Python
import web
import os
import demjson
urls = (
"/github", "hello",
"/github/", "hello",
)
class hello:
def GET(self,a=""):
print "only post"
def POST(self,name=""):
i = web.input()
if not i.has_key("payload"):
print "nodata"
else:
data = demjson.decode(i.payload)
if "update" == data["commits"][0]["message"]:
dir = "/data/www/www.111cn.net/"
os.system("cd "+dir+";git pull origin master 1>/dev/null 2>&1")
os.system("echo "git update" | mail -s "web update" zhangcunchao_cn@163.com")
if __name__ == "__main__": web.run(urls, globals())
这样,我本地写了markdown文档等,甚至修改代码,我就可以直接本地修改提交,就可以自动更新我的服务器web站点了。
以后我的文章就尽量在markdown文档写了,大家多多支持奥。