gpt4 book ai didi

php - 是否可以在不创建 .ssh 目录的情况下执行 ssh 命令?

转载 作者:可可西里 更新时间:2023-11-01 00:35:27 25 4
gpt4 key购买 nike

我正在尝试通过 SSH 从 PHP 脚本在远程服务器上运行命令。这是片段:

    $ssh_command = "ssh -F keys/config -o UserKnownHostsFile=keys/known_hosts -i keys/deployment_key -p $ssh_port $r
$git_fetch = "git --git-dir=$remote_path/.git --work-tree=$remote_path fetch 2>&1";
exec("$ssh_command '$git_fetch' 2>&1", $out);

如果我从命令行运行该脚本,它可以正常工作,因为它是以具有常规登录 shell 和他们自己的 .ssh 目录的用户身份运行的。当我尝试通过 Web 界面运行脚本时,它失败了,因为 SSH 无法在 Apache 用户的主目录中创建它的 .ssh 目录。

是否可以在没有 .ssh 目录的情况下使用 SSH,或者是否有另一种方法可以作为 Apache 用户运行 SSH?我不想为 Apache 用户创建 .ssh 文件夹。

最佳答案

我可以通过一个小问题/副作用来绕过这个限制。

设置选项 UserKnownHostsFile=/dev/nullStrictHostKeyChecking=no,您可以欺骗 SSH 使其不实际存储或要求验证主机 key 。

StrictHostKeyChecking 设置为 no 允许在不知道或验证其 key 的情况下连接到服务器;并将 /dev/null 用于 UserKnownHostsFile 只是读取和写入任何内容,因此不会读取或保存任何值。

需要注意的是,SSH 仍会尝试创建 .ssh 目录并失败,但失败会导致警告并且它将继续连接。警告将包含在您的输出中(除非您要禁止显示警告)。

这是一个例子。注意:对于此示例,我没有设置任何身份验证,因此它将尝试使用密码身份验证并失败,但由于您使用的是身份,因此您应该能够正常连接。

<?php
$ssh_command = "ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no "
."-p 2223 user@host.localdomain";

exec("$ssh_command ls 2>&1", $out);

var_dump($out);

// output when called from browser running as daemon(1)
array(5) {
[0]=>
string(44) "Could not create directory '/usr/sbin/.ssh'."
[1]=>
string(110) "Warning: Permanently added '[host.localdomain]:2223,[192.168.88.20]:2223' (RSA) to the list of known hosts."
[2]=>
string(36) "Permission denied, please try again."
[3]=>
string(36) "Permission denied, please try again."
[4]=>
string(82) "Received disconnect from 192.168.88.20: 2: Too many authentication failures for user"
}

您的输出很可能只包含关于无法创建 .ssh 目录的第一个警告,然后是关于将主机永久添加到已知主机列表中的警告 (/dev/null),然后是命令的输出;所以你必须检查第一行是否是这个警告,并将它从 $out 数组中移出。

另一个注意事项:这确实开启了中间人攻击或 DNS/IP 黑客攻击的可能性,让您尝试连接到流氓服务器。

请参阅 SSH Host Key Protection 上的这篇文章来自赛门铁克。

关于php - 是否可以在不创建 .ssh 目录的情况下执行 ssh 命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9425638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com