ssh2 php module
Internet hostings are normally limited and sometimes you would like to execute some applications that you have in your own computer but you can’t execute in your hosting server. PHP+SSH is one solution if you want to execute a Unix application.
Temp Manual: You should install pear-pecl ssh2 php extension.
Prerequisites:
sudo aptitude update sudo aptitude install php5-dev php5-cli php-pear buid-essential openssl libssl libssl-dev zlib1g-dev
Installation:
1. Download libssh2 from sourceforge (./configure && sudo make all install)
2. Try automatic installation (pecl install -f ssh2)
If error: download ssh2 package from pecl.php.net
Patch ssh2.c: replace #if LIBSSH2_APINO < 200412301450 with —–> #if LIBSSH2_VERSION_NUM < 0×001000
If local installation: patch configure.m4 (add libssh2 path to SEARCH_)
phpize && ./configure –with-ssh2 && make (then you get modules/ssh2.so) chmod a+x ssh2.so
sudo cp ssh2.so /usr/lib/php5/some_date/ (default unix php5 extensions dir)
3. Edit php.ini (/etc/php5/apache2/ and /etc/php5/cli/) add: extension=ssh2.so (in extensions section)
4. Restart Apache to reload php.ini settings (sudo /etc/init.d/apache2 restart)
Usage: Then you can try this php:
<?php
if (!function_exists("ssh2_connect")) die("function ssh2_connect doesn't exist");
// log in at server on port 22
if(!($con = ssh2_connect("srv2", 22))){
echo "fail: unable to establish connection\n";
} else {
// try to authenticate with username root, password secretpassword
if(!ssh2_auth_password($con, "moreda", "mierda")) {
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
echo "Executed ls -la\n";
stream_set_blocking( $stream, true );
$data = "";
while( $buf = fread($stream,4096) ){
$data .= $buf;
echo "".$buf;
}
fclose($stream);
}
}
}
?>
TIP, TRICK (include a timeout):
$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) > 120 ){
echo “fail: timeout of 120 seconds has been reached\n”;
break;
}
}
SCP over PHP
ssh2_scp_send($con, “/tmp/source.dat”, “/tmp/dest.dat”, 0644);
Install at Dreamhost (or other server):
First make sure that you can control settings of your own php.ini file.
http://wiki.dreamhost.com/Custom_PHP.ini
After do the process described above by using: script.sh (UPLOAD…)
Then configure php.ini properly.
Here are some tutorials:
http://kevin.vanzonneveld.net/techblog/article/make_ssh_connections_with_php/ http://www.thescripts.com/forum/thread2449.html http://www.webhostingtalk.com/archive/index.php/t-368992.html