I'm trying to get all .log and .txt files from an Ubuntu server using php 5.3.5 (WAMP). This is my third day using php ... total beginner. I'm reading some doc, but trying to accomplish useful tasks along the way, as to reinforce my learning. Additionally, when I use the code below, the .txt and .log 开发者_Go百科files are printed in the browser but there is no structure (hard to read). How can I print each path on a single line (not sure if it should be apart of the sub process like echo -e \n in the ssh2exec function or a line I should add to the php code? Any help is appreciated ... thanks!
<?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
}
}
?>
In a shell, a new line is established by newline character ("\n"
). In HTML, you'll need to either use CSS to make these newlines count:
echo '<div style="white-space: pre;">';
echo htmlspecialchars($data);
echo '</div>';
or insert <br/>
elements:
echo nl2br(htmlspecialchars($data));
Here is a complete example, including download links and functionality:
<?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>';
精彩评论