luka/php-ssh

为php ssh2扩展提供面向对象的包装。

v2.0.1 2019-01-31 14:06 UTC

This package is auto-updated.

Last update: 2024-09-01 13:18:36 UTC


README

Build Status (develop)

为php ssh2扩展提供面向对象的包装。这是基于Antoine Hérault的工作。

需求

您需要PHP版本7.1+以及SSH2扩展

安装

将库添加到项目的最佳方式是使用composer

$ composer require luka/php-ssh:^2.0

使用

连接配置

要建立SSH连接,您必须首先定义其配置。为此,使用所有需要的参数创建一个配置实例。

<?php

// simple configuration to connect "my-host"
$configuration = new Ssh\HostConfiguration('my-host');

可用的配置类有

  • Ssh\HostConfiguration
  • Ssh\OpenSSH\ConfigFile

连接配置和公钥/私钥认证都可以从ssh配置文件(如~/.ssh/config)中获取

<?php

// simple configuration to connect "my-host"
$configuration = Ssh\OpenSSH\ConfigFile::fromHostname('my-host', '~/.ssh/config');
$authentication = $configuration->createAuthenticationMethod('optional_passphrase', 'optional_username');

创建会话

会话是访问库提供的SSH功能的主要访问点。

<?php
// ... the configuration creation
$session = new Ssh\Session($configuration);

认证

认证类允许您在SSH会话上进行认证。当您为会话定义认证时,它将在连接时进行认证。

<?php

$configuration = new Ssh\HostConfiguration('myhost');
$authentication = new Ssh\Authentication\Password('John', 's3cr3t');

$session = new Session($configuration, $authentication);

可用的认证有

  • None 基于用户名认证
  • Password 基于密码认证
  • PublicKeyFile 使用公钥进行认证
  • HostBasedFile 使用公钥主机密钥进行认证
  • Agent 使用ssh-agent进行认证

Ssh\OpenSSH\ConfigFile进行认证

如果您使用ssh配置文件,可以按如下方式从其中加载您的认证和配置

<?php

$configuration = Ssh\OpenSSH\ConfigFile::fromHostname('my-host');
$session = new Ssh\Session($configuration, $configuration->createAuthenticationMethod());

这将从配置文件中的Host和Identity声明中获取用户名、公钥和私钥。

这个简单的片段仅在存在User声明且私钥不需要密码短语的情况下才有效。如果其中任何一项不成立,您必须将缺失的值传递给createAuthentication()方法。

子系统

一旦通过SSH会话进行认证,您就可以使用子系统。

Sftp

您可以使用getSftp()方法轻松访问会话的sftp子系统

<?php

// the session creation
$sftp = $session->getSftp();

有关可用方法的更多信息,请参阅Ssh\Sftp类。

Publickey

会话还提供了getPublickey()方法来访问publickey子系统

<?php

// ... the session creation
$publickey = $session->getPublickey();

Public-Key子系统允许您提供多个公钥用于认证。有关可用方法的更多信息,请参阅Ssh\Publickey类。

Exec

会话提供了getExec()方法来访问exec子系统

<?php

// ... the session creation

/** @var Ssh\Session $session */
$exec = $session->getExec();
echo $exec->run('ls -lah')->getExitCode(), PHP_EOL;

有关更多详细信息,请参阅Ssh\Exec类。