php - 通过代理 PHP 的 SSH 连接

标签 php ssh proxy phpseclib ssh2-sftp

是否可以使用php通过代理建立ssh连接?

我的php代码是

$connection = ssh2_connect('x.x.x.x');

但是下面报错

PHP Warning:  ssh2_connect(): Unable to connect to x.x.x.x

我也无法通过命令行建立ssh连接。

ssh root@x.x.x.x

解决方案(失败)

然后我找到了解决方案。我创建了 **~/.ssh/config** 文件并向其中添加了代理定义。

Host x.x.x.x
    Hostname x.x.x.x
    User root
    ProxyCommand /usr/bin/corkscrew proxy.somewebsite.com 10080 %h %p

之后我可以通过命令行连接到 ssh :)

但我仍然无法连接 php 代码。我仍然得到同样的错误:(

这里的问题是 ssh2_connection 函数没有使用 ssh 配置文件。有没有办法告诉函数使用它?

最佳答案

使用 phpseclib 确实可行而且非常简单。之前使用 php ssh2 并且工作正常但没有已知的方法通过代理建立连接。 phpseclib 比 php 的 ssh2 更好。如果您使用的是 ssh2_connect,则这意味着没有。这是为我工作的示例代码:

public function connect()
        {
            $auth = base64_encode($this->proxyUser.':'.$this->proxyPass);

            $fsock = fsockopen($this->proxyHost, $this->proxyPort);
            $request = "CONNECT $this->ssh_host:$this->ssh_port HTTP/1.0\r\nContent-Length: 0\r\nProxy-Authorization: Basic $auth\r\n\r\n";

            if(fputs($fsock, $request) != strlen($request)) {
                sys_error("Unable to connect to proxy");
            }

            $response = fgets($fsock); //Response should be 'Connection Established'

            $this->sftp = new Net_SFTP($fsock);  //Will work similarly for Net_SSH

            if(!$this->sftp->login($this->ssh_auth_user, $this->ssh_auth_pass)){
                sys_error('Login to sftp server failed');
                return false;
            }

            return true;
        }

关于php - 通过代理 PHP 的 SSH 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37598196/

相关文章:

php - 使用 php 数组中的键对 div 显示顺序进行排序和更改

linux - 通过 ssh 发送 tee 命令

python - 在 python 中测试 HTTPS 代理

ruby - 什么是 SSH 转发?

proxy - Nexus 代理存储库

proxy - 什么时候应该在 HTTP 代理服务器上使用 CONNECT 和 GET HTTP 方法?

php - 如何在 PHP 中创建搜索过滤器?

javascript - 为第 1 行请求未知参数 '0' - 它在第一行中没有插入任何值

php - 我怎样才能使用2个同名的表单字段,但只使用填写的字段将数据插入mysql?

macos - 全新安装后设置 git