文字

SSH2 函数

Table of Contents

  • ssh2_auth_agent — Authenticate over SSH using the ssh agent
  • 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 — Retrieve 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_chmod — Changes file mode
  • 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

用户评论:

[#1] dan at novapulsar dot com [2007-10-25 23:06:30]

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.

[#2] aeolianmeson at blitzeclipse dot com [2007-08-17 12:00:31]

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.

[#3] astribuncio at gmail dot com [2006-08-31 10:17:22]

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

[#4] chris dot britton at cingular dot com [2006-08-11 06:11:12]

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.

[#5] Mike <esnik8202 at sneakemail dot com> [2006-03-26 21:08:32]

To list directory contents:

<?php
$connection 
ssh2_connect(\"hostname\", 22);
ssh2_auth_password(
$connection,\"username\", \"password\");  // or use any of the ssh2_auth_* methods
$sftp = ssh2_sftp($connection);

$dh = opendir(\"ssh2.sftp://$sftp/path/to/dir/\");

while ((
$file = readdir($dh)) !== false) {
  echo \"
$file is in hostname:/path/to/dir\\n\";
}

closedir(
$dh);
?>


(thanks to Sara for assisting)

[#6] dotwho at NSPM dot mac dot com [2005-10-04 15:15:56]

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! :)

[#7] dotwho at NSPM dot mac dot com [2005-10-04 15:12:08]

Trying to compile this ssh PECL extension for Mac OS X (10.4.2) 
with entropy.ch's php5 distribution? Read on: PART 1:
1) Download libssh (I used version 0.11)
http://sourceforge.net/project/showfiles.php?group_id=125852
2) Unzip the directory and cd to the upacked directory in the terminal.
3) run: ./configure; make all install;
libssh should compile and place the output file in src
function  my_ssh_disconnect ( $reason $message $language ) {
  
printf ( "Server disconnected with reason code [%d] and message: %s\n" ,
         
$reason $message );
}

$methods  = array(
  
'kex'  =>  'diffie-hellman-group1-sha1' ,
  
'client_to_server'  => array(
    
'crypt'  =>  '3des-cbc' ,
    
'comp'  =>  'none' ),
  
'server_to_client'  => array(
    
'crypt'  =>  'aes256-cbc,aes192-cbc,aes128-cbc' ,
    
'comp'  =>  'none' ));

$callbacks  = array( 'disconnect'  =>  'my_ssh_disconnect' );

$connection  ssh2_connect ( 'shell.example.com' 22 $methods $callbacks );
if (!
$connection ) die( 'Connection failed' );
?>

参见

  • ssh2_fingerprint() - Retrieve fingerprint of remote server
  • 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

用户评论:

[#1] thessoro at gmail dot com [2015-02-04 19:38:07]

Be careful when providing a specific hostkey order. 

<?php
ssh2_connect
('IP''port', array('hostkey'=>'ssh-rsa, ssh-dss'));
?>


Will only work when the public key of the server is RSA, and not DSA also as expected. This is caused by the empty space before the "ssh-dss". 

So a similar code:

<?php
ssh2_connect
('IP''port',   array('hostkey'=>'ssh-rsa,ssh-dss'));
?>


Will work. The HOSTKEY method is overriden using exactly what you write, so no empty spaces are allowed.

This took me some time that you could save ;)

[#2] rainerkrauss at googlemail dot com [2014-06-08 11:00:44]

Warning! If you open a ssh connection and execute an external program opening another ssh connection it may result in very strange behavior.

I used an sftp connection to get a file list and used "exec" to download the files afterwards with an external sftp. lftp downloaded zeros with no comment, psftp exits with error code 11 most of the time, but sometimes it works - probably depending on how quickly php collects garbage and closes the unused connection first.

As there is no function to close a connection, you need to be sure to destroy all references (unset) to close it.

[#3] Trev White [2013-07-26 09:20:48]

Hi,
If you are having problems with running a ssh2 session and it waits forever during the execution of stream_get_contents, it might be because the remote system has run the command and is now sitting at a # prompt waiting for the next command.  I had this issue on a HP MSA box, here is the code to get around the issue.

Assuming you are connected with your authentication method and $ssh contains the handle.

<?php
$command 
"check disk";
// Open a nice large window to stop wrapping
$stream ssh2_shell ($ssh'xterm'null200200SSH2_TERM_UNIT_CHARS); 

// Hook into the error stream
$errorStream ssh2_fetch_stream($streamSSH2_STREAM_STDERR);  

// Block the streams so we wait until they complete
stream_set_blocking ($streamtrue);
stream_set_blocking($errorStreamtrue);

// Send the commands to the terminal
fwrite ($stream$command PHP_EOL );

// Wait give the terminal a chance to accept and start processing the command, this is a slow storage device after all
sleep(2);

// IMPORTANT BIT!!  Send exit to the terminal to close the connection BEFORE WE WAIT FOR THE STREAM
fwrite ($stream"exit" PHP_EOL );
sleep (2);

// Print the output
echo stream_get_contents($stream);
$errortext=stream_get_contents($errorStream);

if (
strlen($errortext) > 0) {
          
// Error Data
         
echo "Error Data: $errortext";
         exit (
1);
}

// All Good
exit (0);

?>


You can't use ssh2_exec with this method (well at lease I couldn't) because on executing the first command the stream gets blocked and then you can't run the exit command, whereas a terminal seems to use one session.

I hope this helps someone.

[#4] Steve Kamerman [2011-07-05 15:06:07]

Due to a lack of complete examples, here's a simple SSH2 class for connecting to a server, authenticating with public key authentication, verifying the server's fingerprint, issuing commands and reading their STDOUT and properly disconnecting.  Note: You may need to make sure you commands produce output so the response can be pulled.  Some people suggest that the command is not executed until you pull the response back.
<?php
class NiceSSH {
    
// SSH Host
    
private $ssh_host 'myserver.example.com';
    
// SSH Port
    
private $ssh_port 22;
    
// SSH Server Fingerprint
    
private $ssh_server_fp 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
    
// SSH Username
    
private $ssh_auth_user 'username';
    
// SSH Public Key File
    
private $ssh_auth_pub '/home/username/.ssh/id_rsa.pub';
    
// SSH Private Key File
    
private $ssh_auth_priv '/home/username/.ssh/id_rsa';
    
// SSH Private Key Passphrase (null == no passphrase)
    
private $ssh_auth_pass;
    
// SSH Connection
    
private $connection;
    
    public function 
connect() {
        if (!(
$this->connection ssh2_connect($this->ssh_host$this->ssh_port))) {
            throw new 
Exception('Cannot connect to server');
        }
        
$fingerprint ssh2_fingerprint($this->connectionSSH2_FINGERPRINT_MD5 SSH2_FINGERPRINT_HEX);
        if (
strcmp($this->ssh_server_fp$fingerprint) !== 0) {
            throw new 
Exception('Unable to verify server identity!');
        }
        if (!
ssh2_auth_pubkey_file($this->connection$this->ssh_auth_user$this->ssh_auth_pub$this->ssh_auth_priv$this->ssh_auth_pass)) {
            throw new 
Exception('Autentication rejected by server');
        }
    }
    public function 
exec($cmd) {
        if (!(
$stream ssh2_exec($this->connection$cmd))) {
            throw new 
Exception('SSH command failed');
        }
        
stream_set_blocking($streamtrue);
        
$data "";
        while (
$buf fread($stream4096)) {
            
$data .= $buf;
        }
        
fclose($stream);
        return 
$data;
    }
    public function 
disconnect() {
        
$this->exec('echo "EXITING" && exit;');
        
$this->connection null;
    }
    public function 
__destruct() {
        
$this->disconnect();
    }
}
?>


[EDIT BY danbrown AT php DOT net: Contains two bugfixes suggested by 'AlainC' in user note #109185 (removed) on 26-JUN-2012.]

[#5] suri dot suribala dot com [2005-02-24 05:00:09]

With Sara's help, I have the following SS2 class that is quite flexible. If anyone improves it, please feel free to let me know.

<?php

// ssh protocols
// note: once openShell method is used, cmdExec does not work

class ssh2 {

  private 
$host 'host';
  private 
$user 'user';
  private 
$port '22';
  private 
$password 'password';
  private 
$con null;
  private 
$shell_type 'xterm';
  private 
$shell null;
  private 
$log '';

  function 
__construct($host=''$port=''  ) {

     if( 
$host!='' $this->host  $host;
     if( 
$port!='' $this->port  $port;

     
$this->con  ssh2_connect($this->host$this->port);
     if( !
$this->con ) {
       
$this->log .= "Connection failed !"
     }

  }

  function 
authPassword$user ''$password '' ) {

     if( 
$user!='' $this->user  $user;
     if( 
$password!='' $this->password  $password;

     if( !
ssh2_auth_password$this->con$this->user$this->password ) ) {
       
$this->log .= "Authorization failed !"
     }

  }

  function 
openShell$shell_type '' ) {

        if ( 
$shell_type != '' $this->shell_type $shell_type;
    
$this->shell ssh2_shell$this->con,  $this->shell_type );
    if( !
$this->shell $this->log .= " Shell connection failed !";

  }

  function 
writeShell$command '' ) {

    
fwrite($this->shell$command."\n");

  }

  function 
cmdExec( ) {

        
$argc func_num_args();
        
$argv func_get_args();

    
$cmd '';
    for( 
$i=0$i<$argc $i++) {
        if( 
$i != ($argc-1) ) {
          
$cmd .= $argv[$i]." && ";
        }else{
          
$cmd .= $argv[$i];
        }
    }
    echo 
$cmd;

        
$stream ssh2_exec$this->con$cmd );
    
stream_set_blocking$streamtrue );
    return 
fread$stream4096 );

  }

  function 
getLog() {

     return 
$this->log

  }

}

?>

上一篇: 下一篇: