Home » Php » ssh – Check remote directory using PHP SSH2

ssh – Check remote directory using PHP SSH2

Posted by: admin July 12, 2020 Leave a comment

Questions:

How can I check if a directory ‘xyz’ exist in the remote SSH server using PHP-SSH2?

How to&Answers:

You can use file_exists using sftp prefixing ‘ssh2.sftp://’

For example, with an stablished connection you can:

$sftp = ssh2_sftp($connection);
$fileExists = file_exists('ssh2.sftp://' . $sftp . '/home/marco');

Answer:

I would recommend abandoning PHP SSH2 in lieu of phpseclib, a pure PHP SSH implementation.

Among other things, PHP SSH2’s API sucks. Private keys have to be saved on the filesystem to be loaded whereas with phpseclib all they need be is strings. You can take a key from $_POST without having to dump it to the filesystem as libssh2 requires. To top it off, libssh2 requires you have a separate file for the publickey, which is brain dead, since the private key contains the public key.

ssh2_exec(), from libssh2, also returns ANSI color codes and sometimes never returns output and sometimes does (it’s inconsistent).

Finally, phpseclib is just plain faster.

Answer:

assuming is a linux server

$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$cmd = 'if test -d "/YOUR_DIRECTORY"; then echo 1; fi';
$stream = ssh2_exec($connection, $cmd);

Answer:

 <?php
 $connection = ssh2_connect('shell.example.com', 22);
 ssh2_auth_password($connection, 'username', 'password');

 $sftp = ssh2_sftp($connection);

 $stream = file_exists("ssh2.sftp://$sftp/path/to/file");
 ?>