[ PHP ] 如何讓 PHP可使用ssh連線 (Make SSH connections with PHP)
In this article I'm going to assume that:
- You're running Debian / Ubuntu
If not, you will have to substitute the package manager aptitude with whatever your distribution provides
- You're running PHP 5
If not, just replace php5 with php4 everywhere
- You have basic knowledge of PHP & server administration
- You already have PHP installed
On recent Ubuntu machines, there's no need to do any compiling anymore:
aptitude install libssh2-1-dev libssh2-php
You can now test if PHP recognizes it's new ssh2 extension by running:
php -m |grep ssh2
It should return: 'ssh2'
If the above works for you (you should see also: "Build process completed successfully"), you can skip to: Great! PHP supports SSH - time to code.
Otherwise we need to compile manually, continue reading here.
First let's install the following packages:
aptitude install php5-dev php5-cli php-pear build-essential openssl-dev zlib1g-dev
That should set us up alright.
We need libssh2 from sourcefourge. We have to compile this, but no worries, this is all you need to do:
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
That's it! Easy right?
- Update: since December 26th 2008, libssh2 has reached version 1.0. Though I have not tested it: it has been reported to work. So you may want to check sf.net and download the latest stable version.
Next we need to link libssh & PHP together. There's a PECL module for this so let's install using:
pecl install -f ssh2
The -f makes sure ssh2 is installed even though there's not a stable candidate. You could also use the package name: ssh2-beta to overrule this.
Now you need to make sure our new
ssh2.so module is loaded by PHP. Edit a
php.ini file (I'd recommend a separate one:
/etc/php5/conf.d/ssh2.ini). Make sure it reads:
Great! PHP supports SSH - time to code
You've just enabled ssh2 support in PHP. Now how can we make use of this? There are 2 options. SSH supports the:
- Execute method This tells the server's operating system to execute something and pipe the output back to your script. (recommended)
- Shell method This opens an actual shell to the operating system, just as you would normally when logging in with your terminal application. Some routers that don't have a full POSIX compliant implementation, but run their own application as soon as you login, require this. (advanced)
reference from： http://kevin.vanzonneveld.net/techblog/article/make_ssh_connections_with_php/ 僅轉載並加顏色，圖文一字未改