踩坑:
1、php程序執行linux命令是以webserver的user用戶(如apache 、www……)操作的,需要在/etc/sudoers添加用戶免密碼操作權限;
%apache ALL=(ALL) NOPASSWD:ALL
2、以webserver用戶執行的命令都只能在其默認根目錄中進行,如apache默認根目錄在/usr/share/httpd ;nginx默認根目錄在/usr/share/nginx/html;
3、若主機配置多站點,域名指向指定目錄,即用戶每執行一條命令后都會返回該指定目錄;
4、git用戶公鑰填寫root用戶下.ssh生成公鑰,項目部署公鑰則是webserver用戶下.ssh生成的公鑰,如apache用戶的.ssh目錄在/usr/share/httpd/
git webhook 勾子:
<?php
//test7
class Deploy
{
public function deploy()
{
$commands = ['cd /usr/share/httpd/test','git pull'];
$signature = $_SERVER['HTTP_X_HUB_SIGNATURE'];
$payload = file_get_contents('php://input');
error_log($payload);
if($this->isFromGithub($payload,$signature)){
foreach ($commands as $command) {
shell_exec($command);
}
http_response_code(200);
}else{
exit('error,bad request');
}
}
private function isFromGithub($payload,$signature)
{
return 'sha1='.hash_hmac('sha1',$payload,'2e4dd3e73a4b2f854357ba21a8bdd3fc',false) === $signature; // 2e4dd…… 就是密鑰
}
}
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$deploy = new Deploy();
$deploy->deploy();
}
?>
coding webhook 勾子:
<?php
//test11
class Deploy
{
public function deploy()
{
$commands = ['cd /usr/share/httpd/test','git pull'];
$token = '2e4dd3e73a4b2f854357ba21a8bdd3fc';
$payload = file_get_contents('php://input');
$json = json_decode($payload,true);//error_log($payload);
if(!empty($json['token']) && $json['token'] == $token){
foreach ($commands as $command) {
shell_exec($command);
}
http_response_code(200);
}else{
exit('error,bad request');
}
}
}
if($_SERVER['REQUEST_METHOD']== 'POST'){
$deploy = new Deploy();
$deploy->deploy();
}
