Code Monkey home page Code Monkey logo

php-ssh's Introduction

PHP SSH

Build Status (master)

Provides an object-oriented wrapper for the php ssh2 extension.

Requirements

You need PHP version 5.3+ with the SSH2 extension.

Installation

The best way to add the library to your project is using composer.

$ composer require herzult/php-ssh:~1.0

Usage

Configuration of the connection

To establish an SSH connection, you must first define its configuration. For that, create a Configuration instance with all the needed parameters.

<?php

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

The available configuration classes are:

  • Configuration
  • SshConfigFileConfiguration

Both connection configuration and public/private key authentication can be obtained from a ssh config file such as ~/.ssh/config

<?php

// simple configuration to connect "my-host"
$configuration = new Ssh\SshConfigFileConfiguration('/Users/username/.ssh/config', 'my-host');
$authentication = $configuration->getAuthentication('optional_passphrase', 'optional_username');

Create a session

The session is the central access point to the SSH functionality provided by the library.

<?php

// ... the configuration creation

$session = new Ssh\Session($configuration);

Authentication

The authentication classes allow you to authenticate over a SSH session. When you define an authentication for a session, it will authenticate on connection.

<?php

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

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

The available authentication are:

  • None for username based authentication
  • Password for password authentication
  • PublicKeyFile to authenticate using a public key
  • HostBasedFile to authenticate using a public hostkey
  • Agent to authenticate using an ssh-agent

Authentication from SshConfigFileConfiguration

If you use an ssh config file you can load your authentication and configuration from it as follows:

<?php

$configuration = new Ssh\SshConfigFileConfiguration('~/.ssh/config', 'my-host');

$session = new Session($configuration, $configuration->getAuthentication());

This will pick up your public and private keys from your config file Host and Identity declarations.

Subsystems

Once you are authenticated over a SSH session, you can use the subsystems.

Sftp

You can easily access the sftp subsystem of a session using the getSftp() method:

<?php

// the session creation

$sftp = $session->getSftp();

See the Ssh\Sftp class for more details on the available methods.

Publickey

The session also provides the getPublickey() method to access the publickey subsystem:

<?php

// ... the session creation

$publickey = $session->getPublickey();

See the Ssh\Publickey class for more details on the available methods.

Exec

The session provides the getExec() method to access the exec subsystem

<?php

// ... the session creation

$exec = $session->getExec();

echo $exec->run('ls -lah');

See the Ssh\Exec class for more details.

php-ssh's People

Contributors

ajbdev avatar awildeep avatar cmuench avatar ddeboer avatar gquemener avatar h4cc avatar harryspink avatar herzult avatar jean85 avatar l3l0 avatar rkmax avatar tentacode avatar valdocco avatar woiwa avatar yvalentin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-ssh's Issues

New subsystem SCP

Hi,
I would like to know if you plan to add SCP subsystem, as an alternative to sFTP ?
Thank you for your feedback about this feature.

Flavien

Please tag a release

The latest release is 1 year old. Could you tag a new one ?

Also, it would be great to set the branch alias for your branches

Sftp "scanDirectory" returning invalid results

It seems that the scandir() function in the Sftp::scanDirectory() function sometimes returns entries even if the provided path isn't a directory.

I have an Sftp connection with a directory "filenames". This directory contains many files like: testfile1.TXT, testfile2.TXT, etc. When scanDirectory runs on /filenames/testfile1.TXT, it returns another entry with "testfile1.TXT".

This is causing a path like the following to be returned in the results: "/filenames/testfile1.TXT/testfile1.TXT". Obviously, this is causing issues since this isn't actually a valid file.

I propose that in addition to the if (!$results = @scandir($this->getUrl($directory))) check, we also add an is_file($path) check on the path.

The modification to scanDirectory would be as follows:

if (!$results = @scandir($this->getUrl($directory)) || is_file($this->getUrl($directory))) {
    return false;
}

If this is something that can be added, I can create a PR with the change.
Thank you very much!

adding chmod in sftp feature

Hi,

I have added 'chmod' feature on sftp (due after send, to execute script), I don't know the process to pull an update of the code, so it's only in sftp.php:

/**
 * Creates a directory
 *
 * @param  string $filename The filename to resolve
 * @param  int     $mod       The permissions on the new filename
 *
 * @return Boolean
 */
public function chmod($filename, $mod = 0600)
{
    return ssh2_sftp_chmod($this->getResource(), $filename, $mod);
}

Br,
Gilles

Ssh\Exec : Wrong error code test

Hi,

If i am correct, the test in Exec is

        if ((int) $match[1] !== 0) {
            throw new RuntimeException(stream_get_contents($stderr), (int) $match[1]);
        }

but on Unix 0 means SUCCESS and 1 means ERROR

Packagist

Hi Antoine,

I know you've only merged in the composer.json PR this morning - but are you planning to submit this library/package on packagist.org? Would be handy!

Thanks in advance!

Kind regards,
David

Project status

As title, it seems that this project has been inactive for about over three years.

Many issues are wait for reply/feedback and PRs need to be reviewed/merged.

@Herzult and @h4cc, do you have any idea about this?

Ability to disconnect

How would I go about disconnecting from the server after my command has been ran?

using SshConfigFileConfiguration if the configuration has not defined "identityfile"

I suggets use the same behavior the SSH if i have a host configurate in ~/.ssh/config file like this

Host mytest
Hostname ssh.mytest.com
User testing
Port 5022

the method SshConfigFileConfiguration::getAuthentication must check first if a ~/.ssh/id_rsa and ~/.ssh/id_rsa.pub exist and use at last Authentication\None

modifing the method SshConfigFileConfiguration::getConfigForHost like this

class SshConfigFileConfiguration extends Configuration
{
     const DEFAULT_FILE = '~/.ssh/id_rsa';
     // ...
     public function getConfigForHost($host)
    {
        $matches = array();
        foreach ($this->configs as $config) {
            if (fnmatch($config['host'], $host)) {
                $matches[] = $config;
            }
        }
        if (count($matches) == 0) {
            throw new RuntimeException("Unable to find configuration for host '{$host}'");
        }
        usort($matches, function ($a, $b) {
            return strlen($a['host']) > strlen($b['host']);
        });
        $result = array();
        foreach ($matches as $match) {
            $result = array_merge($result, $match);
        }
        unset($result['host']);
        if (isset($result['identityfile'])) {
            $result['identityfile'] = $this->processPath($result['identityfile']);
        } else if (file_exists($file = $this->processPath(self::DEFAULT_FILE))) {
            $result['identityfile'] = $file;
        }

        return $result;
    }
}

solves the problem quickly

Exec() not working

My Log Fails with

PHP Notice:  Use of undefined constant SSH2_TERM_UNIT_CHARS - assumed 'SSH2_TERM_UNIT_CHARS'

How can I fix this?

ksh incompatble with echo -ne during $session->getExec();

Hi,

I'm connecting to a server AIX using ksh on ssh.

$ssh_remote_script_path= '/home/user_ksh/em/em_os.sh';
$configuration = new Ssh\Configuration('IPAddress');
$authentication = new Ssh\Authentication\Password('user_ksh', 'password');
$session = new Session($configuration, $authentication);
$exec = $session->getExec();
$result = $exec->run($ssh_remote_script_path);

The sript on remote server is /home/<user_ksh>/em/em_os.sh which just identify the server (Linux, AIX, solaris...)

The $result is 'AIX -ne' due to function run(...) in Exec.php which use the command:$cmd .= ';echo -ne "[return_code:$?]"';

Do you think it's possible to change or force the bash or removing the '-ne' when it's ksh ?

Thanks
Gilles

Agent forwarding

Hello

Thank you for this awesome package which makes any ssh connection more simple with PHP !

Right now, I try to connect on a server in order to rsync a folder to another one.
I have to enable agent forwarding but I cannot figure out how.

Can you help, please ?

Here is the code I currently use

$configuration  = new Ssh\Configuration($server);
$authentication = new Ssh\Authentication\Agent($current_user);
$session        = new Ssh\Session($configuration, $authentication);
$exec           = $session->getExec();
echo $exec->run("env | grep SSH_AUTH_SOCK");

Here is the result I would expect:

SSH_AUTH_SOCK=/tmp/ssh-Y8Boe6GL3q/agent.48545

And here is the Exception I get

PHP Fatal error:  Uncaught RuntimeException in /Users/loranger/Developer/myproject/vendor/herzult/php-ssh/src/Ssh/Exec.php:29
Stack trace:
#0 /Users/loranger/Developer/myproject/sync.php(41): Ssh\Exec->run('env | grep SSH_...')
#1 {main}
  thrown in /Users/loranger/Developer/myproject/vendor/herzult/php-ssh/src/Ssh/Exec.php on line 29

Fatal error: Uncaught RuntimeException in /Users/loranger/Developer/myproject/vendor/herzult/php-ssh/src/Ssh/Exec.php:29
Stack trace:
#0 /Users/loranger/Developer/myproject/sync.php(41): Ssh\Exec->run('env | grep SSH_...')
#1 {main}
  thrown in /Users/loranger/Developer/myproject/vendor/herzult/php-ssh/src/Ssh/Exec.php on line 29

What did I miss ? How can I do ?

Error while calling scanDirectory() with recursive true

Hey
I am using this Library for Sftp and calling the function scanDirectory to get a list of files and directories and i found this bug when the directory doesn't contain subDirectories or it's empty

while executing the function:
https://github.com/Herzult/php-ssh/blob/master/src/Ssh/Sftp.php#L267

private function scanDirectory($directory, $recursive)
    {
        if (!$results = @scandir($this->getUrl($directory))) {
            return false;
        }

        $files = array();
        $directories = array();

        foreach ($results as $result) {
            if (in_array($result, array('.', '..'))) {
                continue;
            }

            $filename = sprintf('%s/%s', $directory, $result);

            if (false === @scandir($this->getUrl($filename))) {
                $files[] = $filename;
            } else {
                $directories[] = $filename;

                if ($recursive) {
                    $children = $this->scanDirectory($filename, $recursive);
                    $files = array_merge($files, $children[0]);
                    $directories = array_merge($directories, $children[1]);
                }
            }
        }

        return array($files, $directories);
    }

its giving this error: array_merge(): Argument #2 is not an array
because the function is recursive and can return false (not only array) and we use the function result as array in the line:

$children = $this->scanDirectory($filename, $recursive);
$files = array_merge($files, $children[0]);

Can you please have a look at this issue, And let me know if it can be fixed.

Thanks

php7 + ext-ssh2 on debian 8 ?

hot to install the dependency extension ext-ssh2 on debian 8 ?

- herzult/php-ssh v1.1.1 requires ext-ssh2 * -> the requested PHP extension ssh2 is missing from your system

Composer install issue when ssh2 not available

The php-ssh dependency has a hard dependency on the ssh extension.

 "ext-ssh2": "*"

Possible solution is to make ext-ssh2 a suggest instead of a require.

It will help to install libs which uses php-ssh as require.

Write functional tests for Travis-CI

Check if it would be possible to do a loopback connection on the travis-ci VM to do some functional testing.

This should cover at least authentification, execute and sftp listing.

getenv('HOME') sometimes returns false

This causes SshConfigFileConfiguration::processPath to turn ~/folder into /folder and cause an error.

There are others you can fallback onto ($_SERVER['HOME'] for one) and as a final fallback it should assume the dirname(dirname($file)) of the config file is home (A setter for manually setting it would also be nice)

SFTP - Error when sending file

Hello,

I have a problem when I want to send a file through SFTP. This is the following.

[Symfony\Component\Debug\Exception\ContextErrorException]
Warning: file_put_contents(): Unable to open ssh2.sftp://Resource id #568/${path_remote} on remote host

Here is my code :

$configuration = new Configuration('url');
$authentication = new Password('username', 'password');
$session = new Session($configuration, $authentication);
$sftp = $session->getSftp();
$sftp->send("local_file", "remote_file");

Error is on the last line.

Can you help me please ?

Thanks.

Anthony

RuntimeException during installation of composer

We use deployphp to deploy projects to our servers but sinds a little while composer changed there output from writing lines to writing error's in some cases but the installation is still succesvol. So there is an open issue at deployphp deployphp/deployer#201 library that try's to fix this and they solved it for PhpSecLib server implementation but they also use this library to connect to servers.

In conclusion is it possible to check the output result on exit code like deployphp does for PhpSecLib instead of checking the error output?

More details

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.