我想在其他服务器中列出目录的文件
我使用ssh2_connect函数连接到其他服务器,连接正常,我可以获取所需的文件,但我不确定如何列出这些文件。
任何帮助都是适当的!
答案 0 :(得分:35)
<?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";
}
答案 1 :(得分:1)
http://www.php.net/manual/en/function.ssh2-exec.php
你给它ls
命令,假设它是一个基于UNIX的系统(通常是这种情况),否则特定于OP的命令,如dir
for Windows。
<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$stream = ssh2_exec($connection, 'ls');
?>
答案 2 :(得分:1)
这是一种可以递归扫描目录并在设置了递归参数的情况下返回多维数组的方法,或者仅扫描路径并返回包含该目录中文件的单维数组(如果未设置)。如果需要,可以修改为在非递归模式下包含不包含目录的目录。
将其创建为类可以使以后易于重用。我只包括了班上回答问题所需的方法。
$host = 'example.com';
$port = 22;
$username = 'user1';
$password = 'password123';
$path = '.';
$recursive = true;
$conn = new SFTP($host, $port);
$conn->login($username, $password);
$files = $conn->ls($path, $recursive);
var_dump($files);
class SFTP
{
private $connection;
private $sftp;
public function __construct($host, $port = 22)
{
$this->connection = @ssh2_connect($host, $port);
if (! $this->connection)
throw new Exception("Could not connect to $host on port $port.");
}
public function login($username, $password)
{
if (! @ssh2_auth_password($this->connection, $username, $password))
throw new Exception("Could not authenticate with username $username");
$this->sftp = @ssh2_sftp($this->connection);
if (! $this->sftp)
throw new Exception("Could not initialize SFTP subsystem.");
}
public function ls($remote_path, $recursive = false)
{
$tmp = $this->sftp;
$sftp = intval($tmp);
$dir = "ssh2.sftp://$sftp/$remote_path";
$contents = array();
$handle = opendir($dir);
while (($file = readdir($handle)) !== false) {
if (substr("$file", 0, 1) != "."){
if (is_dir("$dir/$file")){
if ($recursive) {
$contents[$file] = array();
$contents[$file] = $this->ls("$remote_path/$file", $recursive);
}
} else {
$contents[] = $file;
}
}
}
closedir($handle);
return $contents;
}
}