我正在尝试使用php 5.3.5(WAMP)从Ubuntu服务器获取所有.log和.txt文件。这是我第三天使用php ...初学者。我正在阅读一些文档,但是尝试在此过程中完成有用的任务,以加强我的学习。另外,当我使用下面的代码时,.txt和.log文件会在浏览器中打印出来,但是没有结构(难以阅读)。我如何才能在一行上打印每个路径(不知道它是否应该属于子进程,例如ssh2exec函数中的echo -e \ n还是应该添加到php代码中的行?任何帮助表示赞赏...谢谢!
<?php
if (!function_exists("ssh2_connect")) die("function ssh2_connect doesn't exist");
if(!($ssh = ssh2_connect('10.5.32.12', 22))) {
echo "fail: unable to establish connection\n";
} else {
if(!ssh2_auth_password($ssh, 'root', '********')) {
echo "fail: unable to authenticate\n";
} else {
echo "Okay: Logged in ... \n";
$stream = ssh2_exec($ssh, 'find / -name *.log -o -name *.txt');
stream_set_blocking($stream, true);
$data = '';
while($buffer = fread($stream, 4096)) {
$data .= $buffer;
}
fclose($stream);
echo $data; // user
}
}
?>
最佳答案
在 shell 程序中,由换行符("\n"
)建立新行。在HTML中,您将需要使用CSS来使这些换行符生效:
echo '<div style="white-space: pre;">';
echo htmlspecialchars($data);
echo '</div>';
或插入
<br/>
元素:echo nl2br(htmlspecialchars($data));
这是一个完整的示例,包括下载链接和功能:
<?php
if (! ($ssh = ssh2_connect('10.5.32.12', 22))) {
throw new Exception('Connection failed');
}
if (!ssh2_auth_password($ssh, 'root', '*******')) {
throw new Exception('Authentication failed');
}
if (isset($_GET['download'])) {
$fn = $_GET['download'];
if (! preg_match('/^[a-zA-Z0-9 .-_\\/]+(\\.txt|\\.log)$/', $fn)) {
throw new Exception('access denied');
}
header('X-Content-Type-Options: nosniff');
header('Content-Type: text/plain');
$sftp = ssh2_sftp($ssh);
$url = 'ssh2.sftp://' . $sftp . $fn;
readfile($url);
exit();
}
$stream = ssh2_exec($ssh, 'find / -name "*.log" -o -name "*.txt"');
stream_set_blocking($stream, true);
$data = stream_get_contents($stream);
$files = explode("\n", $data);
echo '<ul>';
foreach ($files as $f) {
if ($f == '') continue;
$url = $_SERVER['PHP_SELF'] . '?download=' . urlencode($f);
echo '<li><a href="' . htmlspecialchars($url) . '">';
echo htmlspecialchars($f);
echo '</a></li>';
}
echo '</ul>';
关于php - 我正在尝试在Win7机器上使用php 5.3.5从ubuntu服务器检索文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6986525/