腾讯堡塔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”