Connect SSH to PHP to ensure data transmission security

Source: Internet
Author: User
Tags php cli

Author: freedom Source: Skynet

SSH can transmit data by encrypting the online packets. SSH can be used to encrypt all transmitted data, and no useful information can be obtained even if someone intercepts the data. At the same time, data is compressed, which greatly speeds up transmission. In short, the use of SSH ensures that data transmission is secure and the transmission efficiency is high.

However, not everyone knows the features that PHP can connect to SSH and the ability to execute remote commands, but this is very useful. Since PHP can be used in many different ways, it has many configuration options to control its behavior. A large set of optional parameters can ensure that you can use PHP for many different purposes, but it also means that the combination of these parameters and server configuration will bring some security issues. I have been using SSH in php cli applications. I used it from cronjobs, but it was not very simple at the beginning. It can be said that it was a great deal of money. The Manual on secure use of the Shell2 function is not very practical either. I have conducted many tests before having published this article. I hope you can save some time for configuring PHP after reading this article.

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 corresponding content in this article with the Data Package Manager provided by your Linux release.

You are running PHP5. if you are not running PHP5, use PHP4 instead.

You have a basic understanding of PHP and server management.

You have installed PHP.

Prerequisites

Installation 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

After the installation is complete, go to the next step.

Compile libssh2

After downloading Libssh2 from the sourceforge website, we need to compile it, but don't worry, you just need to 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 whether a new version is available, you can check SF. NET. However, 0.14 is enough.

Install

Install ssh2.so

Next, we need to link libssh and PHPr. There is a PECL module to complete this function. We can use PEAR to install it.

Pear install-f ssh2

The-f parameter ensures that SSH2 is installed, even if there is no stable selection object. You can also use the following package name: ssh2-beta to forcibly run.

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 under "Dynamic Extensions", which is about 515th rows.

PHP supports coding through SSH

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

1. Execution method:

This tells the operating system of your server to execute something and transmits it back to your script through the pipeline.

2. Shell method:

This method opens an actual shell in the operating system, just as it is operated when logging on through the terminal application. Some routers do not have a fully POSIX consistency implementation process. Instead, they run their own applications immediately upon logon. In this case, you need this method.

We will detail the following in detail:

Method 1: Execute

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

If (! Function_exists ("ssh2_connect") die ("function ssh2_connect doesnt exist ")

// Log in at server1.example.com on port 22

If (! ($ Con = ssh2_connect ("server1.example.com", 22 ))){

Echo "fail: unable to establish connection ";

} Else {

// Try to authenticate with username root, password secretpassword

If (! Ssh2_auth_password ($ con, "root", "secretpassword ")){

Echo "fail: unable to authenticate ";

} Else {

// Allright, were in!

Echo "okay: logged in ...";

// Execute a command

If (! ($ Stream = ssh2_exec ($ con, "ls-al "))){

Echo "fail: unable to execute command ";

} Else {

// Collect returning data from command

Stream_set_blocking ($ stream, true );

$ Data = "";

While ($ buf = fread ($ stream, 4096 )){

$ Data. = $ buf;

}

Fclose ($ stream );

}

}

Method 2: Housing

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

If (! Function_exists ("ssh2_connect") die ("function ssh2_connect doesnt exist ")

// Log in at server1.example.com on port 22

If (! ($ Con = ssh2_connect ("server1.example.com", 22 ))){

Echo "fail: unable to establish connection ";

} Else {

// Try to authenticate with username root, password secretpassword

If (! Ssh2_auth_password ($ con, "root", "secretpassword ")){

Echo "fail: unable to authenticate ";

} Else {

// Allright, were in!

Echo "okay: logged in ...";

// Create a shell

If (! ($ Shell = ssh2_shell ($ con, vt102, null, 80, 40, SSH2_TERM_UNIT_CHARS ))){

Echo "fail: unable to establish shell ";

} Else {

Stream_set_blocking ($ shell, true );

// Send a command

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

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, and there is no data in the buffer, the PHP script will stop outputting from a command (even if the command is not completed !) . You can perform the following operations:

Ssh2_exec ($ con, ls-al; echo "_ COMMAND_FINISHED __");

Now, in the loop where you constantly check the buffer, you just need to look at COMMAND_FINISHED. Because you can know that you have all the data. To avoid infinite loops (endless 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 ";

Break;

}

If (time ()-$ time_start)> 10 ){

Echo "fail: timeout of 10 seconds has been reached ";

Break;

}

}

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

Send files through SSH

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

If not

Check the following items:

Follow these steps to check your operations

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 need to add the following line to the file, that is, manually enable this function:

/Etc/ssh/sshd_config:

# Change to yes to enable tunnelled clear text passwords

PasswordAuthentication yes

If this is changed, restart SSH:

/Etc/init. d/ssh restart

 

 

Related Article

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.