[英]Integrating PHP, SSH and ssh-agent
我計划編寫一個建立 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;
}
顯然,返回的響應類型為NET_SSH2_MSG_USERAUTH_FAILURE
。 登錄沒有任何問題,我敢肯定,因此根據代碼中的注釋,這意味着主機(Digital Ocean)必須使用多因素身份驗證。 這就是我難住的地方。 我還缺少什么其他身份驗證方法? 這就是我對 SSH 的理解失敗的地方。
phpseclib 支持 SSH 代理。 例如。
use phpseclib\Net\SSH2;
use phpseclib\System\SSH\Agent;
$agent = new Agent;
$ssh = new SSH2('localhost');
if (!$ssh->login('username', $agent)) {
throw new \Exception('Login failed');
}
更新您的最新編輯
更新:我更多地研究了 phpseclib 並編寫了我自己的簡單包裝類。 但是,我無法通過 ssh-agent 或提供我的 RSA 密鑰來登錄它。 僅基於密碼的身份驗證有效,這與我直接使用 ssh 命令登錄的經驗相反。
代理身份驗證和直接公鑰身份驗證的 SSH 日志是什么樣的? 您可以通過在頂部執行define('NET_SSH2_LOGGING', 2)
然后在身份驗證失敗后echo $ssh->getLog()
來獲取 SSH 日志。
根據 neubert,我必須將這一行添加到 Connection.php 中,並且我能夠讓基於代理的身份驗證工作:
$this->client->setPreferredAlgorithms(['hostkey' => ['ssh-rsa']]);
我仍然無法讓基於密鑰的身份驗證工作,但我不太在意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.