我计划编写一个建立 SSH 连接的 PHP 脚本。我已经研究了如何做到这一点,这看起来是最有希望的解决方案:https ://github.com/phpseclib/phpseclib我唯一的问题是如何处理我的 SSH 密钥有密码的事实,我不想每次运行脚本时都必须输入它。对于 SSH 使用的每一天,我都会在后台运行 ssh-agent,它被配置为使用 pinentry。这样我就不必每次都输入密码了。关于如何让 PHP 和 ssh-agent 相互交谈的任何想法?我唯一的线索是 ssh-agent 设置了一个环境变量SSH_AUTH_SOCK
,指向一个套接字文件。
虽然 phpseclib 的文档解决了这个问题,但它的答案很愚蠢(只需将密码放入代码中):http://phpseclib.sourceforge.net/ssh/2.0/auth.html#encrsakey
更新:我更深入地研究了 phpseclib 并编写了我自己的简单包装类。但是,我无法通过 ssh-agent 或提供我的 RSA 密钥来登录。与我直接使用 ssh 命令登录的经验相反,只有基于密码的身份验证有效。这是我的代码:
<?php
// src/Connection.php
declare(strict_types=1);
namespace MyNamespace\PhpSsh;
use phpseclib\System\SSH\Agent;
use phpseclib\Net\SSH2;
use phpseclib\Crypt\RSA;
use Exception;
class Connection
{
private SSH2 $client;
private string $host;
private int $port;
private string $username;
/**
* @param string $host
* @param int $port
* @param string $username
*
* @return void
*/
public function __construct(string $host, int $port,
string $username)
{
$this->host = $host;
$this->port = $port;
$this->username = $username;
$this->client = new SSH2($host, $port);
}
/**
* @return bool
*/
public function connectUsingAgent(): bool
{
$agent = new Agent();
$agent->startSSHForwarding($this->client);
return $this->client->login($this->username, $agent);
}
/**
* @param string $key_path
* @param string $passphrase
*
* @return bool
* @throws Exception
*/
public function connectUsingKey(string $key_path, string $passphrase = ''): bool
{
if (!file_exists($key_path)) {
throw new Exception(sprintf('Key file does not exist: %1$s', $key_path));
}
if (is_dir($key_path)) {
throw new Exception(sprintf('Key path is a directory: %1$s', $key_path));
}
if (!is_readable($key_path)) {
throw new Exception(sprintf('Key file is not readable: %1$s', $key_path));
}
$key = new RSA();
if ($passphrase) {
$key->setPassword($passphrase);
}
$key->loadKey(file_get_contents($key_path));
return $this->client->login($this->username, $key);
}
/**
* @param string $password
*
* @return bool
*/
public function connectUsingPassword(string $password): bool
{
return $this->client->login($this->username, $password);
}
/**
* @return void
*/
public function disconnect(): void
{
$this->client->disconnect();
}
/**
* @param string $command
* @param callable $callback
*
* @return string|false
*/
public function exec(string $command, callable $callback = null)
{
return $this->client->exec($command, $callback);
}
/**
* @return string[]
*/
public function getErrors(): array {
return $this->client->getErrors();
}
}
和:
<?php
// test.php
use MyNamespace\PhpSsh\Connection;
require_once(__DIR__ . '/vendor/autoload.php');
(function() {
$host = '0.0.0.0'; // Fake, obviously
$username = 'user'; // Fake, obviously
$connection = new Connection($host, 22, $username);
$connection_method = 'AGENT'; // or 'KEY', or 'PASSWORD'
switch($connection_method) {
case 'AGENT':
$connected = $connection->connectUsingAgent();
break;
case 'KEY':
$key_path = getenv( 'HOME' ) . '/.ssh/id_rsa.pub';
$passphrase = trim(fgets(STDIN)); // Pass this in on command line via < key_passphrase.txt
$connected = $connection->connectUsingKey($key_path, $passphrase);
break;
case 'PASSWORD':
default:
$password = trim(fgets(STDIN)); // Pass this in on command line via < password.txt
$connected = $connection->connectUsingPassword($password);
break;
}
if (!$connected) {
fwrite(STDERR, "Failed to connect to server!" . PHP_EOL);
$errors = implode(PHP_EOL, $connection->getErrors());
fwrite(STDERR, $errors . PHP_EOL);
exit(1);
}
$command = 'whoami';
$result = $connection->exec($command);
echo sprintf('Output of command "%1$s:"', $command) . PHP_EOL;
echo $result . PHP_EOL;
$command = 'pwd';
$result = $connection->exec($command);
echo sprintf('Output of command "%1$s:"', $command) . PHP_EOL;
echo $result . PHP_EOL;
$connection->disconnect();
})();
该类SSH2
有一个getErrors()
方法,不幸的是在我的情况下它没有记录任何内容。我不得不调试课程。我发现,无论是使用 ssh-agent 还是传入我的密钥,它总是会到达这个位置(https://github.com/phpseclib/phpseclib/blob/2.0.23/phpseclib/Net/SSH2.php#L2624):
<?php
// vendor/phpseclib/phpseclib/phpseclib/Net/SSH2.php: line 2624
extract(unpack('Ctype', $this->_string_shift($response, 1)));
switch ($type) {
case NET_SSH2_MSG_USERAUTH_FAILURE:
// either the login is bad or the server employs multi-factor authentication
return false;
case NET_SSH2_MSG_USERAUTH_SUCCESS:
$this->bitmap |= self::MASK_LOGIN;
return true;
}
显然返回的响应是 type NET_SSH2_MSG_USERAUTH_FAILURE
。我敢肯定,登录没有问题,因此根据代码中的注释,这意味着主机(数字海洋)必须使用多因素身份验证。这就是我难过的地方。我还缺少什么其他的身份验证方式?这就是我对 SSH 的理解失败的地方。