【发布时间】:2013-01-07 15:28:16
【问题描述】:
我使用的是 Linux 本地计算机,需要定期备份/镜像一些非常大的文件结构。我只能访问 SFTP。
我追求的是简单的一键式解决方案。我最初尝试在 BASH 中编写这个小脚本,但我以前从未使用过它,并且对语法不熟悉,所以我求助于 PHP。 (我确实明白 PHP 不是为这类工作而设计的,但我时间紧迫,没有时间进入 BASH atm)
<?php
//init
parse_str(implode('&', array_slice($argv, 1)), $_GET);
$error = array();
$lPrefix = '/home/hozza/Sites/';
$archiveLocation = '/home/hozza/Backups/';
$lDir = isset($_GET['l']) ? $_GET['l'] : $error[] = 'Local Directory Required';
$rDir = isset($_GET['r']) ? $_GET['r'] : $error[] = 'Remote Directory Required';
$bookmark = isset($_GET['b']) ? $_GET['b'] : $error[] = 'lftp Bookmark Required';
//Check for args
if(count($error) == 0) {
$archiveName = end(explode('/', $lDir)) . '_' . date('Y-m-d_H-i');
//Validate local dir
if(is_dir($lPrefix . $lDir)) {
//preserve Sublime Text 2 config SFTP files
$ST2_SFTP_conf = false;
if(file_exists($lPrefix . $lDir . '/sftp-config.json')) {
$ST2_SFTP_conf = file_get_contents($lPrefix . $lDir . '/sftp-config.json');
unlink($lPrefix . $lDir . '/sftp-config.json');
}
//Start mirror
$lftOutput = explode("\n", shell_exec('lftp -e "mirror -e -p --parallel=10 --log=' . $archiveLocation . 'logs/' . $archiveName . '.txt ' . $rDir . '/ ' . $lPrefix . $lDir . '/; exit top" ' . $bookmark));
//Tar regardless of lftp error or success
$tarOutput = shell_exec('cd ' . $lPrefix . ' && tar -czf ' . $archiveLocation . $archiveName . '.tar.gz ' . $lDir);
//Output completion or errors
shell_exec('notify-send -i gnome-network-properties -t 0 "Mirror & Archive Complete" "' . $archiveName . '\n\n' . implode('\n', $lftOutput) . $tarOutput . '"');
//put back ST2 SFTP conf
if($ST2_SFTP_conf != false) file_put_contents($lPrefix . $lDir . '/sftp-config.json', $ST2_SFTP_conf);
exit;
}
else shell_exec('notify-send -i error -t 0 "Mirror & Archive Error" "' . date('Y-m-d') . ' ' . date('H-i') . '\n' . $lDir . ' \n Does not exist! D:"');
}
else shell_exec('notify-send -i error -t 0 "Mirror & Archive Error" "' . date('Y-m-d') . ' ' . date('H-i') . '\n' . implode('\n', $error) . '"');
?>
它可以通过这样的快捷方式在许多网站上运行...
terminator -T "Mirror & Archive" -e "php ~/Programs/mirror.php l=local-dir_path r=./ b=lftp-bookmark-name"
如果 LFTP 书签中没有密码(不应该因为它以纯文本形式存储),终端会提示输入密码,脚本运行后,会给出一个很好的通知,其中包含有关文件/文件夹/的一些信息速度等。
但是,当脚本在终端中运行时,只有“输入密码”位输出到终端,我希望终端中显示所有输出(通常会显示当前正在使用的文件/文件夹等等)
有人知道怎么做吗?
【问题讨论】:
-
也许您应该从您的
shell_exec()调用中捕获/输出返回值?但是,这只会在命令完全完成之后显示输出。您编写脚本的方式我认为您永远无法看到它的现场直播。 -
是的 atm 它会输出最终结果,但我可能无法像这样。对于如何更好地应对这种情况,您有什么建议吗?
标签: php file-structure bash ftp