CentOS7+Git+码云+TP(php) WebHook自动同步部署更新代码到阿里云服务器_菜鸟详情图文教程

阿里云服务器:oneinstack一键PHP环境

一、搭建码云好仓库 (略过)

教程:https://blog.csdn.net/haibo0668/article/details/90403673

二、服务器搭建Git  oneinstack已经安装好GIT,版本是:1.8.3

 查看git版本

git --version

2.1 在服务器上生成公钥 (就像在你自己电脑生成公钥一样子)

生成公钥的目的,是为了更安全更方便的SSH拉取方式,同时让git命令语句更简洁。

部署公钥允许以只读的方式访问仓库,SSH主要用于仓库在生产服务器的部署上,免去HTTP方式每次操作都要输入密码和普通SSH方式担心不小心修改仓库代码的麻烦。

部署公钥配置后的机器,只支持clone与pull等只读操作。如果您想要对仓库进行写操作,请 添加个人公钥

2.1.0 生成公钥

sudo -u www ssh-keygen -t rsa -C "[email protected]" 

注意:www表示有权限执行PHP的用户 

2.1.1 如何查看服务器上执行PHP的用户(www)

xshell下执行 "ps aux|grep php-fpm"

ps aux | grep php-fpm

去找你php-fpm的配置文件,看图

查看这个文件,查看用户和组名称

邮箱可以不同于码云帐号,默认三次回车即可生成 ssh key 

sudo -u www ssh-keygen -t rsa -C "[email protected]" 

说明:你也可以不输入文件名,使用默认文件名(推荐),那么就会生成 id_rsa 和 id_rsa.pub 两个秘钥文件。

接着又会提示你输入两次密码(该密码是你push文件的时候要输入的密码,而不是github管理者的密码),
当然,你也可以不输入密码,直接按回车。那么push的时候就不需要输入密码,直接提交到github上了,
 

2.1.2 出现错误:无法创建目录“/home/www/.ssh”

Generating public/private rsa key pair.
Enter file in which to save the key (/home/www/.ssh/id_rsa): 
Could not create directory '/home/www/.ssh': Permission denied
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Passphrases do not match.  Try again.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
open /home/www/.ssh/id_rsa failed: No such file or directory.
Saving the key failed: /home/www/.ssh/id_rsa.

2.1.3 使用命令查看用户的家目录位置

位置:www:x:1001:1001::/home/www:/bin/bash

2.1.4 解决无法创建目录“/home/www/.ssh”

用FTP软件查看/home文件夹里边,什么东西都没有,空白一片

所以需要创建WWW文件夹

[root@ixxxxxxxxxxZ ~]# cd /home
[root@ixxxxxxxxxxZ home]# ls
[root@ixxxxxxxxxxZ home]# ls -l
total 0
[root@ixxxxxxxxxxZ home]# mkdir www
[root@ixxxxxxxxxxZ home]# ls -l
total 4
drwxr-xr-x 2 root root 4096 Aug  2 15:51 www
[root@ixxxxxxxxxxZ home]# sudo chown www.www /home/www/

参考一个外国朋友方案:https://stackoverflow.com/questions/15860189/could-not-create-directory-home-hadoop-ssh-permission-denied

我花了大约1小时就完成了这件事,最后得到了解决方案。这是由于许可问题。你必须为你的'hadoop用户'使用chown。

1.首先制作hadoop目录。
cd / home 
mkdir hadoop
然后检查'ls -l'。它给出的结果如下:
drwxr-xr-x 2 hadoop hadoop 4096 8月22日22:17 hadoop

2. sudo chown hadoop.hadoop / home / hadoop /
3.然后运行关键生成器的剩余命令。

再生成公钥一次

sudo -u www ssh-keygen -t rsa -C "[email protected]" 

生成成功

 2.1.5  修改刚刚生成的公钥

记下生成公钥的目录:

Your identification has been saved in /home/www/.ssh/id_rsa.
Your public key has been saved in /home/www/.ssh/id_rsa.pub.

2.1.6 查看公钥 

cat /home/www/.ssh/id_rsa.pub
说明:
cat 查看
/home/www/.ssh/id_rsa.pub  刚刚上面生成公钥的完整路径

2.1.7 把公钥填入到码云上

2.1.8 验证公钥是否生效,是否可以链接码云了

sudo -u www ssh -T [email protected]

 

 

四、初始化  (我们需要先在服务器上clone一次,以后都可以实现自动部署了)

Clone克隆代码

4.1 初始化方法一:初次使用,先克隆一次代码到网站目录(推荐这个)

一定要先进入网站根目录(比如正面webhook文件夹)

sudo -u www git clone 码云仓库SSH地址  /网站根目录
sudo -u www git clone [email protected]:xxxx/cms.git /data/wwwroot/default/webhook

 

4.2 初始化方法二:初次使用,先克隆一次代码到网站目录

# 进入需要自动部署的目录xxx (就是服务器上放代码的地方)
cd xxx
# 初始化
git init
# 添加远程仓库
git remote add origin GIT仓库地址

git报错:'fatal:remote origin already exists'怎么处理?

4.2.1、先删除

1

$ git remote rm origin

4.2.2、再次执行添加就可以了。

git报错:fatal: remote origin already exists.

远程来源已经存在

 

成功

 

五、码云WebHook通知服务器拉取代码webhook.php

注意:

自动更新到阿里云服务器代码

5.1 更新语句一:把远程和服务器同名分支更新,由本地当前分支决定,默认是把远程master分支更新到阿里服务器的master分支中

echo shell_exec("cd {$savePath} && git pull {$gitPath} 2>&1");

例子:如果本地(阿里云服务器)上,默认当前分支是master,那么就把码云的master分支代码更新过来

 

5.2 更新语句二   初始化后自动更新代码才有用

 echo shell_exec("cd $savePath && git checkout -f && git pull $branch 2>&1");

git命令:https://blog.csdn.net/haibo0668/article/details/99690269

 

代码一:从码云自动更新到服务器一个文件夹

    //用于Gitee码云通过WebHooks实现自动同步代码部署
    public function webhook()
    {

		// 先做一下测试
		// 测试ls是否能用
		// $output = shell_exec('ls -lart');
		// echo "<pre>$output</pre>";
		// echo shell_exec("ls -a");
        error_reporting(1);
	
		//git webhook 自动部署脚本
		//项目存放物理路径,第一次clone时,必须保证该目录为空
		$savePath = "/data/wwwroot/default/cms.fn321.cn/application/2020";//更新锋牛代码
		//$savePath = "/data/wwwroot/default/cms.fn321.cn/application";//更新锋牛代码
		//$savePath8 = "/data/wwwroot/default/www.4008338788.com/application";//更众联牛代码
		// $gitPath  = "https://gitee.com/fn321/cms.git";//代码仓库
		$gitPath  = "[email protected]:fn321/cms.git";//代码仓库 一定要使用ssh方式不然每次都得输入密码
		$branch = "refs/heads/develop";//同步那个分支

		//密码
		$password = 'fn321@20190801/com';
		 
		//获取请求参数
		$request = file_get_contents('php://input');
		if (empty($request)) {
			die('request is empty');
		}
		 
		//echo $request;
		//验证密码是否正确
		$content = json_decode($request, true);
		if ($content['password'] != md5($password)) {
			header("HTTP/1.1 403 Forbidden");
			die('非法提交');
		}
		
        //运行代码 拉取码云最代码到阿里服务器上
		//说明: 
		//1.shell_exec()即PHP用于执行系统命令的函数,
		//2.cd $dir:进入上面设置的项目仓库文件夹中,
		//3.git checkout -f 撤销本地的修改,
		//4.git pull origin master  从码云的项目仓库master分支拉取最新代码,注意origin为远程仓库的别名,要与 git remote add 远程仓库,
		//5.别名 仓库地址 中的远程仓库别名保持一致
//      echo shell_exec("cd {$savePath} && git checkout -f && git pull {$branch} 2>&1"); //更新锋牛代码
        //echo shell_exec("cd {$savePath8} && git checkout -f && git pull {$branch} 2>&1"); //更众联牛代码
        echo shell_exec("cd {$savePath} && git pull {$gitPath} {$branch} 2>&1");//只能拉取远程码云master分支到阿里云服务器上,其它分支不会拉取
		die('done ' . date('Y-m-d H:i:s', time()));

    }

代码二:从码云自动同时候更新到几个服务器文件夹中

例子:同时更新到服务器2020和2021文件中

    //用于Gitee码云通过WebHooks实现自动同步代码部署
    public function webhook()
    {

		// 先做一下测试
		// 测试ls是否能用
		// $output = shell_exec('ls -lart');
		// echo "<pre>$output</pre>";
		// echo shell_exec("ls -a");
        error_reporting(1);
	
		//git webhook 自动部署脚本
		//项目存放物理路径,第一次clone时,必须保证该目录为空
		$savePath = "/data/wwwroot/default/xxxx.cn/application/2020";
		$savePath1 = "/data/wwwroot/default/xxxxx.cn/application/2021";
		// $gitPath  = "https://gitee.com/fn321/cms.git";//代码仓库
		$gitPath  = "[email protected]:fn321/cms.git";//代码仓库 一定要使用ssh方式不然每次都得输入密码
		$branch = "refs/heads/develop";//同步那个分支

		//密码
		$password = '190801com';
		 
		//获取请求参数
		$request = file_get_contents('php://input');
		if (empty($request)) {
			die('request is empty');
		}
		 
		//echo $request;
		//验证密码是否正确
		$content = json_decode($request, true);
		if ($content['password'] != $password) {
			header("HTTP/1.1 403 Forbidden");
			die('非法提交');
		}
		
        //运行代码 拉取码云最代码到阿里服务器上
		//说明: 1.shell_exec()即PHP用于执行系统命令的函数,
		//2.cd $dir:进入上面设置的项目仓库文件夹中,
		//3.git checkout -f 撤销本地的修改,
		//4.git pull origin master  从码云的项目仓库master分支拉取最新代码,注意origin为远程仓库的别名,要与 git remote add 远程仓库,
		//5.别名 仓库地址 中的远程仓库别名保持一致

		echo shell_exec("cd {$savePath} && git pull {$gitPath} {$branch} 2>&1");//只能拉取远程码云master分支到阿里云服务器上,其它分支不会拉取
        echo shell_exec("cd {$savePath1} && git pull {$gitPath} {$branch} 2>&1");//只能拉取远程码云master分支到阿里云服务器上,其它分支不会拉取
		die('done ' . date('Y-m-d H:i:s', time()));

    }

注意:2020和2021两个文件夹里边都上传一样子的.GIT文件才行,就是说要创建一个仓库,但是这个仓库同时存在两个文件夹中

同一个.GIT

 

关键函数:shell_exec

webhooks用到的php代码中使用了 shell_exec 函数,一般配置php会禁止这个函数,需要打开 shell_exec 函数;

参考:解决PHP调用exec或shell_exec的问题 https://blog.csdn.net/Qiang1370373713/article/details/84539990

注意:开放shell_exec这个php函数是非常危险的,因此切记不要在生产环境开放这个函数,更加不能用root权限去执行php。 
建议将以下代码放到一个单独配置的测试用网站环境,除log日志文件以外,此环境下所有文件禁止www用户的写入和修改。

5.1 开启 shell_exec 函数;

  • 找到php.ini文件 (我自己的路径:/usr/local/php/etc)
  • 查询disable_function
  • 删除shell_exec,
  • 保存
  • 重启PHP
  • 重启php 随便一个
    service php-fpm restart
    service nginx reload

5.2 测试服务器shell_exec函数是否开启

https://cms.xxxx.cn/webhook.php代码中写

 

		// 先做一下测试
		// 测试ls是否能用
		$output = shell_exec('ls -lart');
		echo "<pre>$output</pre>";

结果:

这个一定要勾上

5.3 测试拉码云代码

5.3.1 错误:error: cannot open .git/FETCH_HEAD: Permission denied(无法打开。git/fetch_head:权限被拒绝)

一种情况是:权限的问题

二种情况是:在服务器放在放代码那个文件夹中没有初始化git没有成功,找不到.git文件夹(相当在本地服务器上建立仓库)

查看.git是否存在  

进行到服务器放代码那个文件夹(本例放到2020文件夹中,路径:/default/cms.xxxx.cn/application/2020)

把初始化的仓库.git文件夹用户名和用户组修改为www www

修改:

方法一:如果你服务器是oneinstack配置的,使用官方说明:https://oneinstack.com/docs/lnmpstack-image-guide/

网站根目录权限遵循:
文件644, 文件夹755 ,权限用户和用户组www
如出现文件权限问题时,请执行下面3条命令:


chown -R www.www /data/wwwroot/
find /data/wwwroot/ -type d -exec chmod 755 {} \;
find /data/wwwroot/ -type f -exec chmod 644 {} \;

结果:

方法二:环境自己配置

# 这里以www用户为例
# 假设/wwwroot/web为网站根目录
sudo chown -R www:www /wwwroot/web

5.3.2  错误:Host key verification failed.

Host key verification failed.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

解决方法:如果遇到 Host Key Verification Failed,就执行:

sudo -u www ssh-keyscan -t rsa gitee.com >> /home/www/.ssh/known_hosts
sudo -u www ssh-keyscan -t rsa 120.55.226.24 >> /home/www/.ssh/known_hosts

六  成功

From gitee.com:fnxxxxx/cms
 * branch            HEAD       -> FETCH_HEAD
done 2019-08-03 11:42:51

表明成功,已经从码云中拉到最新代码到你自己服务器指定的位置上

 

七、实践例子(前提是公钥已经生成)

7.1 在服务上创建application文件夹 手动在服务器创建(里边不能上传内容,保留空白)
7.2 给权限

chown -R www.www /data/wwwroot/
find /data/wwwroot/ -type d -exec chmod 755 {} \;
find /data/wwwroot/ -type f -exec chmod 644 {} \;

7.3 进入application文件夹(一定要先进入这个文件夹)

cd /data/wwwroot/default/cms.xxx.cn/application


7.4 创建.GIT本地仓库(就是服务器上创建git库) 同时初始化了库,同时还更新了一次代码

sudo -u www git clone [email protected]:xxx/cms.git /data/wwwroot/default/cms.xxxx.cn/application

格式:sudo -u www git clone 自己GIT网址 服务器仓库文件夹地址(绝对地址)

7.5 切换本地分支(阿里服务器仓库)  

情况一(默认情况):如果你从码云master分支更新到阿里服务器master分支 就可以直接用了

情况二:如果你从码云develop分支更新到阿里服务器develop分支

git branch
git checkout -b develop

7.6 更新权限,避免新创建的文件和更新没有修改权限

chown -R www.www /data/wwwroot/
find /data/wwwroot/ -type d -exec chmod 755 {} \;
find /data/wwwroot/ -type f -exec chmod 644 {} \;

7.7 如果创建不成功,只能删除阿里服务器的.GIT库再7.1开始再来一次

rm -rf .git

 

八、实践例子二   全新阿里服务器(公钥按前面的步骤生成)

8.1 在服务上创建application文件夹 手动在服务器创建(里边不能上传内容,保留空白)

8.2 要初始化GIT,增加用户名和邮箱

git init
git config user.name "xxx"
git config user.email "[email protected]"

特别出现错误

From gitee.com:xxxxx/cms
 * branch            xxxx -> FETCH_HEAD

*** Please tell me who you are.

Run

  git config --global user.email "[email protected]"
  git config --global user.name "Your Name"

to set your account's default identity.
Omit --global to set the identity only in this repository.

一定要要用上面代码初始化GIT

8.3 切换阿里服务器的分支,要切换服务器分支与自己码云要同步一样子分支名称,

如果没有创建,阿里服务器默认是master分支,也会默认同步码云master 分支

//查看分支
git branch
//创始400xxx并切换到400xxx分支
git checkout -b 400xxx

8.4 第一次拉代码

sudo -u www git clone [email protected]:xxx/cms.git /data/wwwroot/default/www.xxx.com/application

 

教程参考:https://blog.csdn.net/haibo0668/article/details/102982414

 

参考:

https://blog.csdn.net/u012830303/article/details/82255431

https://blog.csdn.net/Qiang1370373713/article/details/87889009

https://blog.csdn.net/zmzwll1314/article/details/77678293

https://blog.csdn.net/huang3513/article/details/52837075

https://blog.csdn.net/hebin199118/article/details/80449067

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章