【发布时间】:2017-08-11 20:59:31
【问题描述】:
我需要通过ssh从远程服务器的根目录获取一些文件,本地机器使用php7。我制作了这个脚本:
<?php
$strServer = "my-server.com";
$strServerPort = "22";
$strServerUsername = "my.username";
$strServerPassword = "my-password";
$resConnection = ssh2_connect($strServer, $strServerPort);
if(ssh2_auth_password($resConnection, $strServerUsername, $strServerPassword)) {
$files = array();
$resSFTP = ssh2_sftp($resConnection);
$dirHandle = opendir("ssh2.sftp://" . intval($resSFTP) . "/");
while ($dirHandle && ($file = readdir($dirHandle)) !== false) {
if ($file == "." || $file == "..") {
continue;
}
$strData = file_get_contents("ssh2.sftp://" . intval($resSFTP) . "/" . $file);
file_put_contents('/path/to/dir/' . $file, $strData);
}
ssh2_exec($resConnection, 'exit');
unset($resConnection);
}
die;
它有效,即文件被提取,但脚本永远不会停止。
如果我知道要获取的文件的名称,那么脚本将是:
if(ssh2_auth_password($resConnection, $strServerUsername, $strServerPassword)) {
$files = array();
$resSFTP = ssh2_sftp($resConnection);
$file = 'name_of_the_file.xlsx';
$strData = file_get_contents("ssh2.sftp://" . intval($resSFTP) . "/" . $file);
file_put_contents('/path/to/dir/' . $file, $strData);
}
然后文件被提取,脚本在执行结束时停止。
我不能使用 phpseclib,因为它需要 composer 并且我不能在本地机器上使用它。
如果不让脚本无限运行,我可以对opendir() 和readdir() 做什么?
【问题讨论】:
标签: php php-7 opendir readdir libssh2