【问题标题】:Php exec git pull script with ssh doesn't work but doing it manually works使用 ssh 的 Php exec git pull 脚本不起作用,但手动执行它可以
【发布时间】:2018-01-11 13:44:55
【问题描述】:

我正在尝试制作一个脚本,在推送到 Bitbucket 存储库后,我可以在其中将 Git 拉到我的 ubuntu 服务器上。我已经为 Bitbucket 设置了 ssh 密钥,它可以在存储库上执行 git pull 命令,但是当我从 php exec 尝试它时它不起作用。

我已经尝试过 chmod 命令,例如 /.ssh/bitbucket_rsa,例如 775 和 777 以及 chown -R www-data:www-data/.ssh,但没有任何运气。

回复:

array (
 0 => 'Host key verification failed.',
 1 => 'fatal: Could not read from remote repository.',
 2 => '',
 3 => 'Please make sure you have the correct access rights',
 4 => 'and the repository exists.',
 )  

代码:

    public function gitPull() {
    try {
        exec("cd " . env("REPO_PATH") . " && git pull 2>&1", $output);
        Log::info($output);
    } catch (\Exception $e) {
        Log::error($e);
    }
    http_response_code(200);
}

【问题讨论】:

  • 该代码在哪个用户下运行?请查看exec('whoami'); 的输出以确定。
  • 'www-data' 是输出
  • 你用什么用户设置了 ssh 密钥?
  • 我用 root 设置了 ssh 密钥

标签: php git ssh


【解决方案1】:

我猜你对用户 www-data 无法建立到 git 服务器的 SSH 连接这一事实感到困惑。我认为最简单的方法是为 www-data 用户创建一个主目录,并在其中创建一个具有适当权限的 .ssh 目录、一个配置文件和一个密钥文件。您始终可以使用

以 root 身份测试设置
# su - www-data
$ cd <to your repository>
$ git pull

Google 为“无密码的 SSH 连接”正确设置它。还要注意,如果权限松动,SSH 会拒绝使用密钥文件。

【讨论】:

    【解决方案2】:
    Host key verification failed.
    

    表示 ssh 无法验证主机密钥,很可能是因为 www-data 的 home/.ssh 目录中没有 known_hosts 文件包含您的 repo 服务器的预期主机密钥。

    至少有两种方法可以解决这个问题:

    • 使用ssh-keyscan as described over on Serverfault.se:

      ssh-keyscan -H [hostname] >> /path/to/www-data's_home_directory/.ssh/known_hosts
      

      您只需要这样做一次(除非密钥更改),但您应该在运行ssh-keyscan 后检查密钥是否确实正确。

    • 在运行git 之前设置GIT_SSH_COMMAND 环境变量。您可以使用它让 ssh 使用不同的 known_hosts 文件:

      export GIT_SSH_COMMAND="ssh -o UserKnownHostsFile=/path/to/known_hosts"
      

      请注意,以上假设为 shell 语法(例如 Bash),您可能需要针对 PHP 进行调整,尤其是 export GIT_SSH_COMMAND= 部分。

    【讨论】:

      【解决方案3】:

      我在使用 github 时遇到了同样的问题:

      ssh-keyscan -t rsa github.com | tee github-key-temp | ssh-keygen -lf -
      cat github-key-temp >> ~/.ssh/known_hosts
      cat github-key-temp >> /etc/ssh/ssh_known_hosts
      

      但这还不是全部,通过下一条命令,您可以检查出了什么问题(通过 exec 或 shell_exec 运行它(保存到某个日志中):

      ssh -vT git@github.com 2>&1
      

      所以,在 privious 命令的帮助下,我明白在我的情况下:cron run's command via php script,但是在 ssh 连接中它找不到我的密钥文件(我有该文件的自定义名称):

      cd /etc/ssh/ssh_config.d/
      sudo touch <some_name>.conf
      sudo echo 'IdentityFile ~/.shh/<custom_key_file_name>' > <some_name>.conf
      

      或者尝试添加密钥文件位置的完整路径(~/ = 当前用户主目录)。 您可以通过运行检查 cron 用户,这可以帮助:

      shell_exec('whoami');
      

      附:我不知道这个解决方案是否足够安全。但我觉得很好。

      【讨论】:

        猜你喜欢
        • 2018-06-29
        • 2012-06-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-21
        • 1970-01-01
        • 2014-12-28
        相关资源
        最近更新 更多