Connect SSH with PHP to ensure data transmission security

Source: Internet
Author: User
Tags fread ini connect pear php and php cli php script ssh
SSH can transmit data through the technology of online packet encryption; Using SSH, you can encrypt all the data that is transmitted, even if someone intercepts the data and cannot get useful information. At the same time the data compression, greatly accelerated the speed of transmission. In short, through the use of SSH, you can ensure that data transmission is more secure and more efficient transmission.

However, not everyone knows the nature of the PHP connection 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 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. The author has been using SSH in the PHP CLI application, the author uses it from the cronjobs, but it is not very simple at first, it can be said that it is quite time-consuming. About the safe use of the SHELL2 function of the manual is not very practical, the author has a number of tests after the today's small article, I would like you to read after you can configure PHP to save a little time.

In this article, I need to assume:

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're running a PHP5. If you're not running PHP5, you can use PHP4 instead.

You have a basic understanding of PHP and Server management.

You have installed PHP.

Prerequisite

Installing packages

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

Installation complete to the next step.

Compiling LIBSSH2

After downloading Libssh2 from the SourceForge website, we need to compile it, but don't worry, you just have to do the following:

Cd/usr/src

wget 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 you have a new version, you can view the sf.net. However, the 0.14 version is sufficient.

Installation

Install ssh2.so

Next, we need to link libssh and PHPR. There is a pecl module that can perform this function. We can install it with pear.

Pear install-f SSH2

The-f parameter ensures that the SSH2 is installed, even if there is no 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 with 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 under "Dynamic Extensions", about the No. 515 line or so.

PHP supports SSH writing code

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

1. Methods of Implementation:

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

2. Shell method:

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

Let us elaborate on the following:

The first method: executing

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

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

Log in 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

In the same way, you can also write a function or a class for the following code. However, this article only provides the basic idea:

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

Log in 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, Ssh2_term_unit_chars)) {

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

}

else{

Stream_set_blocking ($shell, true);

Send a Commandfwrite ($shell, "ls-al\n");

Sleep (1);

& Collect returning Data$data = "";

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

$data. = $buf;

}

Fclose ($shell);

}

}

}

Small tip:

Sometimes the server is busy, or a connection error, the buffer does not have data, the PHP script will stop the output from a command (even if the command is not completed!). ) to collect the data. You can do this by doing the following:

Ssh2_exec ($con, ' ls-al; echo "__command_finished__");

Now, in the loop where you're constantly checking the buffers, 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 timeout limit of 10 seconds:

$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 the stream_set_blocking to False.

Sending files via SSH

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

If you don't work properly

Please check the following aspects:

Follow this article to check every step of your operation

On the server side, "Passwordauthentication yes" must be enabled in Sshd_config. The default value is yes on most servers, but in some cases you may want to add the following line to the file, which is to manually turn on the feature:

/etc/ssh/sshd_config:

# change to Yes to enable tunnelled clear text

Passwordspasswordauthentication 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.