PHP调用git操作服务器代码

文章讲述了作者在Windows环境下使用PHP通过API调用Linux服务器上的Git时遇到的问题,包括SSHkey验证、sudo权限和命令找不到。解决办法包括添加2>&1重定向错误、使用sudo并指定密码。
摘要由CSDN通过智能技术生成

腾讯堡塔linux服务器,命令行终端以root用户(默认)调用git,没问题。
编写php文件来调用git,在本地windows 11运行,没问题。
代码如下

    $cmd = 'cd ' . ROOT_PATH . ' && git pull';
    exec($cmd, $output, $code);

而放上服务器后,通过api来调用却没反应, $output为空数组,怎么回事?
再看$code,为128,非0即有错误,怎么不见报错呢?

原来需要在命令后面拼上2>&1,将错误输出重定向到标准输出,linux知识!
参考:
php exec返回状态为1
Linux shell中2>&1的含义解释
调整命令,代码如下

    $cmd = 'cd ' . ROOT_PATH . ' && git pull 2>&1';
    exec($cmd, $output, $code);

$output如下

    [
        "Host key verification failed.",
        "fatal: Could not read from remote repository.",
        "",
        "Please make sure you have the correct access rights",
        "and the repository exists."
    ]

意思是ssh key有问题,但是在命令行终端直接调用git就没问题,为啥?
因为服务器上php文件运行在www用户名下,而之前生成ssh key时用了默认的root

还得以root之名调用git,加上sudo,代码如下

    $cmd = 'cd ' . ROOT_PATH . ' && sudo git pull 2>&1';
    exec($cmd, $output, $code);

$output如下

    [
        "",
        "We trust you have received the usual lecture from the local System",
        "Administrator. It usually boils down to these three things:",
        "",
        "    #1) Respect the privacy of others.",
        "    #2) Think before you type.",
        "    #3) With great power comes great responsibility.",
        "",
        "sudo: no tty present and no askpass program specified"
    ]

意思是需要密码验证,而由于是通过api调用,所以没地方进行输入。
设法调通sudo,又报sudo: git: command not found
参考:
避免sudo需要密码及“sudo: git: command not found”

  • 10
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值