我需要通过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,因为它需要作曲家,而且我不能在语言设置机器上使用它。
如何在不无限运行脚本的情况下opendir()
和readdir()
?
尝试在file_put_contents
后中断
例如:
if (file_put_contents('/path/to/dir/' . $file, $strData) !== false) {
break;
}
或者作为最佳方法,您可以在放置数据后直接使用closedir
do {
if ($file == "." || $file == "..") {
continue;
}
$strData = file_get_contents("ssh2.sftp://" . intval($resSFTP) . "/" . $file);
if (file_put_contents('/path/to/dir/' . $file, $strData)) {
break;
}
} while ($dirHandle && ($file = readdir($dirHandle)) !== false);
closedir($dirHandle);