Hot File

How to Securely Communicating with Remote Servers via PHP

View: 174    Dowload: 0   Comment: 0   Post by: hanhga  
Author: none   Category: Php&mySql   Fields: Other

0 point/0 review File has been tested

PHP has an SSH2 library which provides access to resources (shell, remote exec, tunneling, file transfer) on a remote machine using a secure cryptographic transport. Objectively, it is a tedious and highly frustrating task for a developer to implement it due to its overwhelming configuration options and complex API with little documentation.

Introduction

PHP has an SSH2 library which provides access to resources (shell, remote exec, tunneling, file transfer) on a remote machine using a secure cryptographic transport. Objectively, it is a tedious and highly frustrating task for a developer to implement it due to its overwhelming configuration options and complex API with little documentation.

 

The phpseclib (PHP Secure Communications Library) package has a developer friendly API. It uses some optional PHP extensions if they’re available and falls back on an internal PHP implementation otherwise. To use this package, you don’t need any non-default PHP extensions installed.

Installation

composer require phpseclib/phpseclib

This will install the most recent stable version of the library via Composer.

Use-cases

Before diving in blindly, I’d like to list some use-cases appropriate for using this library:

  1. Executing deployment scripts on a remote server
  2. Downloading and uploading files via SFTP
  3. Generating SSH keys dynamically in an application
  4. Displaying live output for remote commands executed on a server
  5. Testing an SSH or SFTP connection

Connecting to the Remote Server

Using phpseclib, you can connect to your remote server with any of the following authentication methods:

  1. RSA key
  2. Password Protected RSA key
  3. Username and Password (Not recommended)

RSA Key

We will assume that you have a secure RSA key already generated. If you are not familiar with generating a secure RSA key pair, you can go through this article. For a video explanation, you can refer to Creating and Using SSH Keys from Servers For Hackers.

To log in to a remote server using RSA key authentication:

namespace App;

use phpseclib\Crypt\RSA;
use phpseclib\Net\SSH2;

$key = new RSA();
$key->loadKey(file_get_contents('privatekey'));

//Remote server's ip address or hostname
$ssh = new SSH2('192.168.0.1');

if (!$ssh->login('username', $key)) {
    exit('Login Failed');
}

Password Protected RSA Key

If your RSA keys are password protected, do not worry. Phpseclib takes care of this particular use case:

namespace App;

use phpseclib\Crypt\RSA;
use phpseclib\Net\SSH2;

$key = new RSA();
$key->setPassword('your-secure-password');
$key->loadKey(file_get_contents('privatekey'));

//Remote server's ip address or hostname
$ssh = new SSH2('192.168.0.1');

if (!$ssh->login('username', $key)) {
    exit('Login Failed');
}

Username and Password

Alternatively, to log in to your remote server using a username and password (we don’t recommend this practice):

namespace App;

use phpseclib\Net\SSH2;

//Remote server's ip address or hostname
$ssh = new SSH2('192.168.0.1');

if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}

For other options such as No Authentication or Multi-Factor authentication please refer to the documentation

Executing Commands on the Remote Server

The code to execute commands on a remote server is pretty simple. You call the $ssh->exec($cmd) method with the command to execute as the parameter.

namespace App;

use phpseclib\Crypt\RSA;
use phpseclib\Net\SSH2;

$key = new RSA();
$key->loadKey(file_get_contents('privatekey'));

//Remote server's ip address or hostname
$ssh = new SSH2('192.168.0.1');

if (!$ssh->login('username', $key)) {
    exit('Login Failed');
}

$ssh->exec('ls -la');

Executing Multiple Commands on Remote Server

In real life applications, we rarely execute a single command. We often need to traverse around the server using cd and execute many other commands. If you try to execute multiple commands on the remote server as below, it won’t give you the desired output:

$ssh->exec('pwd'); //outputs /home/username

$ssh->exec('cd mysite.com');

$ssh->exec('pwd'); //outputs /home/username

The reason for above is that a call to the exec method does not carry state forward to the next exec call. To execute multiple commands without losing state:

$ssh->exec('cd /home/username; ls -la'); //Lists all files at /home/username

You can append as many commands as you wish with a semicolon or new line character PHP_EOL.

For example, if you want to run a full deployment script for Laravel:

$ssh->exec(
      "git pull origin master" . PHP_EOL
        . "composer install --no-interaction --no-dev --prefer-dist" . PHP_EOL
        . "composer dump-autoload -o" . PHP_EOL
        . "php artisan optimize" . PHP_EOL
        . "php artisan migrate --force"
);

Exiting on First Error

In the above script, the whole set of commands is executed as a single shell script. Every command will be executed, even if some of them fail, just like in a regular shell script. As a default, this is fine, but if we need to exit on the first error, we have to alter our bash script. This is not something specific to phpseclib, it is related to bash scripting.

If you put a set -e option at the beginning of the script, the script will terminate as soon as any command in the chain returns a non-zero value.

For example, the modified version of the above deployment script would be

$ssh->exec(
    "set -e" . PHP_EOL
        . "git pull origin master" . PHP_EOL 
        . "composer install --no-interaction --no-dev --prefer-dist" . PHP_EOL
        . "composer dump-autoload -o" . PHP_EOL
        . "php artisan optimize" . PHP_EOL
        . "php artisan migrate --force"
);

The above script will terminate if any of the commands results in an error.

Gathering Output

The exec method returns the output of your remote script:

$output = $ssh->exec('ls -la');
echo $output;

Sometimes, however, it does not return the whole output. You can overcome this by passing a closure as a second argument to the exec method to make sure that any uncaught output will also be returned.

$ssh->exec(
    $deployment_script, function ($str) {
        $output .= $str;
});

echo $output;

Note: Error output, if any, will also be returned by the exec method or the underlying closure.

Displaying Live Output

If you want to execute the script via console commands and display live output, you can achieve this by echoing the output in the underlying closure.

$ssh->exec($deployment_script, function ($str) {
    echo $str;
});
If you want to display it in a web browser, you need to flush (send) the output buffer with ob_flush().
$ssh->exec(
    $deployment_script, function ($str) {
        echo $str;
        flush();
        ob_flush();
});

Other Configuration Options

It’s also possible to set many other available configuration options. You can call them as $ssh->{option}.

For example: $ssh->setTimeout(100).

How to Securely Communicating with Remote Servers via PHP

How to Securely Communicating with Remote Servers via PHP Posted on 04-10-2016  PHP has an SSH2 library which provides access to resources (shell, remote exec, tunneling, file transfer) on a remote machine using a secure cryptographic transport. Objectively, it is a tedious and highly frustrating task for a developer to implement it due to its overwhelming configuration options and complex API with little documentation. 5/10 174

Comment:

To comment you must be logged in members.

Files with category

  • How to Picking the Brains of Your Customers with Microsoft’s Text Analytics

    View: 2948    Download: 0   Comment: 0   Author: none  

    How to Picking the Brains of Your Customers with Microsoft’s Text Analytics

    Category: Php&mySql
    Fields: Other

    5/1 review
    With the explosion of machine learning services in recent years, it has become easier than ever for developers to create “smart apps”. In this article, I’ll introduce you to Microsoft’s offering for providing machine-learning capabilities to apps.

  • How to MySqli Tutorial PHP MySqli Extension

    View: 246    Download: 0   Comment: 0   Author: none  

    How to MySqli Tutorial PHP MySqli Extension

    Category: Php&mySql
    Fields: Other

    0/0 review
    PHP provides three api to connect mysql Database.

  • Make Laravel Artisan Commands

    View: 222    Download: 0   Comment: 0   Author: none  

    Make Laravel Artisan Commands

    Category: Php&mySql
    Fields: Other

    0/0 review
    Artisan is the command line tool used in Laravel framework. It offers a bunch of useful command that can help you develop application quickly. Apart from Artisan available commands, you can create your own custom commands to improve your workflow.

  • Check if a Number is a Power of 2

    View: 202    Download: 0   Comment: 0   Author: none  

    Check if a Number is a Power of 2

    Category: Php&mySql
    Fields: Other

    2.25/2 review
    How to check if a number is a power of 2. To understand this question, let’s take some example.

  • Concatenate columns in MySql

    View: 261    Download: 0   Comment: 0   Author: none  

    Concatenate columns in MySql

    Category: Php&mySql
    Fields: Other

    0/1 review
    Artisan is the command line tool used in Laravel framework. It offers a bunch of useful command that can help you develop application quickly. Apart from Artisan available commands, you can create your own custom commands to improve your workflow

  • How to Query NULL Value in MySql

    View: 193    Download: 0   Comment: 0   Author: none  

    How to Query NULL Value in MySql

    Category: Php&mySql
    Fields: Other

    5/1 review
    Misunderstanding NULL is common mistake beginners do while writing MySql query. While quering in MySql they compare column name with NULL. In MySql NULL is nothing or in simple word it isUnknown Value so if you use comparison operator for NULL values...

  • How to Abstract Class in PHP

    View: 226    Download: 0   Comment: 0   Author: none  

    How to Abstract Class in PHP

    Category: Php&mySql
    Fields: Other

    0/0 review
    What is an abstract class in PHP and when to use an abstract class in your application. In this tutorial, we’ll learn about abstract class and their implementation.

  • Use Enums in Rails for Mapped Values

    View: 221    Download: 0   Comment: 0   Author: none  

    Use Enums in Rails for Mapped Values

    Category: Php&mySql
    Fields: Other

    5/1 review
    When I worked in a call center, we used to mark cases with different statuses. This allowed upper management to get a handle on where cases stood, what the bottlenecks were and flow of calls. Thankfully it has been a long time since I worked in a...

 
Newsletter Email

File suggestion for you

File top downloads

logo codetitle
Codetitle.com - library source code to share, download the file to the community
Copyright © 2015. All rights reserved. codetitle.com Develope by Vinagon .Ltd