How to list files of a directory in an other serve

2019-01-18 23:00发布

I would like to list the files of a directory in an other server

I am connected to an other server using ssh2_connect function the connection is going well and i am able to fetch a desired file but i am not sure how the files can be listed.

Any help is appriciated!

标签: php ssh
3条回答
地球回转人心会变
2楼-- · 2019-01-18 23:34

http://www.php.net/manual/en/function.ssh2-exec.php

You give it the ls command, assuming it is a UNIX-based system (usually the case), otherwise the OP-specific command like dir for Windows.

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

$stream = ssh2_exec($connection, 'ls');
?>
查看更多
等我变得足够好
3楼-- · 2019-01-18 23:37

In case anybody is struggling to get this to work, and you are running PHP 5.6.28 there was a recent update that either created a requirement or introduced a bug where intval() must be used on each SFTP folder/file access function:

$handle = opendir("ssh2.sftp://".intval($sftp)."/path/to/directory");
查看更多
对你真心纯属浪费
4楼-- · 2019-01-18 23:48

You can use ssh2_sftp and opendir, like this:

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

$sftp = ssh2_sftp($connection);
$sftp_fd = intval($sftp);

$handle = opendir("ssh2.sftp://$sftp_fd/path/to/directory");
echo "Directory handle: $handle\n";
echo "Entries:\n";
while (false != ($entry = readdir($handle))){
    echo "$entry\n";
}
查看更多
登录 后发表回答