git push后自动部署

前提,服务器已经装好ssh,本地也已经将ssh 公钥传到服务器对应位置

先用 pbcopy < ~/.ssh/PRIVATE_KEY.pub 将公钥复制到剪贴板;通过 ssh USER@SERVER 访问服务器,这时会提示输入密码(它也许只有这么一次「询问」的机会);成功登录后 vim ~/.ssh/authorized_keys,在合适的位置 cmd + V 并保存退出(同时 exit 退出 SSH 连接)。

Host HOST_ALIAS                       # 用于 SSH 连接的别名,最好与 HostName 保持一致
  HostName SERVER_DOMAIN              # 服务器的域名或 IP 地址
  Port SERVER_PORT                    # 服务器的端口号,默认为 22,可选
  User SERVER_USER                    # 服务器的用户名
  PreferredAuthentications publickey
  IdentityFile ~/.ssh/PRIVATE_KEY     # 本机上存放的私钥路径

如何公钥名非默认,可打开上面的文件进行配置,在~/.ssh/config中

1  先在远程库 testproject目录(用户访问的那个git库)创建一个并行目录testproject.git(这是个目录,后面的后缀是为了方便认出是一个git库,用于设置hook)

2然后cd testproject.git,git init,初始化这个库,

然后vim .git/config

添加

[receive]

           denyCurrentBranch = ignore

这两行,或者git config receive.denyCurrentBranch ignore  

这样才可接受本地的push

然后这个git 库的地址就是   root@xxx.xxx.xxx.xxx:/xxx/xxx/testproject.git

中间是服务器的ip,后面是库的路径,注意这里的root是登录的用户,其实可以自己建一个其他的用户,这里root是懒,

建其他用户的方法是 useradd paul 

userpwd paul设置密码

然后建立对应的库,并为库设置属主chmod paul:paul testproject.git

然后切换到pual用户,还要为新用户设置.ssh什么的,不然push提交的时候还是得输密码

上面弄好远程库后,再在本地git remote set-url --add origin root@xxx.xxx.xxx.xxx:/xxx/xxx/testproject.git

把这个远程库添加到Orogin名下,

3  在远程库.git/hooks下,cp post-update.sample  post-update ,vim post-update

把里面删除

加入 

#!/bin/sh

unset GIT_DIR

NowPath=`pwd`
DeployPath="../../testproject"

cd $DeployPath
git pull origin master

cd $NowPath
exit 0

原理不复杂,就是当你Push时,同时向这个远程库push,push完后调用这个hook中的脚本,然后切换到对应目录去pull,完事,当然 也可以在这个hook中加些其他东西,比如python xxx.py什么的,招待一些
脚本,不过好像本地当你提交时,必须要等这个hook中的脚本执行完毕,本地那边 才结束,因为当我运行一个
while True:
  print "hello"
时,本地那个会一直出现 hello.
暂时没想到异步运行的方法
原文地址:https://www.cnblogs.com/xqnq2007/p/8168000.html