Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Secure Shell2 Functions

Secure Shell2 Functions

Introduction

Bindings to the » libssh2 library which provide access to resources (shell, remote exec, tunneling, file transfer) on a remote machine using a secure cryptographic transport.

Installation

Windows binaries may be found at » http://snaps.php.net/. To install, download php_ssh2.dll to the folder specified by your php.ini file's extension_dir directive. Enable it by adding extension=php_ssh2.dll to your php.ini and restarting your web server.

extension_dir=c:/php5/exts/
extension=php_ssh2.dll

Linux, BSD, and other *nix variants can be compiled using the following steps:

  • Download and install » OpenSSL. If you install OpenSSL via your distribution's packaging system be sure to install the development libraries as well. This will typically be a package named openssl-dev, openssl_devel, or some variation thereof.
  • Download and install » libssh2. Typically this means executing the following command from the libssh2 source tree. ./configure && make all install.
  • Run the pear installer for PECL/ssh2: pear install ssh2
  • Copy ssh2.so from the directory indicated by the build process to the location specified in your php.ini file under extension_dir.
  • Add extension=ssh2.so to your php.ini
  • Restart your web server to reload your php.ini settings.
Development Versions:

There are currently no stable versions of PECL/ssh2, to force installation of the beta version of PECL/ssh2 execute: pear install ssh2-beta

Compiling PECL/ssh2 without using the PEAR command:

Rather than using pear install ssh2 to automatically download and install PECL/ssh2, you may download the tarball from » PECL. From the root of the unpacked tarball, run: phpize && ./configure --with-ssh2 && make to generate ssh2.so. Once built, continue the installation from step 4 above.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/ssh2.

Note:

You will need version 0.4 or greater of the libssh2 library (possibly higher, see release notes).

Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

SSH2_FINGERPRINT_MD5 (integer)
Flag to ssh2_fingerprint() requesting hostkey fingerprint as an MD5 hash.
SSH2_FINGERPRINT_SHA1 (integer)
Flag to ssh2_fingerprint() requesting hostkey fingerprint as an SHA1 hash.
SSH2_FINGERPRINT_HEX (integer)
Flag to ssh2_fingerprint() requesting hostkey fingerprint as a string of hexits.
SSH2_FINGERPRINT_RAW (integer)
Flag to ssh2_fingerprint() requesting hostkey fingerprint as a raw string of 8-bit characters.
SSH2_TERM_UNIT_CHARS (integer)
Flag to ssh2_shell() specifying that width and height are provided as character sizes.
SSH2_TERM_UNIT_PIXELS (integer)
Flag to ssh2_shell() specifying that width and height are provided in pixel units.
SSH2_DEFAULT_TERM_WIDTH (integer)
Default terminal width requested by ssh2_shell().
SSH2_DEFAULT_TERM_HEIGHT (integer)
Default terminal height requested by ssh2_shell().
SSH2_DEFAULT_TERM_UNIT (integer)
Default terminal units requested by ssh2_shell().
SSH2_STREAM_STDIO (integer)
Flag to ssh2_fetch_stream() requesting STDIO subchannel.
SSH2_STREAM_STDERR (integer)
Flag to ssh2_fetch_stream() requesting STDERR subchannel.
SSH2_DEFAULT_TERMINAL (string)
Default terminal type (e.g. vt102, ansi, xterm, vanilla) requested by ssh2_shell().

Table of Contents

ssh2_auth_hostbased_file — Authenticate using a public hostkey
ssh2_auth_none — Authenticate as "none"
ssh2_auth_password — Authenticate over SSH using a plain password
ssh2_auth_pubkey_file — Authenticate using a public key
ssh2_connect — Connect to an SSH server
ssh2_exec — Execute a command on a remote server
ssh2_fetch_stream — Fetch an extended data stream
ssh2_fingerprint — Retreive fingerprint of remote server
ssh2_methods_negotiated — Return list of negotiated methods
ssh2_publickey_add — Add an authorized publickey
ssh2_publickey_init — Initialize Publickey subsystem
ssh2_publickey_list — List currently authorized publickeys
ssh2_publickey_remove — Remove an authorized publickey
ssh2_scp_recv — Request a file via SCP
ssh2_scp_send — Send a file via SCP
ssh2_sftp_lstat — Stat a symbolic link
ssh2_sftp_mkdir — Create a directory
ssh2_sftp_readlink — Return the target of a symbolic link
ssh2_sftp_realpath — Resolve the realpath of a provided path string
ssh2_sftp_rename — Rename a remote file
ssh2_sftp_rmdir — Remove a directory
ssh2_sftp_stat — Stat a file on a remote filesystem
ssh2_sftp_symlink — Create a symlink
ssh2_sftp_unlink — Delete a file
ssh2_sftp — Initialize SFTP subsystem
ssh2_shell — Request an interactive shell
ssh2_tunnel — Open a tunnel through a remote server

Code Examples / Notes » ref.ssh2

dan

you will have an issue transferring any file using ssh2_scp_send unless you send a dummy file after your real file, or preferably issue an
ssh2_exec ($connection, 'exit');
I was transferring hundreds of thousands of files in my prototype across multiple servers, and noticed that each file had a mismatched md5 hash and bytelength.
after a bit of research i learnt that this was a bug, and added the code above as suggested at pecl.php.net in the bugs section.
hopefully this helps someone who is getting partial file transfer that could ruin your whole app.


josh kritner

Update for the Mac OS X install when using the Entropy.ch PHP5 package: You can use the PECL installer for ssh2 now instead of manually downloading it.
1) Download and install libssh2 per the instructions below(Steps 1-5)
2) run "sudo /usr/local/php5/bin/pecl install ssh2-beta"
3) add extension=ssh2.so to /usr/local/php5/lib/php.ini
4) Restart Apache (sudo apachectl restart)


dotwho

Trying to compile this ssh PECL extension for Mac OS X (10.4.2)
with entropy.ch's php5 distribution? Read on: PART 2:
11) Check your shell's path variable by SHELL$ "echo $PATH".
If your php5 binary directory is not listed before the standard OS X binary directory,
update your $PATH variable to list it first. Mine reads:
/usr/local/mysql/bin/: /usr/local/php5/bin/: /bin:/sbin: /usr/bin:/usr/sbin
11a) if you do not do this step, the PECL extension will link against the old
php4 version that ships with Mac OS X. You will know this by the fact that the
next step lists a server API that is different than the output of phpinfo():
My version was 20041030, Apples version was 20020429.
12) Run: phpize && ./configure --with-ssh2 && make
This will produce a lot of output and probably some warnings. If you get a note
at the end that says "Build Complete", then the process has completed
(probably successfully). The command has produced the output file ssh2.so within
the ssh2-0.9 (or whatever version) directory.
13) Check where the extension directory is located at by running the following command:
SHELL$/usr/local/php5/bin/php-config --extension-dir
If it lists some directory that actually exists, copy the ssh2.so file to this directory.
If it doesn't list a location that exists, you can either create the location, or
choose a different location and update the line in your php.ini file:
extension_dir = "./"
to point to the directory you would like to use. I chose:
extension_dir = "/usr/local/php5/extensions/"?>
14) Add the line
extension=ssh2.so
to the Dynamic Extensions area of your php.ini file.
15) Restart your web server for the extensioin to be loaded. If there are any problems, they will be written to the webserver log.
16) Check if your new ssh based streams are available by running:
SHELL$ /usr/local/php5/bin/php -r "print_r(stream_get_wrappers());"
You should get something similar to this output:
Array
(
   [0] => php
   [1] => file
   [2] => http
   [3] => ftp
   [4] => compress.bzip2
   [5] => compress.zlib
   [6] => https
   [7] => ftps
   [8] => ssh2.shell
   [9] => ssh2.exec
   [10] => ssh2.tunnel
   [11] => ssh2.scp
   [12] => ssh2.sftp
)
You should now be able to do all the cool things you need to do with ssh
(like sftp scp ssh execution)! Take a look at some of the comment here for some
example scripts to test things out:
http://us2.php.net/manual/en/ref.ssh2.php
Good luck... hope that saves you my headache! :)


mike
To slightly correct the directory listing code below....
<?php
$connection = ssh2_connect("hostname", 22);
 // use any of the ssh2_auth_* methods
ssh2_auth_password($connection,"username", "password");
$sftp = ssh2_sftp($connection);
$dir = "ssh2.sftp://$sftp/path/to/dir/";
$dh = opendir($dir);
while (($file = readdir($dh)) !== false) {
 echo "$file is in hostname:/path/to/dir\ n";
}
closedir($dh);
?>
(thanks to Sara for assisting)


cjs

The windows binary if php_ssh2.pdb on http://snaps.php.net/ is located in the debug pack.

aeolianmeson

Some installations of PHP 5 may have a problem starting the SSH2 extension as a Windows' service. It just started happening to me today, spontaneously. I have PHP 5.2.2 (and have tried 5.2.3), on Apache 2.0.59 .
It turns out that it's an Apache problem. Even though I was given an error message when starting it, it still worked perfectly from the CLI. So, I commented it out in the
INI file again, and am just loading it using extension_loaded('ssh2') and dl('php_ssh2.dll') from within the script.


jr

OK, the SSH class I wrote is now available for free on the Net.
The class uses an underlying SSH implementation, and hence does not require any library to be compiled against.
It is available at savannah.cer.ch as a byproduct of project GridGramm (look in the downloads section). There are two releases available, the first one establishes a connection for each command, having a serious authentication overhead. The second release shares a master connection, highly reducing auth payload, but requires openssh >= 3.8.
They are also available from the development site at
http://savannah.cern.ch/projects/gridgramm
and come with extensive documentation and examples.
These are work in progress, and I hope to add more enhancements in the close future. But you are welcome to use them now.


kickthedonkey

Just a quick note about the manual installation instructions above.  If your PHP is in a non-standard location, or you're running multiple installs of different PHP version, you have to complie the module with an explicit path to phpize and php-config:
/path/to/correct/php/bin/phpize && ./configure --with-ssh2 --with-php-config=/path/to/correct/php/bin/php-config && make
Took me an hour to figure out why I was getting a "Unable to initialize module Module compiled with module API" error when I loaded the module.  Turns out, it was compiling against my php4 libs, and not the php5 ones.


mjames

Just a note, if you're download the libssh2 source tar, you'll need to download libssh2-0.12.tar.gz.  The newer versions won't compile properly.  I've tried either the pecl or manual way, and kept getting a compile time error  when using the pecl package ssh2-0.10.
Michael James
mjames@voipsupply.com


astribuncio

Installing on HPUX 11.11 cookbook
Just follow the install instructions on the man page and solved the problems as they appear
- when making libssh2
Problem related with /lib/pa20_64 and 64 bits library in 32 bits link
Edited the configure file  and changed
SHLIB_LDFLAGS="-b +vnocompatwarnings -L/lib/pa20_64"
to
SHLIB_LDFLAGS="-b +vnocompatwarnings -L/lib"
-when executing phpize
Problems with aclocal, autom4ke and m4
Installed automake, autoconf and m4
-when ./configuring the ssh2
Configure: error: libssh2 version >= 0.4 not found
Edited the configure.m4 and removed the -ldl switch from line (as posted before)
39      -L$SSH2_DIR/lib -lm -ldl
runned phpize again and ./configure --with-ssh2


chris dot britton

I was building out the ssh2 extension (0.10) under OpenBSD 3.9 on sparc64 and I got this error when running configure:
checking for libssh2_banner_set in -lssh2... no
configure: error: libssh2 version >= 0.4 not found
I did some poking around in the configure file and traced the problem down.  The reason for the failure is that configure is trying to compile a test program with -ldl.  libdl is not installed on OpenBSD 3.9. The OpenBSD folks purged libdl years ago and I could not find a package that contains it.
(The error message above is misleading because the problem is not with libssh2.)
I looked at the ssh2 extension code and could not see a reason for using libdl, so I removed the -ldl from the config.m4 file.  Re-ran phpize and configure. No errors.  Did make and installed ssh2.so.  Works fine.


stevec

I couldn't get `pear install ssh2-beta` to work, so I tried the manual installation.  I followed the instructions:
phpize && ./configure --with-ssh2 && make
Copy ssh2.so from the directory indicated by the build process to the location specified in your php.ini file under extension_dir.
When I restarted Apache, I got:
PHP Warning:  Unknown(): Invalid library (maybe not a PHP library) 'ssh2.so'  in Unknown on line 0
To fix the problem, I ran `make install`, instead of copying ssh2.so into the extension directory.


s haycroft

I also struggled with the
configure: error: libssh2 version >= 0.4 not found
error using verions 0.10 of ssh2 and 0.14 of libssh.
When looking in the config.log file I found that it was unable to find my SSL libraries, and as I installed my openssl in /usr/local/ssl it could not find it.  It was only looking in /usr/local/lib.
To get round this problem, I set
LDFLAGS="-L /usr/local/ssl/lib"
and this works a treat.


tim wood

For those trying to use this under an x86_64 version of an rpm-based distribution (e.g. CentOS, RHEL or Fedora Core) who don't have an rpm for libssh2, here's a work around.
Locate the source rpm for an i386 version (for instance from dag or dries) and rebuild it:
rpmbuild --rebuild --target x86_64 libssh2-*.src.rpm
If the rebuild complains about not being able to find something and references a path beginning /var/tmp or /tmp, it may very well have built the files but failed due to a minor error in the spec file.  I was too lazy to fix the spec file, so I just manually copied the files into place.  In my case, the path in the error included /var/tmp/libssh2-0.12-root/usr/lib/...  Note that libssh2 part?  That's the area where all the files are dumped during the rpmbuild process.  if you move everything in there to the comparable place on your drive, you're golden.  In this case libssh2.so was in /var/tmp/libssh2-0.12-root/usr/lib/  Strip off the /var/tmp/libssh2* part and you find out the libssh2.so file goes in /usr/lib/
Enjoy.


kevmaster

A detailed installation how to, and some source code examples:
http://kevin.vanzonneveld.net/?mp=techblog&sp=article&id=37


Change Language


Follow Navioo On Twitter
.NET Functions
Apache-specific Functions
Alternative PHP Cache
Advanced PHP debugger
Array Functions
Aspell functions [deprecated]
BBCode Functions
BCMath Arbitrary Precision Mathematics Functions
PHP bytecode Compiler
Bzip2 Compression Functions
Calendar Functions
CCVS API Functions [deprecated]
Class/Object Functions
Classkit Functions
ClibPDF Functions [deprecated]
COM and .Net (Windows)
Crack Functions
Character Type Functions
CURL
Cybercash Payment Functions
Credit Mutuel CyberMUT functions
Cyrus IMAP administration Functions
Date and Time Functions
DB++ Functions
Database (dbm-style) Abstraction Layer Functions
dBase Functions
DBM Functions [deprecated]
dbx Functions
Direct IO Functions
Directory Functions
DOM Functions
DOM XML Functions
enchant Functions
Error Handling and Logging Functions
Exif Functions
Expect Functions
File Alteration Monitor Functions
Forms Data Format Functions
Fileinfo Functions
filePro Functions
Filesystem Functions
Filter Functions
Firebird/InterBase Functions
Firebird/Interbase Functions (PDO_FIREBIRD)
FriBiDi Functions
FrontBase Functions
FTP Functions
Function Handling Functions
GeoIP Functions
Gettext Functions
GMP Functions
gnupg Functions
Net_Gopher
Haru PDF Functions
hash Functions
HTTP
Hyperwave Functions
Hyperwave API Functions
i18n Functions
IBM Functions (PDO_IBM)
IBM DB2
iconv Functions
ID3 Functions
IIS Administration Functions
Image Functions
Imagick Image Library
IMAP
Informix Functions
Informix Functions (PDO_INFORMIX)
Ingres II Functions
IRC Gateway Functions
PHP / Java Integration
JSON Functions
KADM5
LDAP Functions
libxml Functions
Lotus Notes Functions
LZF Functions
Mail Functions
Mailparse Functions
Mathematical Functions
MaxDB PHP Extension
MCAL Functions
Mcrypt Encryption Functions
MCVE (Monetra) Payment Functions
Memcache Functions
Mhash Functions
Mimetype Functions
Ming functions for Flash
Miscellaneous Functions
mnoGoSearch Functions
Microsoft SQL Server Functions
Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
Mohawk Software Session Handler Functions
mSQL Functions
Multibyte String Functions
muscat Functions
MySQL Functions
MySQL Functions (PDO_MYSQL)
MySQL Improved Extension
Ncurses Terminal Screen Control Functions
Network Functions
Newt Functions
NSAPI-specific Functions
Object Aggregation/Composition Functions
Object property and method call overloading
Oracle Functions
ODBC Functions (Unified)
ODBC and DB2 Functions (PDO_ODBC)
oggvorbis
OpenAL Audio Bindings
OpenSSL Functions
Oracle Functions [deprecated]
Oracle Functions (PDO_OCI)
Output Control Functions
Ovrimos SQL Functions
Paradox File Access
Parsekit Functions
Process Control Functions
Regular Expression Functions (Perl-Compatible)
PDF Functions
PDO Functions
Phar archive stream and classes
PHP Options&Information
POSIX Functions
Regular Expression Functions (POSIX Extended)
PostgreSQL Functions
PostgreSQL Functions (PDO_PGSQL)
Printer Functions
Program Execution Functions
PostScript document creation
Pspell Functions
qtdom Functions
Radius
Rar Functions
GNU Readline
GNU Recode Functions
RPM Header Reading Functions
runkit Functions
SAM - Simple Asynchronous Messaging
Satellite CORBA client extension [deprecated]
SCA Functions
SDO Functions
SDO XML Data Access Service Functions
SDO Relational Data Access Service Functions
Semaphore
SESAM Database Functions
PostgreSQL Session Save Handler
Session Handling Functions
Shared Memory Functions
SimpleXML functions
SNMP Functions
SOAP Functions
Socket Functions
Standard PHP Library (SPL) Functions
SQLite Functions
SQLite Functions (PDO_SQLITE)
Secure Shell2 Functions
Statistics Functions
Stream Functions
String Functions
Subversion Functions
Shockwave Flash Functions
Swish Functions
Sybase Functions
TCP Wrappers Functions
Tidy Functions
Tokenizer Functions
Unicode Functions
URL Functions
Variable Handling Functions
Verisign Payflow Pro Functions
vpopmail Functions
W32api Functions
WDDX Functions
win32ps Functions
win32service Functions
xattr Functions
xdiff Functions
XML Parser Functions
XML-RPC Functions
XMLReader functions
XMLWriter Functions
XSL functions
XSLT Functions
YAZ Functions
YP/NIS Functions
Zip File Functions
Zlib Compression Functions
eXTReMe Tracker