Много времени прошло с момента поднятия cacti на серваке. Написал скрипт для бэкапа, который рекурсивно копирует папку cacti со всеми скриптами и файлами графиков, сливает mysql базу и всё это заворачивает в tar и gzip. Можт кому будет интересно.
Собственно листинг:
#/usr/bin/bash
TMPDIR=/space/cacti_bkp
CACTIDIR=/usr/local/apache2/htdocs/cacti
BKPDIR=/space/
BKP=cacti_bkp
if test -d $TMPDIR
then rm -r $TMPDIR; mkdir $TMPDIR
else mkdir $TMPDIR
fi
echo "Copying files.."
(cp -R $CACTIDIR $TMPDIR)
wait
echo "Making SQL dump.."
/usr/local/mysql/bin/mysqldump -ucactiuser -pcactiuser --opt cacti > $TMPDIR/cacti_base.sql
echo "TARing files.."
tar cf $BKPDIR/$BKP.tar $TMPDIR
rm -r $TMPDIR
echo "GZIPing files.."
gzip -9 $BKPDIR/$BKP.tar
chown cacti:cacti $BKPDIR/$BKP.tar.gz
mv $BKPDIR/$BKP.tar.gz $BKPDIR/$BKP`date '+_%Y%m%d_%H%M%S'`.tar.gz
Результат работы скрипта:
-rw-r--r-- 1 cacti cacti 178235269 Jan 10 08:17 cacti_bkp_20100110_082232.tar.gz
-rw-r--r-- 1 cacti cacti 178720071 Jan 13 07:46 cacti_bkp_20100113_075147.tar.gz
В cron:
15 8 * * 0 sh /space/cacti_bkp.sh 1>/dev/null &
20 8 * * * find /space/*.gz -mtime 28 -exec rm {} \;
Первая строка собственно бэкап, вторая ищет старые бэкапы и трёт их.
JunOS, IOS, Unix, Linux, Windows, routing, switching, security, QoS, network design, telecom.. Статьи, заметки. Решил собрать блог, чтоб разместить полезные статьи в одном месте.
среда, 13 января 2010 г.
пятница, 25 декабря 2009 г.
PHP redirection
Очень удобная штука. Редиректит на http://172.26.18.179/cacti/
$ref=$_SERVER['QUERY_STRING'];
if ($ref!='') $ref='?'.$ref;
header('HTTP/1.1 301 Moved Permanently');
header('Location: http://172.26.18.179/cacti/'.$ref);
exit();
?>
$ref=$_SERVER['QUERY_STRING'];
if ($ref!='') $ref='?'.$ref;
header('HTTP/1.1 301 Moved Permanently');
header('Location: http://172.26.18.179/cacti/'.$ref);
exit();
?>
среда, 2 декабря 2009 г.
Perl Threads многопоточность
UPD: Продолжение тут - http://www.k4route.ru/2012/05/perl-threads-queue.html
Имеется много хостов. Периодически нужно цеплятся к каждому и вытягивать какой-нить принтаут или просто давать какаю-нить команду, да так, чтоб одновременно. Множить скрипты? Нужно использовать многопоточность! Начал гуглить. Perl, нити :) Нити-нити! :) Много инфы, мануалы на английском... не очень понятно... разбираюсь... Очередная ссылка, попадая на блог, где чел прям совсем доступно рассказывает про эти самые нити. С базовым пониманием уже можно приступать к изучению крутых мануалов. Собственно ссылко http://nopox.wordpress.com/2007/11/06/multithreading-in-perl-part-2/
И первая моя прога с нитями. Цепляется к массиву хостов по телнет, вытягивает принтаут комманды date.
use threads; #Подключаем модуль нитей
use Net::Telnet; #Модуль Telnet
@sgsns=('172.26.18.163', '172.26.18.164', '172.26.18.165', '172.26.18.166');
$login="log";
$password="pass";
#Создаём столько нитей, сколько у нас элементов в массиве @sgsns
for ($i=0; $i<=$#sgsns; $i++) {
push @threads, threads->create(\&sub1, $sgsns[$i], $login, $password)
}
foreach $thread (@threads) {
$thread->join(); #Сообщаем главной программе,
} #чтоб дожидалась выполнения нити
sub sub1 {
my @InboundParameters = @_;
my $host = $InboundParameters[0];
my $login = $InboundParameters[1];
my $password = $InboundParameters[2];
my $fd=new Net::Telnet (Timeout => 30 , Prompt => '/[\$%#>] $/');
$fd->open($host);
$fd->login($login,$password);
my @lines1=$fd->cmd("date");
print "$host\: @lines1";
print "\n";
}
Имеется много хостов. Периодически нужно цеплятся к каждому и вытягивать какой-нить принтаут или просто давать какаю-нить команду, да так, чтоб одновременно. Множить скрипты? Нужно использовать многопоточность! Начал гуглить. Perl, нити :) Нити-нити! :) Много инфы, мануалы на английском... не очень понятно... разбираюсь... Очередная ссылка, попадая на блог, где чел прям совсем доступно рассказывает про эти самые нити. С базовым пониманием уже можно приступать к изучению крутых мануалов. Собственно ссылко http://nopox.wordpress.com/2007/11/06/multithreading-in-perl-part-2/
И первая моя прога с нитями. Цепляется к массиву хостов по телнет, вытягивает принтаут комманды date.
use threads; #Подключаем модуль нитей
use Net::Telnet; #Модуль Telnet
@sgsns=('172.26.18.163', '172.26.18.164', '172.26.18.165', '172.26.18.166');
$login="log";
$password="pass";
#Создаём столько нитей, сколько у нас элементов в массиве @sgsns
for ($i=0; $i<=$#sgsns; $i++) {
push @threads, threads->create(\&sub1, $sgsns[$i], $login, $password)
}
foreach $thread (@threads) {
$thread->join(); #Сообщаем главной программе,
} #чтоб дожидалась выполнения нити
sub sub1 {
my @InboundParameters = @_;
my $host = $InboundParameters[0];
my $login = $InboundParameters[1];
my $password = $InboundParameters[2];
my $fd=new Net::Telnet (Timeout => 30 , Prompt => '/[\$%#>] $/');
$fd->open($host);
$fd->login($login,$password);
my @lines1=$fd->cmd("date");
print "$host\: @lines1";
print "\n";
}
вторник, 1 декабря 2009 г.
Apache, PHP, PostgeSQL на Solaris 10
Решил потестить, что за зверь такой. Пару раз приходилось поднимать сию базу на линуксах под 1С. Особо желания и времени изучить её не было. Была чёткая последовательность, какой за каким rpm пакет разворачивать. Пришло время :).
Имеется сервак с Solaris 5.10. На нём крутятся разнообразные php приложения, скрипты, собирающие статистику и заливающие её в mysql базу... Чтож, скачал исходник. Развернул. С устновкой самой postgre проблем не было. Стандартные ./configure ; make ; make install. Надо ж и веб морду прикрутить. Качаю phpPgAdmin, разворачиваю в апачевкий DocumentRoot, набираю в браузере заветную строку... :) Тра-ля-ля у вас php собран без ключа --with-pgsql. Грустно... Ищу откуда я ставил php. Вроде бы нашёл. Даю make uninstall, а сей прекраснейший скрипт не знает такого :(. В общем и целом, несколько раз я собирал php, вродеб он даже заливался в нужный каталоги... Короче говоря решил я в конце концов переставить связку apache2+php5, да так, чтоб всё с исходников. Apache у меня стоял пакетом. Собственно хотел зарисовать флаги для configure скрипта.
Apache2:
./configure --prefix=/usr/local/apache2 --enable-mods-shared=all --enable-ssl=shared --enable-ssl --with-ssl=/usr/local/ssl --enable-proxy --enable-proxy-connect --enable-proxy-ftp --enable-proxy-http --enable-so
make ; make install
PHP5:
./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-mysql=/usr/local/mysql/ --with-pgsql=/usr/local/pgsql/ --with-zlib --enable-sockets
make ; make install
Вот собственно говоря и всё :)
Имеется сервак с Solaris 5.10. На нём крутятся разнообразные php приложения, скрипты, собирающие статистику и заливающие её в mysql базу... Чтож, скачал исходник. Развернул. С устновкой самой postgre проблем не было. Стандартные ./configure ; make ; make install. Надо ж и веб морду прикрутить. Качаю phpPgAdmin, разворачиваю в апачевкий DocumentRoot, набираю в браузере заветную строку... :) Тра-ля-ля у вас php собран без ключа --with-pgsql. Грустно... Ищу откуда я ставил php. Вроде бы нашёл. Даю make uninstall, а сей прекраснейший скрипт не знает такого :(. В общем и целом, несколько раз я собирал php, вродеб он даже заливался в нужный каталоги... Короче говоря решил я в конце концов переставить связку apache2+php5, да так, чтоб всё с исходников. Apache у меня стоял пакетом. Собственно хотел зарисовать флаги для configure скрипта.
Apache2:
./configure --prefix=/usr/local/apache2 --enable-mods-shared=all --enable-ssl=shared --enable-ssl --with-ssl=/usr/local/ssl --enable-proxy --enable-proxy-connect --enable-proxy-ftp --enable-proxy-http --enable-so
make ; make install
PHP5:
./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-mysql=/usr/local/mysql/ --with-pgsql=/usr/local/pgsql/ --with-zlib --enable-sockets
make ; make install
Вот собственно говоря и всё :)
четверг, 26 ноября 2009 г.
Find
-atime n True если прошло n дней с создания файла.
-mtime n True если файл был изменен n дней назад.
-exec command Выполнить команду если в поиске пришло true. Завершение команды должно быть отмечено знаком ";". Аргумент для команды {} заменяется найденым путем к файлу.
find /space/*.gz -mtime 28 -exec rm {} \;
Найти архивы gzip в разделе /space/ созданные ранее чем 28 дней и стереть.
-mtime n True если файл был изменен n дней назад.
-exec command Выполнить команду если в поиске пришло true. Завершение команды должно быть отмечено знаком ";". Аргумент для команды {} заменяется найденым путем к файлу.
find /space/*.gz -mtime 28 -exec rm {} \;
Найти архивы gzip в разделе /space/ созданные ранее чем 28 дней и стереть.
среда, 25 ноября 2009 г.
Почистить транзакционные логи MySQL
12.6.1.1. PURGE BINARY LOGS Syntax
PURGE { BINARY | MASTER } LOGS
{ TO 'log_name' | BEFORE datetime_expr }
The binary log is a set of files that contain information about data modifications made by the MySQL server. The log consists of a set of binary log files, plus an index file.
The PURGE BINARY LOGS statement deletes all the binary log files listed in the log index file prior to the specified log file name or date. The log files also are removed from the list recorded in the index file, so that the given log file becomes the first.
This statement has no effect if the --log-bin option has not been enabled.
Examples:
PURGE BINARY LOGS TO 'mysql-bin.010';
PURGE BINARY LOGS BEFORE '2008-04-02 22:46:26';
The BEFORE variant's datetime_expr argument should evaluate to a DATETIME value (a value in 'YYYY-MM-DD hh:mm:ss' format). BINARY and MASTER are synonyms.
This statement is safe to run while slaves are replicating. You do not need to stop them. If you have an active slave that currently is reading one of the logs you are trying to delete, this statement does nothing and fails with an error. However, if a slave is dormant and you happen to purge one of the logs it has yet to read, the slave will be unable to replicate after it comes up.
To safely purge logs, follow this procedure:
1.
On each slave server, use SHOW SLAVE STATUS to check which log it is reading.
2.
Obtain a listing of the binary logs on the master server with SHOW BINARY LOGS.
3.
Determine the earliest log among all the slaves. This is the target log. If all the slaves are up to date, this is the last log on the list.
4.
Make a backup of all the logs you are about to delete. (This step is optional, but always advisable.)
5.
Purge all logs up to but not including the target log.
You can also set the expire_logs_days system variable to expire binary log files automatically after a given number of days (see Section 5.1.3, “Server System Variables”). If you are using replication, you should set the variable no lower than the maximum number of days your slaves might lag behind the master.
Prior to MySQL 5.0.60, PURGE BINARY LOGS TO and PURGE BINARY LOGS BEFORE did not behave in the same way (and neither one behaved correctly) when binary log files listed in the .index file had been removed from the system by some other means (such as using rm on Linux). Beginning with MySQL 5.0.60, both variants of the statement fail with an error in such cases. (Bug#18199, Bug#18453) You can handle such errors by editing the .index file (which is a simple text file) manually and insuring that it lists only the binary log files that are actually present, then running again the PURGE BINARY LOGS statement that failed.
PURGE { BINARY | MASTER } LOGS
{ TO 'log_name' | BEFORE datetime_expr }
The binary log is a set of files that contain information about data modifications made by the MySQL server. The log consists of a set of binary log files, plus an index file.
The PURGE BINARY LOGS statement deletes all the binary log files listed in the log index file prior to the specified log file name or date. The log files also are removed from the list recorded in the index file, so that the given log file becomes the first.
This statement has no effect if the --log-bin option has not been enabled.
Examples:
PURGE BINARY LOGS TO 'mysql-bin.010';
PURGE BINARY LOGS BEFORE '2008-04-02 22:46:26';
The BEFORE variant's datetime_expr argument should evaluate to a DATETIME value (a value in 'YYYY-MM-DD hh:mm:ss' format). BINARY and MASTER are synonyms.
This statement is safe to run while slaves are replicating. You do not need to stop them. If you have an active slave that currently is reading one of the logs you are trying to delete, this statement does nothing and fails with an error. However, if a slave is dormant and you happen to purge one of the logs it has yet to read, the slave will be unable to replicate after it comes up.
To safely purge logs, follow this procedure:
1.
On each slave server, use SHOW SLAVE STATUS to check which log it is reading.
2.
Obtain a listing of the binary logs on the master server with SHOW BINARY LOGS.
3.
Determine the earliest log among all the slaves. This is the target log. If all the slaves are up to date, this is the last log on the list.
4.
Make a backup of all the logs you are about to delete. (This step is optional, but always advisable.)
5.
Purge all logs up to but not including the target log.
You can also set the expire_logs_days system variable to expire binary log files automatically after a given number of days (see Section 5.1.3, “Server System Variables”). If you are using replication, you should set the variable no lower than the maximum number of days your slaves might lag behind the master.
Prior to MySQL 5.0.60, PURGE BINARY LOGS TO and PURGE BINARY LOGS BEFORE did not behave in the same way (and neither one behaved correctly) when binary log files listed in the .index file had been removed from the system by some other means (such as using rm on Linux). Beginning with MySQL 5.0.60, both variants of the statement fail with an error in such cases. (Bug#18199, Bug#18453) You can handle such errors by editing the .index file (which is a simple text file) manually and insuring that it lists only the binary log files that are actually present, then running again the PURGE BINARY LOGS statement that failed.
вторник, 10 ноября 2009 г.
Perl и время
($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime(time);
$year=$year+1900;
$mon=$mon+1;
print "$year-$mon-$mday $hour:$min:$sec";
print "\n";
$year=$year+1900;
$mon=$mon+1;
print "$year-$mon-$mday $hour:$min:$sec";
print "\n";
Подписаться на:
Сообщения (Atom)