Connect ssh to PHP to ensure secure data transfer

Source: Internet
Author: User
Keywords Connect ssh to PHP to ensure secure data transfer
Tags fread pear php cli

SSH can be transmitted by the technology of the online packet encryption, using SSH to encrypt all the data transferred, even if someone intercepts the data will not be able to obtain useful information. At the same time, the data is compressed, which greatly accelerates the transmission speed. In short, the use of SSH can ensure that data transmission is more secure and efficient transmission.

However, not everyone knows the features of PHP that can be connected to SSH and the ability to execute remote commands, but this is useful. Since we can make use of PHP in many different ways, it has many settings options to control its behavior. A large set of optional parameters guarantees that you can use PHP for many different purposes, but it also means that the combination of these parameters and the server-side configuration poses some security issues. I have been using SSH in the PHP CLI application, I use it from the cronjobs, but it was not very simple at first, can say quite a lot of trouble. The manual on the safe use of the SHELL2 function is not very practical, the author after many tests have been today this small article, I would like you to read after you can configure PHP to save a bit of time.

In this article, I need to assume that:

The operating system you are running is debian/ubuntu. If you are not running Debian/ubuntu, you may need to replace the contents of this article with the packet manager provided by your Linux distribution.

You are running PHP5. If you are not running PHP5, you can use PHP4 instead.

You have a basic understanding of PHP and Server management.

You have already installed PHP.

Prerequisite

Install package

First, let's install the following package:

sudo aptitude update

sudo aptitude install php5-dev php5-cli php-pear buid-essential \

Openssl-dev Zlib1g-dev

The installation is complete and goes to the next step.

Compiling LIBSSH2

After downloading Libssh2 from the SourceForge website, we need to compile it, but don't worry, just follow the steps below:

Cd/usr/src

wget http://surfnet.dl.sourceforge.net/sourceforge/libssh2/libssh2-0.14.tar.gz

TAR-ZXVF libssh2-0.14.tar.gz

CD libssh2-0.14/

./configure

Make all Install

If you want to check if a new version is available, you can view sf.net. However, this version of 0.14 is sufficient.

Installation

Installing ssh2.so

Next, we need to link libssh and PHPR together. There is a PECL module to complete this function. We can install it using pear.

Pear install-f SSH2

The-f parameter ensures that the SSH2 is installed, even if it does not have a stable selection object. You can also use the following package name: Ssh2-beta to force the operation.

Now you need to make sure that our new ssh2.so module is loaded by PHP. Edit your php.ini file (for CLI utility:/etc/php5/cli/php.ini, for Apache utility:/etc/php5/apache2/php.ini)

Extension=ssh2.so

This should be placed below the "Dynamic Extensions", about the No. 515 row or so.
PHP supports SSH writing code

You have just enabled SSH2 in PHP. So how do we use it now? There are two options. SSH support:

1. Method of execution:

This tells your server's operating system to execute something and pass it back to your script through the pipeline.

2. Shell method:

This approach opens an actual shell in the operating system, just as it does when logged on through a terminal application. Some routers do not have a full POSIX conformance implementation process, but instead run their own applications as soon as you log on. This is the way you need it.

Let us elaborate on the following separately:

The first method: Execute

You'd better create a function or a class for the following code, but this article only serves as a basic idea for you, so you can start with this:

if (!function_exists ("Ssh2_connect")) Die ("function ssh2_connect doesn ' t exist")

Log in at server1.example.com on Port 22

if (! ( $con = Ssh2_connect ("server1.example.com", 22))) {

echo "fail:unable to establish connection\n";

} else {

Try to authenticate with username root, PassWord secretpassword

if (!ssh2_auth_password ($con, "root", "Secretpassword")) {

echo "fail:unable to authenticate\n";

} else {

Allright, we ' re in!

echo "okay:logged in ... \ n ";

Execute a command

if (! ( $stream = Ssh2_exec ($con, "Ls-al"))) {

echo "fail:unable to execute command\n";

} else{

Collect returning data from command

Stream_set_blocking ($stream, true);

$data = "";

while ($buf = Fread ($stream, 4096)) {

$data. = $buf;

}

Fclose ($stream);

}

}
Second method: Shell

Similarly, you can write a function or a class for the following code. However, this article provides only basic concepts:

if (!function_exists ("Ssh2_connect")) Die ("function ssh2_connect doesn ' t exist")

Log in at server1.example.com on Port 22

if (! ( $con = Ssh2_connect ("server1.example.com", 22))) {

echo "fail:unable to establish connection\n";

} else {

Try to authenticate with username root, password Secretpassword

if (!ssh2_auth_password ($con, "root", "Secretpassword")) {

echo "fail:unable to authenticate\n";

} else {

Allright, we ' re in!

echo "okay:logged in ... \ n ";

Create a shell

if (! ( $shell = Ssh2_shell ($con, ' vt102 ', null, up, up, Ssh2_term_unit_chars))) {

echo "fail:unable to establish shell\n";

} else{

Stream_set_blocking ($shell, true);

Send a command

Fwrite ($shell, "ls-al\n");

Sleep (1);

& Collect returning data

$data = "";

while ($buf = Fread ($shell,, 4096)) {

$data. = $buf;

}

Fclose ($shell);

}

}

}

Tips:

Sometimes the server is busy, or a connection error occurs, the buffer does not have data, and the PHP script stops from a command output (even if the command is not completed!) Collect data in the. You can do this for the following actions:

Ssh2_exec ($con, ' ls-al; Echo ' __command_finished__ ');
Now, in the loop where you keep checking the buffer, just look at the command_finished. Because you can know that you have all the data. To avoid infinite loops (dead loops), you can use a 10-second timeout limit:

$time _start = time ();

$data = "";

while (true) {

$data. = Fread ($stream, 4096);

if (Strpos ($data, "__command_finished__")!== false) {

echo "Okay:command finished\n";

Break

}

if ((Time ()-$time _start) > 10) {

echo "Fail:timeout of seconds has been reached\n";

Break

}

}

In the example above, you'd better set stream_set_blocking to False.

Send files via SSH

Ssh2_scp_send ($con, "/tmp/source.dat", "/tmp/dest.dat", 0644);

If not working properly

Please check the following areas:

Check every step of your operation according to this article

On the server side, "Passwordauthentication yes" must be enabled in Sshd_config. The default value on most servers is yes, but in some cases you may need to add the following line to the file to open it yourself:

/etc/ssh/sshd_config:

# change-to-yes to enable tunnelled clear text passwords

Passwordauthentication Yes

If you make a change, you will need to restart SSH:

/etc/init.d/ssh restart

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.