2009-09-14 Ramon Novoa <rnovoa@artica.es>

* unix, unix/pandora_agent_installer,
          unix/plugins, unix/pandora_agent,
          unix/pandora_agent_daemon, unix/AUTHORS,
          unix/pandora_agent.conf, unix/COPYING,
          unix/pandora_agent.spec, unix/tentacle_client,
          unix/README: Added to repository. Generic Pandora FMS Unix agent
          written in PERL. The skeleton files where copied from the linux
          subdirectory.




git-svn-id: https://svn.code.sf.net/p/pandora/code/trunk@1940 c3f86ba8-e40f-0410-aaad-9ba5e7f4b01f
This commit is contained in:
Ramon Novoa 2009-09-14 15:57:00 +00:00
parent 9c009b6b94
commit 2b2bf344ce
11 changed files with 2047 additions and 0 deletions

View File

@ -1,3 +1,14 @@
2009-09-14 Ramon Novoa <rnovoa@artica.es>
* unix, unix/pandora_agent_installer,
unix/plugins, unix/pandora_agent,
unix/pandora_agent_daemon, unix/AUTHORS,
unix/pandora_agent.conf, unix/COPYING,
unix/pandora_agent.spec, unix/tentacle_client,
unix/README: Added to repository. Generic Pandora FMS Unix agent
written in PERL. The skeleton files where copied from the linux
subdirectory.
2009-09-01 Sancho Lerena <slerena@artica.es> 2009-09-01 Sancho Lerena <slerena@artica.es>
* linux/pandora_agent.spec: Using chkconfig to manage service * linux/pandora_agent.spec: Using chkconfig to manage service

View File

@ -0,0 +1,3 @@
Sancho Lerena <slerena@gmail.com>
Manuel Arostegui <manuel.arostegui@artica.es>
Ramon Novoa <rnovoa@artica.es>

View File

@ -0,0 +1,92 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS

View File

@ -0,0 +1,58 @@
Pandora FMS : The Free Monitoring System v1.3.1
===============================================
http://pandora.sourceforge.net
How to install
--------------
Please refer to documentation on our website. This includes schemas, quick-install
guides and how to use preconfigured packages and installers for all components.
What is Pandora FMS?
--------------------
Pandora FMS is a monitoring application to watch systems and applications.
Pandora FMS allows to know the status of any element of your bussiness systems.
Pandora FMS watches your hardware, your software, your multilayer system and, of
course, your Operating System. Pandora FMS can detect a network interface down
or the movement of any NASDAQ new technology market value. If you wish, Pandora
FMS can send a SMS message when your system or your application fails... or when
Google stock value drops below 330 US$.
Pandora FMS will adjust, like an octopus, to your systems and requirements,
because it has been designed to be open, modular, multiplattform and easy to
customize. Pandora FMS is developed for system administrators.
What else can Pandora FMS do?
-----------------------------
Pandora FMS is a monitoring tool that not only measures if a parameter is right
or wrong. Pandora FMS can quantify the state (right or wrong), or store a value
(numeric or alphanumeric) for months if necessary. Pandora FMS can measure
performances, compare values among differen systems and set alarms over
thresholds. Pandora FMS works against a Database so that it can generate
reports, statistics, SLA and meausre anything: Operating Systems, aplications
and hardware systems—such as firewalls, proxies, Databases, web servers, VPN,
routers, switches, processes, services, remote accesses to servers, etc.
everything integrated in a open and distributed architecture. Pandora FMS can be
deployed over any Operating System, with specific agents for each platform.
There are already agents for Windows (2000, XP, 2003), GNU/Linux, Solaris,
HP-UX, BSD, AIX, IPSO and OpenWRT.
Pandora FMS not only gathers information through its agents, but it can also
monitor any hardware sistem with TCP/IP connectivity —such as load balancing
systems, routers, switches, printers, etc.— through SNMP and TCP/ICMP checks.
Often the question "What kind of things can be monitored?" shows up, since
Pandora FMS can —virtually— monitor anthing, sometimes is convenient give some
specific examples. Pandora FMS can monitor any process or system that, though a
command, returns a value, and also any value inside a log file of the Operating
System.
License
-------
The project is distributed under the GPL License v2 or later.
Copyright (C) 2004-2008 Pandora FMS development team

601
pandora_agents/unix/pandora_agent Executable file
View File

@ -0,0 +1,601 @@
#!/usr/bin/perl
# **********************************************************************
# Pandora FMS Generic Linux Agent
# (c) 2009 Artica Soluciones Tecnológicas
# with the help of many people. Please see http://pandorafms.org
# This code is licensed under GPL 2.0 license.
# **********************************************************************
use strict;
use warnings;
use POSIX qw(strftime floor);
use Sys::Hostname;
use File::Basename;
use File::Copy;
use constant AGENT_VERSION => '3.0';
use constant AGENT_BUILD => '090831';
# OS and OS version
my $OS = $^O;
my $OS_VERSION;
# Used to calculate the MD5 checksum of a string
use constant MOD232 => 2**32;
# Directory where pandora_agent.conf is located
my $ConfDir = '';
# Pandora FMS agent configuration file
my $ConfFile = 'pandora_agent.conf';
# Configuration tokens
my %Conf = (
'server_ip' => 'localhost',
'server_path' => '/var/spool/pandora/data_in',
'temporal' => '/var/spool/pandora/data_out',
'log_file' => '/var/log/pandora/pandora_agent.log',
'interval' => 300,
'debug' => 0,
'agent_name' => hostname (),
'description' => '',
'group' => '',
'encoding' => 'ISO-8859-15',
'server_port' => 41121,
'transfer_mode' => 'tentacle',
'server_pwd' => '',
'server_ssl' => 'no',
'server_opts' => '',
'delayed_startup' => 0,
'pandora_nice' => 0,
'cron_mode' => 0,
'remote_config' => 0,
'secondary_mode' => 'never',
'secondary_server_ip' => 'localhost',
'secondary_server_path' => '/var/spool/pandora/data_in',
'secondary_server_port' => 41121,
'secondary_transfer_mode' => 'tentacle',
'secondary_server_pwd' => 'mypassword',
'secondary_server_ssl' => 'no',
'secondary_server_opts' => '',
'autotime' => 0
# Missing: group,
);
# Modules
my @Modules;
# Plugins
my @Plugins;
# Logfile file handle
my $LogFileFH;
# Agent name MD5;
my $AgentMD5;
# Remote configuration file name
my $RemoteConfFile;
# Remote md5 file name
my $RemoteMD5File;
################################################################################
# Print usage information and exit.
################################################################################
sub print_usage () {
print "\nUsage: $0 <Pandora home>\n\n";
print "\tPandora home is the directory where pandora_agent.conf is located,\n";
print "\tby default /etc/pandora.\n\n";
exit 1;
}
################################################################################
# Print an error message and exit.
################################################################################
sub error ($) {
my $msg = shift;
print ("[ERROR] $msg\n\n");
exit 1;
}
################################################################################
# Open the agent logfile and start logging.
################################################################################
sub start_log () {
# Get the logfile
my $log_file_name = read_config ('logfile');
$log_file_name = '/var/log/pandora/pandora_agent.log' unless defined ($log_file_name);
# Open it
open ($LogFileFH, "> $log_file_name") or error ("Could not open log file '$log_file_name' for writing: $!.");
print "Logging to $log_file_name\n";
}
################################################################################
# Close the agent logfile and stop logging.
################################################################################
sub stop_log () {
close ($LogFileFH);
}
################################################################################
# Log a message to the agent logfile.
################################################################################
sub log_message ($$;$) {
my ($source, $msg, $dest) = @_;
if (defined ($dest)) {
print $dest strftime ('%Y/%m/%d %H:%M:%S', localtime ()) . " - [$source] - $msg\n";
} else {
print $LogFileFH strftime ('%Y/%m/%d %H:%M:%S', localtime ()) . " - [$source] - $msg\n";
}
}
################################################################################
# Read configuration file. Exit on error.
################################################################################
sub read_config (;$) {
my $token = shift;
my $module;
error ("File '$ConfDir/$ConfFile' not found.") unless (-e "$ConfDir/$ConfFile");
open (CONF_FILE, "$ConfDir/$ConfFile") or error ("Could not open file '$ConfDir/$ConfFile': $!.");
while (my $line = <CONF_FILE>) {
# Skip comments and empty lines
next if ($line =~ m/^\s*#/) or ($line =~ m/^\s*$/);
# Single token search
if (defined ($token)) {
return $2 if ($line =~ /^\s*(\S+)\s+(.*)$/ && $1 eq $token);
next;
}
# Module definition
if ($line =~ /^\s*module_begin\s*$/) {
$module = {
'name' => '',
'type' => 'generic_data',
'description' => '',
'exec' => '',
'description' => '',
'interval' => 1,
'counter' => 0,
'max' => 0,
'min' => 0,
'postprocess' => 0
};
} elsif ($line =~ /^\s*module_name\s+(.+)$/) {
$module->{'name'} = $1;
} elsif ($line =~ /^\s*module_description\s+(.+)$/) {
$module->{'description'} = $1;
} elsif ($line =~ /^\s*module_type\s+(\S+)\s*$/) {
$module->{'type'} = $1;
} elsif ($line =~ /^\s*module_exec\s+(.+)$/) {
$module->{'exec'} = $1;
} elsif ($line =~ /^\s*module_max\s+(\d+)\s*$/) {
$module->{'max'} = $1;
} elsif ($line =~ /^\s*module_min\s+(\d+)\s*$/) {
$module->{'max'} = $1;
} elsif ($line =~ /^\s*module_end\s*$/) {
next unless ($module->{'name'} ne '') and ($module->{'exec'} ne '');
push (@Modules, $module);
# Plugin
} elsif ($line =~ /^\s*module_plugin\s+(.+)$/) {
push (@Plugins, $1);
# Configuration token
} elsif ($line =~ /^\s*(\S+)\s+(.*)$/) {
log_message ('setup', "$1 is $2");
$Conf{$1} = $2;
# Remove trailing spaces
$Conf{$1} =~ s/\s*$//;
}
}
# Update the agent MD5 since agent_name may have changed
$AgentMD5 = md5 ($Conf{'agent_name'}) unless (defined ($token));
$RemoteConfFile = "$AgentMD5.conf";
$RemoteMD5File = "$AgentMD5.md5";
close (CONF_FILE);
return '';
}
################################################################################
# Remove any trailing / from directory names.
################################################################################
sub fix_directory ($) {
my $dir = shift;
my $char = chop ($dir);
return $dir if ($char eq '/');
return $dir . $char;
}
################################################################################
# Sends a file to the server.
################################################################################
#sub send_file ($;$) {
sub send_file {
my ($file, $secondary) = @_;
my $output;
if ($Conf{'transfer_mode'} eq 'tentacle') {
$output = `tentacle_client -v -a $Conf{'server_ip'} -p $Conf{'server_port'} $Conf{'server_opts'} $file 2>&1 >/dev/null`;
} elsif ($Conf{'transfer_mode'} eq 'ssh') {
$output = `scp -P $Conf{'server_port'} $file pandora@"$Conf{'server_ip'}:$Conf{'server_path'}" 2>&1 >/dev/null`;
} elsif ($Conf{'transfer_mode'} eq 'ftp') {
my $base = basename ($file);
my $dir = dirname ($file);
$output = `ftp -n $Conf{'server_ip'} $Conf{'server_port'} 2>&1 >/dev/null <<FEOF1
quote USER pandora
quote PASS $Conf{'server_pwd'}
lcd "$dir"
cd "$Conf{'server_path'}"
put "$base"
quit
FEOF1`
} elsif ($Conf{'transfer_mode'} eq 'local') {
$output = `cp $file $Conf{'server_path'}/ 2>&1 >/dev/null`;
}
# Get the errorlevel
my $rc = $? >> 8;
if ($rc != 0) {
log_message ('error', "Error sending file '$file': $output");
}
return $rc unless (defined ($secondary));
# Send the file to the secondary server
return $rc unless ($Conf{'secondary_mode'} eq 'always' || ($Conf{'secondary_mode'} eq 'on_error' && $rc != 0));
swap_servers ();
$rc = send_file ($file);
swap_servers ();
return $rc;
}
################################################################################
# Swap primary and secondary servers.
################################################################################
sub swap_servers () {
($Conf{'server_ip'}, $Conf{'secondary_server_ip'}) = ($Conf{'secondary_server_ip'}, $Conf{'server_ip'});
($Conf{'server_path'}, $Conf{'secondary_server_path'}) = ($Conf{'secondary_server_path'}, $Conf{'server_path'});
($Conf{'server_port'}, $Conf{'secondary_server_port'}) = ($Conf{'secondary_server_port'}, $Conf{'server_port'});
($Conf{'server_transfer_mode'}, $Conf{'secondary_server_transfer_mode'}) = ($Conf{'secondary_server_transfer_mode'}, $Conf{'server_transfer_mode'});
($Conf{'server_pwd'}, $Conf{'secondary_server_pwd'}) = ($Conf{'secondary_server_pwd'}, $Conf{'server_pwd'});
($Conf{'server_ssl'}, $Conf{'secondary_server_ssl'}) = ($Conf{'secondary_server_ssl'}, $Conf{'server_ssl'});
($Conf{'server_opts'}, $Conf{'secondary_server_opts'}) = ($Conf{'secondary_server_opts'}, $Conf{'server_opts'});
}
################################################################################
# Receive a file from the server.
################################################################################
sub recv_file ($) {
my $file = shift;
my $output;
if ($Conf{'transfer_mode'} eq 'tentacle') {
$output = `cd "$Conf{'temporal'}"; tentacle_client -v -g -a $Conf{'server_ip'} -p $Conf{'server_port'} $Conf{'server_opts'} $file 2>&1 >/dev/null`
} elsif ($Conf{'transfer_mode'} eq 'ssh') {
$output = `scp -P $Conf{'server_port'} pandora@"$Conf{'server_ip'}:$Conf{'server_path'}/$file" $Conf{'temporal'} 2>&1 >/dev/null`;
} elsif ($Conf{'transfer_mode'} eq 'ftp') {
my $base = basename ($file);
my $dir = dirname ($file);
$output = `ftp -n $Conf{'server_ip'} $Conf{'server_port'} 2>&1 >/dev/null <<FEOF1
quote USER pandora
quote PASS $Conf{'server_pwd'}
lcd "$Conf{'temporal'}"
cd "$Conf{'server_path'}"
get "$file"
quit
FEOF1`
} elsif ($Conf{'transfer_mode'} eq 'local') {
$output = `cp $Conf{'server_path'}/$file $Conf{'temporal'} 2>&1 >/dev/null`;
}
# Get the errorlevel
my $rc = $? >> 8;
if ($rc != 0) {
log_message ('error', "Error sending XML data file: $output");
}
return $rc;
}
################################################################################
# Check the server for a remote configuration.
################################################################################
sub check_remote_config () {
return unless ($Conf{'remote_config'} eq '1' && $Conf{'debug'} eq '0');
# Calculate the configuration file MD5 digest
open (CONF_FILE, "$ConfDir/$ConfFile") or error ("Could not open file '$ConfDir/$ConfFile': $!.");
binmode(CONF_FILE);
my $conf_md5 = md5 (join ('', <CONF_FILE>));
close (CONF_FILE);
# Get the remote MD5 file
if (recv_file ($RemoteMD5File) != 0) {
open (MD5_FILE, "> $Conf{'temporal'}/$RemoteMD5File") || error ("Could not open file '$ConfDir/$RemoteMD5File' for writing: $!.");
print MD5_FILE $conf_md5;
close (MD5_FILE);
copy ("$ConfDir/$ConfFile", "$Conf{'temporal'}/$RemoteConfFile");
send_file ("$Conf{'temporal'}/$RemoteConfFile");
send_file ("$Conf{'temporal'}/$RemoteMD5File");
log_message ('remote config', 'Uploading configuration for the first time.');
unlink ("$Conf{'temporal'}/$RemoteConfFile");
unlink ("$Conf{'temporal'}/$RemoteMD5File");
return;
}
open (MD5_FILE, "< $Conf{'temporal'}/$RemoteMD5File") || error ("Could not open file '$ConfDir/$RemoteMD5File' for writing: $!.");
my $remote_conf_md5 = <MD5_FILE>;
close (MD5_FILE);
# No changes
return if ($remote_conf_md5 eq $conf_md5);
# Get the new configuration file
return if (recv_file ($RemoteConfFile) != 0);
log_message ('remote config', 'Configuration has changed!');
# Save the new configuration and reload it
move ("$Conf{'temporal'}/$RemoteConfFile", "$ConfDir/$ConfFile");
read_config ();
# Log file may have changed
stop_log ();
start_log ();
}
###############################################################################
# MD5 leftrotate function. See http://en.wikipedia.org/wiki/MD5#Pseudocode.
###############################################################################
sub leftrotate ($$) {
my ($x, $c) = @_;
return ($x << $c) | ($x >> (32 - $c));
}
###############################################################################
# Initialize some variables needed by the MD5 algorithm.
# See http://en.wikipedia.org/wiki/MD5#Pseudocode.
###############################################################################
my (@R, @K);
sub md5_init () {
# R specifies the per-round shift amounts
@R = (7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21);
# Use binary integer part of the sines of integers (radians) as constants
for (my $i = 0; $i < 64; $i++) {
$K[$i] = floor(abs(sin($i + 1)) * MOD232);
}
}
###############################################################################
# Return the MD5 checksum of the given string.
# Pseudocode from http://en.wikipedia.org/wiki/MD5#Pseudocode.
###############################################################################
sub md5 ($) {
my $str = shift;
# Note: All variables are unsigned 32 bits and wrap modulo 2^32 when calculating
# Initialize variables
my $h0 = 0x67452301;
my $h1 = 0xEFCDAB89;
my $h2 = 0x98BADCFE;
my $h3 = 0x10325476;
# Pre-processing
my $msg = unpack ("B*", pack ("A*", $str));
my $bit_len = length ($msg);
# Append "1" bit to message
$msg .= '1';
# Append "0" bits until message length in bits ≡ 448 (mod 512)
$msg .= '0' while ((length ($msg) % 512) != 448);
# Append bit /* bit, not byte */ length of unpadded message as 64-bit little-endian integer to message
$msg .= unpack ("B64", pack ("VV", $bit_len));
# Process the message in successive 512-bit chunks
for (my $i = 0; $i < length ($msg); $i += 512) {
my @w;
my $chunk = substr ($msg, $i, 512);
# Break chunk into sixteen 32-bit little-endian words w[i], 0 <= i <= 15
for (my $j = 0; $j < length ($chunk); $j += 32) {
push (@w, unpack ("V", pack ("B32", substr ($chunk, $j, 32))));
}
# Initialize hash value for this chunk
my $a = $h0;
my $b = $h1;
my $c = $h2;
my $d = $h3;
my $f;
my $g;
# Main loop
for (my $y = 0; $y < 64; $y++) {
if ($y <= 15) {
$f = $d ^ ($b & ($c ^ $d));
$g = $y;
}
elsif ($y <= 31) {
$f = $c ^ ($d & ($b ^ $c));
$g = (5 * $y + 1) % 16;
}
elsif ($y <= 47) {
$f = $b ^ $c ^ $d;
$g = (3 * $y + 5) % 16;
}
else {
$f = $c ^ ($b | (~ $d));
$g = (7 * $y) % 16;
}
my $temp = $d;
$d = $c;
$c = $b;
$b = ($b + leftrotate (($a + $f + $K[$y] + $w[$g]) % MOD232, $R[$y])) % MOD232;
$a = $temp;
}
# Add this chunk's hash to result so far
$h0 = ($h0 + $a) % MOD232;
$h1 = ($h1 + $b) % MOD232;
$h2 = ($h2 + $c) % MOD232;
$h3 = ($h3 + $d) % MOD232;
}
# Digest := h0 append h1 append h2 append h3 #(expressed as little-endian)
return unpack ("H*", pack ("V", $h0)) . unpack ("H*", pack ("V", $h1)) . unpack ("H*", pack ("V", $h2)) . unpack ("H*", pack ("V", $h3));
}
################################################################################
# Try to guess the OS version.
################################################################################
sub guess_os_version ($) {
my $os = shift;
# Linux
return `lsb_release -sd` if ($os eq 'linux');
# Solaris
return `uname -r` if ($os eq 'solaris');
# AIX
if ($os eq 'aix') {
return "$2.$1" if (`uname -rv` =~ /\s*(\d)\s+(\d)\s*/);
}
# HP-UX
return `uname -r` if ($os eq 'aix');
return '';
}
################################################################################
# Main.
################################################################################
# Check command line arguments
print_usage unless ($#ARGV == 0);
$ConfDir = $ARGV[0];
error ("Directory '$ConfDir' does not exist.") unless (-d "$ConfDir");
# Guess the OS version
$OS_VERSION = guess_os_version ($OS);
# Initialize MD5 variables
md5_init ();
# Start logging
start_log ();
# Read configuration file
read_config ();
# Fix directory names
$ConfDir = fix_directory ($ConfDir);
$Conf{'temporal'} = fix_directory ($Conf{'temporal'});
$Conf{'server_path'} = fix_directory ($Conf{'server_path'});
$Conf{'secondary_server_path'} = fix_directory ($Conf{'secondary_server_path'});
# Startup delay
log_message ('log', 'Sleeping for ' . $Conf{'delayed_startup'} . ' seconds.') if ($Conf{'delayed_startup'} > 0);
sleep ($Conf{'delayed_startup'});
# Loop
while (1) {
# Check for a new configuration
check_remote_config ();
my $xml = "<?xml version='1.0' encoding='" . $Conf{'encoding'} . "'?>\n" .
"<agent_data description='" . $Conf{'description'} ."' group='" . $Conf{'group'} .
"' os_name='$OS' os_version='$OS_VERSION' interval='" . $Conf{'interval'} .
"' version='" . AGENT_VERSION . ($Conf{'autotime'} eq '1' ? '' : "' timestamp='" . strftime ('%Y/%m/%d %H:%M:%S', localtime ())) .
"' agent_name='" . $Conf{'agent_name'} . "'>\n";
# Execute modules
foreach my $module (@Modules) {
# Check module interval
next unless (++$module->{'counter'} >= $module->{'interval'});
# Reset module counter
$module->{'counter'} = 0;
# Execute the module and generate the XML
my @data = `$module->{'exec'} 2> /dev/null`;
next unless ($? eq 0 && defined ($data[0]));
$xml .= " <module>\n" .
" <name><![CDATA[$module->{'name'}]]></name>\n" .
" <description><![CDATA[$module->{'description'}]]></description>\n";
# Data list
if ($#data > 0) {
$xml .= " <datalist>\n";
foreach my $data_item (@data) {
chomp ($data_item);
$xml .= " <data><value><![CDATA[$data_item]]></value></data>\n";
}
$xml .= " </datalist>\n";
# Single data
} else {
chomp ($data[0]);
$xml .= " <data><![CDATA[$data[0]]]></data>\n";
}
$xml .= " </module>\n";
}
# Execute plugins
foreach my $plugin (@Plugins) {
my $output = `$ConfDir/plugins/$plugin`;
next unless ($? eq 0);
$xml .= $output;
}
$xml .= "</agent_data>";
# Save XML data file
my $temp_file = $Conf{'temporal'} . '/' . $Conf{'agent_name'} . '.' . time () . '.data';
open (TEMP_FILE, "> $temp_file") || error ("Could not write XML data file: $!");
print TEMP_FILE $xml;
close (TEMP_FILE);
# Debug mode
if ($Conf{'debug'} eq '1') {
log_message ('debug', "Wrote XML data file '$temp_file'");
log_message ('debug', "Wrote XML data file '$temp_file'", *STDOUT);
last;
}
# Send the XML data file
send_file ($temp_file, 1);
unlink ($temp_file);
# Cron mode
last if ($Conf{'cron_mode'} == 1);
# Go to sleep
sleep ($Conf{'interval'});
}

View File

@ -0,0 +1,165 @@
# Base config file for Pandora FMS agents
# Version 3.0
# Licensed under GPL license v2,
# (c) 2003-2009 Artica Soluciones Tecnologicas
# please visit http://pandora.sourceforge.net
# General Parameters
# ==================
server_ip localhost
server_path /var/spool/pandora/data_in
temporal /var/spool/pandora/data_out
logfile /var/log/pandora/pandora_agent.log
# Interval in seconds, 300 by default
interval 300
# Debug mode only generate XML, and stop after first execution,
# and does not copy XML to server.
debug 0
# By default, agent takes machine name
#agent_name adama
# Agent description
#description Demo agent
# Group assigned for this agent (descriptive, p.e: Servers)
#group Servers
# Autotime: Enforce to server to ignore timestamp coming from this
# agent, used when agents has no timer or it's inestable. 1 to enable
# this feature
# autotime 1
# By default agent try to take default encoding defined in host.
# encoding iso-8859-15
# Listening TCP port for remote server. By default is 41121 (for tentacle)
# if you want to use SSH use 22, and FTP uses 21.
server_port 41121
# Transfer mode: tentacle, ftp, ssh or local
transfer_mode tentacle
# Server password (Tentacle or FTP). Leave empty for no password (default).
# server_pwd mypassword
# Set to yes/no to enable/disable OpenSSL support for Tentacle (disabled by default).
# server_ssl no
# Extra options for the Tentacle client (for example, server_opts "-v -r 5").
# server_opts
# delayed_startup defines number of MINUTES before start execution
# for first time when startup Pandora FMS Agent
# delayed_startup 10
# Pandora nice defines priority of execution. Less priority means more intensive execution
# A recommended value is 10. 0 priority means no Pandora CPU protection enabled (default)
# pandora_nice 0
# Cron mode replace Pandora FMS own task schedule each XX interval seconds by the use
# of old style cron. You should add to crontab Pandora FMS agent script to use this mode.
# This is disabled by default, and is not recommended. Use Pandora FMS internal scheduler
# is much more safe.
# cron_mode
# If set to 1 allows the agent to be configured via the web console (Only Enterprise version)
# remote_config 1
# Secondary server configuration
# ==============================
# If secondary_mode is set to on_error, data files are copied to the secondary
# server only if the primary server fails. If set to always, data files are
# always copied to the secondary server.
# secondary_mode on_error
# secondary_server_ip localhost
# secondary_server_path /var/spool/pandora/data_in
# secondary_server_port 41121
# secondary_transfer_mode tentacle
# secondary_server_pwd mypassword
# secondary_server_ssl no
# secondary_server_opts
# Module Definition
# =================
# System information
# vmstat syntax depends on linux distro and vmstat command version, please check before use it
module_begin
module_name cpu_user
module_type generic_data
module_interval 1
module_exec vmstat 1 2 | tail -1 | awk '{ print $13 }'
module_max 100
module_min 0
module_description User CPU Usage (%)
module_end
module_begin
module_name Load Average
module_type generic_data
module_exec uptime | awk '{ print $10 }' | cut -f 1 -d ","
module_description Average process in CPU (Last minute)
module_end
module_begin
module_name disk_root_free
module_type generic_data
module_exec df -kh / | tail -1 | awk '{ print 100-$5 }'
module_max 100
module_min 0
module_description Free disk Percentage of root partition
module_end
module_begin
module_name memfree
module_type generic_data
module_exec cat /proc/meminfo | grep MemFree | awk '{ print $2 }'
module_end
# This module uses postprocess feature to pass postprocess value to module
module_begin
module_name memused
module_type generic_data
module_exec cat /proc/meminfo | grep "Active" | awk '{ print $2 }'
module_postprocess 0,976
module_end
module_begin
module_name proctotal
module_type generic_data
module_exec ps -A | wc -l
module_end
# Process information
module_begin
module_name sshDaemon
module_type generic_proc
module_exec ps -Af | grep sshd | grep -v "grep" | wc -l
module_end
# Async data example
module_begin
module_name LastLogin
module_type async_string
module_exec last | head -1
module_end
# Plugin example
# This parses /var/log/syslog file, under the module name "syslog"
# And search for "ssh" string into it, sending only that information.
module_plugin grep_log /var/log/syslog Syslog ssh
# Plugin for inventory on the agent (Only Enterprise)
# module_plugin inventory 1 cpu ram video nic hd cdrom software

View File

@ -0,0 +1,123 @@
#
#Pandora FMS Linux Agent
#
%define name pandorafms_agent
%define version 3.0.0
Summary: Pandora FMS Linux agent
Name: %{name}
Version: %{version}
Release: 1
License: GPL
Vendor: ArticaST <http://www.artica.es>
Source0: %{name}-%{version}.tar.gz
URL: http://pandorafms.org
Group: System/Monitoring
Packager: Manuel Arostegui <manuel@todo-linux.com>
Prefix: /usr/share
BuildRoot: %{_tmppath}/%{name}-%{version}-buildroot
BuildArchitectures: noarch
Requires: coreutils
AutoReq: 0
Provides: %{name}-%{version}
%description
Pandora FMS agents are based on native languages in every platform: scripts that can be written in any language. Its possible to reproduce any agent in any programming language and can be extended without difficulty the existing ones in order to cover aspects not taken into account up to the moment.
These scripts are formed by modules that each one gathers a "chunk" of information. Thus, every agent gathers several "chunks" of information; this one is organized in a data set and stored in a single file, called data file.
%prep
rm -rf $RPM_BUILD_ROOT
%setup -q -n linux
%build
%install
rm -rf $RPM_BUILD_ROOT
mkdir -p $RPM_BUILD_ROOT%{prefix}/pandora_agent/
mkdir -p $RPM_BUILD_ROOT/usr/bin/
mkdir -p $RPM_BUILD_ROOT/usr/sbin/
mkdir -p $RPM_BUILD_ROOT/etc/pandora/
mkdir -p $RPM_BUILD_ROOT/etc/init.d/
mkdir -p $RPM_BUILD_ROOT/var/spool/pandora/data_out
mkdir -p $RPM_BUILD_ROOT/var/log/pandora/
cp -aRf * $RPM_BUILD_ROOT%{prefix}/pandora_agent/
cp -aRf $RPM_BUILD_ROOT%{prefix}/pandora_agent/tentacle_client $RPM_BUILD_ROOT/usr/bin/
%if "%{_vendor}" == "redhat"
mv $RPM_BUILD_ROOT%{prefix}/pandora_agent/pandora_agent $RPM_BUILD_ROOT/usr/bin/
%else
mv $RPM_BUILD_ROOT%{prefix}/pandora_agent/pandora_agent $RPM_BUILD_ROOT/usr/bin/
%endif
mv $RPM_BUILD_ROOT%{prefix}/pandora_agent/pandora_agent_daemon $RPM_BUILD_ROOT/etc/init.d/pandora_agent_daemon
# Checking old config file (if exists)
if [ -f /etc/pandora/pandora_agent.conf ] ; then
cp /etc/pandora/pandora_agent.conf /etc/pandora/pandora_agent.conf.backup
fi
cp $RPM_BUILD_ROOT%{prefix}/pandora_agent/pandora_agent.conf $RPM_BUILD_ROOT%{prefix}/pandora_agent/pandora_agent.conf.rpmnew
if [ -f $RPM_BUILD_ROOT%{prefix}/pandora_agent/pandora_agent.spec ] ; then
rm $RPM_BUILD_ROOT%{prefix}/pandora_agent/pandora_agent.spec
fi
%clean
rm -Rf $RPM_BUILD_ROOT
%pre
/usr/sbin/useradd -d %{prefix}/pandora -s /bin/false -M -g 0 pandora
exit 0
%post
if [ ! -d /etc/pandora ] ; then
mkdir -p /etc/pandora
fi
if [ ! -f /usr/share/pandora_agent/pandora_agent.conf ] ; then
cp /usr/share/pandora_agent/pandora_agent.conf.rpmnew /usr/share/pandora_agent/pandora_agent.conf
else
cp /usr/share/pandora_agent/pandora_agent.conf /etc/pandora/pandora_agent.conf.backup
cp /usr/share/pandora_agent/pandora_agent.conf.rpmnew /usr/share/pandora_agent/pandora_agent.conf
fi
if [ -f /etc/pandora/pandora_agent.conf ] ; then
rm -Rf /etc/pandora/pandora_agent.conf
fi
if [ ! -e /etc/pandora/plugins ]; then
ln -s /usr/share/pandora_agent/plugins /etc/pandora
fi
if [ ! -e /etc/pandora/pandora_agent.conf ]; then
ln -s /usr/share/pandora_agent/pandora_agent.conf /etc/pandora/pandora_agent.conf
fi
chkconfig -s pandora_agent_daemon on
%preun
chkconfig -d pandora_agent_daemon
/etc/init.d/pandora_agent_daemon stop
rm /etc/init.d/pandora_agent_daemon
/usr/sbin/userdel pandora
rm -Rf /etc/pandora/pandora_agent.conf
rm -Rf /var/log/pandora/pandora_agent* 2> /dev/null
exit 0
%files
%defattr(750,pandora,root)
/usr/bin/pandora_agent
%defattr(770,pandora,root)
/var/log/pandora/
/var/spool/pandora/data_out
%defattr(755,pandora,root)
/usr/bin/tentacle_client
/etc/init.d/pandora_agent_daemon
%docdir %{prefix}/pandora_agents/docs
%{prefix}/pandora_agent
#%{_mandir}/man1/pandora.1.gz
#%{_mandir}/man1/pandora_agents.1.gz

View File

@ -0,0 +1,85 @@
#!/bin/bash
# Pandora FMS Linux Agent, startup script
# Copyright (c) 2006-2009 Artica ST, <info@artica.es>
# Linux Version (generic), for SuSe and Debian/Ubuntu.
# other Linux distros could not work properly without modifications
# v3.0 Build 090810
# http://www.pandorafms.com
### BEGIN INIT INFO
# Provides: pandora_agent
# Required-Start: $network
# Required-Stop: $network
# Default-Start: S 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Startup script daemon for Pandora FMS agent
### END INIT INFO
PATH=/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin
PANDORA_PATH=/etc/pandora
DAEMON=/usr/bin/pandora_agent
LOGFILE=/var/log/pandora_agent.log
# This function replace pidof, not working in the same way in different linux distros
function pidof_pandora () (
PANDORA_PID=`ps aux | grep $DAEMON | grep -v grep | head -1 | awk '{ print $2 }'`
echo $PANDORA_PID
)
if [ ! -f $DAEMON ]
then
echo "Pandora FMS Agent not found at $DAEMON, please check setup"
exit
fi
case "$1" in
start)
PANDORA_PID=`pidof_pandora`
if [ ! -z "$PANDORA_PID" ]
then
echo "Pandora FMS Agent is currently running on this machine with PID $PANDORA_PID"
echo "Cannot launch again. Aborting."
exit 1
fi
nohup $DAEMON $PANDORA_PATH 2> $LOGFILE &
sleep 1
PANDORA_PID=`pidof_pandora`
echo "Pandora FMS Agent is now running with PID $PANDORA_PID"
;;
stop)
PANDORA_PID=`pidof_pandora`
if [ -z "$PANDORA_PID" ]
then
echo "Pandora FMS Agent is not running, cannot stop it. Aborting now..."
exit 1
else
echo "Stopping Pandora Agent."
kill $PANDORA_PID > /dev/null 2>&1
fi
;;
status)
PANDORA_PID=`pidof_pandora`
if [ -z "$PANDORA_PID" ]
then
echo "Pandora FMS Agent is not running."
else
echo "Pandora FMS Agent is running with PID $PANDORA_PID."
fi
exit 0
;;
force-reload|restart)
$0 stop
sleep 2
$0 start
;;
*)
echo "Uso: /etc/init.d/pandora_agent_daemon {start|stop|restart|status|force-reload}"
exit 1
esac

View File

@ -0,0 +1,226 @@
#!/bin/bash
# Pandora FMS Agent Installer (c) 2008-2009 Artica ST
# Linux Version (generic), for SuSe and Debian/Ubuntu only
# other Linux distros could not work properly without modifications
# Please see http://www.pandorafms.org
# v3.0 Build 090810
# This code is licensed under GPL 2.0 license.
# **********************************************************************
PI_VERSION=3.0
PANDORA_BIN=/usr/bin/pandora_agent
PANDORA_HOME=/usr/share/pandora_agent
PANDORA_TEMP=/var/spool/pandora
PANDORA_CFG=/etc/pandora
PANDORA_LOG=/var/log/pandora/pandora_agent.log
PANDORA_STARTUP=/etc/init.d/pandora_agent_daemon
TENTACLE=/usr/bin/tentacle_client
PANDORA_CFG_FILE=/etc/pandora/pandora_agent.conf
FORCE=0
LOG_TIMESTAMP=`date +"%Y/%m/%d %H:%M:%S"`
MODE=$1
if [ ! -f "pandora_agent" ]
then
echo " "
echo "You need to place pandora_agent file on main distribution directory before install"
echo " "
exit 1
fi
get_distro () {
# Get Linux Distro type and version
if [ -f "/etc/SuSE-release" ]
then
OS_VERSION=`cat /etc/SuSE-release | grep VERSION | cut -f 3 -d " "`
LINUX_DISTRO=SUSE
else
if [ -f "/etc/lsb-release" ]
then
OS_VERSION=`cat /etc/lsb-release | grep DISTRIB_RELEASE | cut -f 2 -d "="`
LINUX_DISTRO=UBUNTU
OS_VERSION="UBUNTU $OS_VERSION"
else
if [ -f "/etc/debian_version" ]
then
OS_VERSION=`cat /etc/debian_version`
OS_VERSION="DEBIAN $OS_VERSION"
LINUX_DISTRO=DEBIAN
else
if [ -f "/etc/fedora-release" ]
then
OS_VERSION=`cat /etc/fedora-release | cut -f 4 -d " "`
OS_VERSION="FEDORA $OS_VERSION"
LINUX_DISTRO=FEDORA
else
LINUX_DISTRO=GENERIC
OS_VERSION=`uname -r`
fi
fi
fi
fi
echo $LINUX_DISTRO
}
uninstall () {
echo "Removing Pandora FMS Agent..."
rm -Rf $PANDORA_BIN
rm -Rf $PANDORA_TEMP
rm -Rf $PANDORA_CFG_FILE
rm -Rf $PANDORA_STARTUP
rm -Rf $PANDORA_HOME
rm -Rf $PANDORA_LOG
rm -Rf $TENTACLE
echo "Done"
}
install () {
DISTRO=`get_distro`
OLDFILENAMETMP=`date +"%Y-%m-%d"`
echo "Detecting Linux distribution: $DISTRO"
if [ -f $PANDORA_HOME ] && [ "$FORCE" = "0" ]
then
echo "Seems that default dir already exists. Please use --force to"
echo "force installer to install on $PANDORA_HOME"
exit
else
echo "Checking default dir $PANDORA_HOME..."
fi
if [ -f $PANDORA_BIN ] && [ "$FORCE" = "0" ]
then
echo "Seems that $PANDORA_BIN already exists. Please use --force to"
echo "force installer to reinstall overwriting it"
echo " "
exit
else
echo "Checking Pandora FMS Agent on $PANDORA_BIN...."
fi
# Create directories
echo "Creating Pandora FMS Agent home directory at $PANDORA_HOME ..."
mkdir $PANDORA_HOME 2> /dev/null
mkdir $PANDORA_TEMP 2> /dev/null
mkdir $PANDORA_TEMP/data_out 2> /dev/null
mkdir $PANDORA_CFG 2> /dev/null
mkdir /var/log/pandora 2> /dev/null
# Create logfile
if [ ! -z "`touch $PANDORA_LOG`" ]
then
echo "Seems to be a problem generating logfile ($PANDORA_LOG) please check it";
else
echo "Creating logfile at $PANDORA_LOG..."
fi
echo "$LOG_TIMESTAMP Pandora FMS installer has created this file at startup" > $PANDORA_LOG
# Copying agent and securing it
echo "Copying Pandora FMS Agent to $PANDORA_BIN..."
cp pandora_agent $PANDORA_BIN
chmod 700 $PANDORA_BIN
echo "Copying Pandora FMS Agent contrib dir to $PANDORA_HOME/..."
cp pandora_agent_daemon $PANDORA_HOME
echo "Copying Pandora FMS Agent configuration file to $PANDORA_HOME/pandora_agent.conf..."
if [ -e /etc/pandora/pandora_agent.conf ]
then
cat /etc/pandora/pandora_agent.conf > /etc/pandora/pandora/pandora_agent.conf.$OLDFILENAMETMP
echo "Backing up old configuration file to /etc/pandora_agent.conf.$OLDFILENAMETMP"
fi
echo "Copying default agent configuration to $PANDORA_HOME/pandora_agent.conf"
cp pandora_agent.conf $PANDORA_HOME/pandora_agent.conf
chmod 600 $PANDORA_HOME/pandora_agent.conf
echo "Copying Pandora FMS Agent plugins to $PANDORA_HOME/plugins..."
cp -r plugins $PANDORA_HOME
chmod -R 700 $PANDORA_HOME/plugins
echo "Copying tentacle client to $TENTACLE"
cp tentacle_client $TENTACLE
echo "Linking Pandora FMS Agent plugins directory to $PANDORA_CFG/plugins..."
rm $PANDORA_CFG/plugins 2> /dev/null
ln -s $PANDORA_HOME/plugins $PANDORA_CFG 2> /dev/null
echo "Linking Pandora FMS Agent configuration to $PANDORA_CFG/pandora_agent.conf..."
rm $PANDORA_CFG/pandora_agent.conf 2> /dev/null
ln -s $PANDORA_HOME/pandora_agent.conf $PANDORA_CFG/pandora_agent.conf
echo "Setting secure permissions and ownership for all Pandora FMS Agent files..."
chown -R root $PANDORA_HOME
chmod -R 600 $PANDORA_TEMP/data_out
chmod 640 $PANDORA_LOG
chgrp root $PANDORA_LOG
echo "Linking start-up daemon script at $PANDORA_STARTUP";
cp pandora_agent_daemon $PANDORA_STARTUP
if [ "$DISTRO" == "UBUNTU" ]
then
echo "Linking start-up daemon script to /etc/rc2.d";
ln -s /etc/init.d/pandora_agent_daemon /etc/rc2.d/S90pandora_agent
else
INITLV=`cat /etc/inittab | grep "[0-9]\:initdefault" | cut -f 2 -d ":"`
echo "Linking start-up daemon script to /etc/rc.d/rc$INITLV.d";
ln -s /etc/init.d/pandora_agent_daemon /etc/rc.d/rc$INITLV.d/S90pandora_agent
fi
chown -R root:root $PANDORA_BIN
echo "Done."
echo " "
echo "You have your startup script ready at $PANDORA_STARTUP"
echo " "
echo "Tentacle is the default transfer mode since 2.0 version."
echo "If you want to use SSH, firstly you need to copy your public SSH keys ($HOME/.ssh/id_dsa)"
echo "under /home/pandora/.ssh/authorized_keys on your Pandora FMS Server host"
echo "You also need to setup your $PANDORA_CFG/pandora_agent.conf config file"
echo " "
}
help () {
echo " --force-install To force installation if already installed on system "
echo " --install To install Pandora FMS Agent on this system"
echo " --uninstall To uninstall and remove Pandora FMS Agent on this System"
echo " "
}
# Script banner at start
echo " "
echo "Pandora FMS Agent Installer $PI_VERSION (c) 2008-2009 ArticaST"
echo "This program is licensed under GPL2 Terms. http://pandorafms.com"
echo " "
case "$MODE" in
'--force-install')
FORCE=1
install
exit
;;
'--install')
install
exit
;;
'--uninstall')
uninstall
exit
;;
*)
help
esac

1
pandora_agents/unix/plugins Symbolic link
View File

@ -0,0 +1 @@
../linux/plugins/

View File

@ -0,0 +1,682 @@
#!/usr/bin/perl
eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
if 0; # not running under some shell
################################################################################
#
# Copyright (c) 2007-2008 Ramon Novoa <rnovoa@artica.es>
# Copyright (c) 2007-2008 Artica Soluciones Tecnologicas S.L.
#
# tentacle_client.pl Tentacle Client. See http://www.openideas.info/wiki for
# protocol description.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
################################################################################
package tentacle::client;
use strict;
use File::Basename;
use Getopt::Std;
use IO::Select;
use IO::Socket::INET;
# Program version
our $VERSION = '0.2.0';
# Server address
my $t_address = '127.0.0.1';
# Block size for socket read/write operations in bytes
my $t_block_size = 1024;
# Log messages, 1 enabled, 0 disabled
my $t_log = 0;
# Server port
my $t_port = 41121;
# Do not output error messages, 1 enabled, 0 disabled
my $t_quiet = 0;
# Server password
my $t_pwd = '';
# Receive mode, 1 enabled, 0 disabled
my $t_recv = 0;
# Retries for socket read/write operations
my $t_retries = 3;
# Select handler
my $t_select;
# Server socket
my $t_socket;
# Use SSL, 1 true, 0 false
my $t_ssl = 0;
# SSL ca certificate file
my $t_ssl_ca = '';
# SSL certificate file
my $t_ssl_cert = '';
# SSL private key file
my $t_ssl_key = '';
# SSL private key file password
my $t_ssl_pwd = '';
# Timeout for socket read/write operations in seconds
my $t_timeout = 1;
################################################################################
## SUB print_help
## Print help screen.
################################################################################
sub print_help {
print ("Usage: $0 [options] [file] [file] ...\n\n");
print ("Tentacle client v$VERSION. See http://www.openideas.info/wiki for protocol description.\n\n");
print ("Options:\n");
print ("\t-a address\tServer address (default $t_address).\n");
print ("\t-c\t\tEnable SSL without a client certificate.\n");
print ("\t-e cert\t\tOpenSSL certificate file. Enables SSL.\n");
print ("\t-f ca\t\tVerify that the peer certificate is signed by a ca.\n");
print ("\t-g\t\tGet files from the server.\n");
print ("\t-h\t\tShow help.\n");
print ("\t-k key\t\tOpenSSL private key file.\n");
print ("\t-p port\t\tServer port (default $t_port).\n");
print ("\t-q\t\tQuiet. Do now print error messages.\n");
print ("\t-r number\tNumber of retries for network operations (default $t_retries).\n");
print ("\t-t time\t\tTime-out for network operations in seconds (default ${t_timeout}s).\n");
print ("\t-v\t\tBe verbose.\n");
print ("\t-w\t\tPrompt for OpenSSL private key password.\n");
print ("\t-x pwd\t\tServer password.\n\n");
}
################################################################################
## SUB parse_options
## Parse command line options and initialize global variables.
################################################################################
sub parse_options {
my %opts;
my $tmp;
# Get options
if (getopts ('a:ce:f:ghk:p:qr:t:vwx:', \%opts) == 0 || defined ($opts{'h'})) {
print_help ();
exit 1;
}
# Address
if (defined ($opts{'a'})) {
$t_address = $opts{'a'};
if ($t_address !~ /^[a-zA-Z\.]+$/ && ($t_address !~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
|| $1 < 0 || $1 > 255 || $2 < 0 || $2 > 255
|| $3 < 0 || $3 > 255 || $4 < 0 || $4 > 255)) {
error ("Address $t_address is not valid.");
}
}
# Enable SSL without a client certificate
if (defined ($opts{'c'})) {
require IO::Socket::SSL;
$t_ssl = 1;
}
# Enable SSL
if (defined ($opts{'e'})) {
if (defined ($opts{'c'})) {
error ("Flags -c and -e can not be used at the same time.");
}
require IO::Socket::SSL;
$t_ssl_cert = $opts{'e'};
if (! -f $t_ssl_cert) {
error ("File $t_ssl_cert does not exist.");
}
$t_ssl = 1;
}
# Verify peer certificate
if (defined ($opts{'f'})) {
if (! defined ($opts{'e'})) {
error ("Flag -e must be set to enable peer certificate verify.");
}
$t_ssl_ca = $opts{'f'};
if (! -f $t_ssl_ca) {
error ("File $t_ssl_ca does not exist.");
}
}
# Get files
if (defined ($opts{'g'})) {
$t_recv = 1;
}
# SSL private key file
if (defined ($opts{'k'})) {
if (! defined ($opts{'e'})) {
error ("Flag -e must be set to use a private key file.");
}
$t_ssl_key = $opts{'k'};
if (! -f $t_ssl_key) {
error ("File $t_ssl_key does not exist.");
}
}
# Port
if (defined ($opts{'p'})) {
$t_port = $opts{'p'};
if ($t_port !~ /^\d+$/ || $t_port < 1 || $t_port > 65535) {
error ("Port $t_port is not valid.");
}
}
# Quiet mode
if (defined ($opts{'q'})) {
$t_quiet = 1;
}
# Retries
if (defined ($opts{'r'})) {
$t_retries = $opts{'r'};
if ($t_retries !~ /^\d+$/ || $t_retries < 1) {
error ("Invalid number of retries for network operations.");
}
}
# Timeout
if (defined ($opts{'t'})) {
$t_timeout = $opts{'t'};
if ($t_timeout !~ /^\d+$/ || $t_timeout < 1) {
error ("Invalid timeout for network operations.");
}
}
# Be verbose
if (defined ($opts{'v'})) {
$t_log = 1;
}
# SSL private key password
if (defined ($opts{'w'})) {
if (! defined ($opts{'e'})) {
error ("Flag -k must be set to provide a private key password.");
}
$t_ssl_pwd = ask_passwd ("Enter private key file password: ", "Enter private key file password again for confirmation: ");
}
# Server password
if (defined ($opts{'x'})) {
$t_pwd = $opts{'x'};
}
}
################################################################################
## SUB start_client
## Open the server socket.
################################################################################
sub start_client {
# Connect to server
$t_socket = IO::Socket::INET->new (
PeerAddr => $t_address,
PeerPort => $t_port,
);
if (! defined ($t_socket)) {
error ("Cannot connect to $t_address on port $t_port: $!.");
}
# Add server socket to select queue
$t_select = IO::Select->new ();
$t_select->add ($t_socket);
print_log ("Connected to $t_address port $t_port");
}
################################################################################
## SUB stop_client
## Close the server socket.
################################################################################
sub stop_client {
$t_socket->close ();
}
################################################################################
## SUB start_ssl
## Convert the server socket to an IO::Socket::SSL socket.
################################################################################
sub start_ssl {
my $err;
if ($t_ssl_cert eq ''){
IO::Socket::SSL->start_SSL (
$t_socket,
);
}
elsif ($t_ssl_ca eq '') {
IO::Socket::SSL->start_SSL (
$t_socket,
SSL_cert_file => $t_ssl_cert,
SSL_key_file => $t_ssl_key,
SSL_passwd_cb => sub {return $t_ssl_pwd},
SSL_use_cert =>'1',
# No authentication
SSL_verify_mode => '0x00',
);
}
else {
IO::Socket::SSL->start_SSL (
$t_socket,
SSL_ca_file => $t_ssl_ca,
SSL_cert_file => $t_ssl_cert,
SSL_key_file => $t_ssl_key,
SSL_passwd_cb => sub {return $t_ssl_pwd},
SSL_use_cert =>'1',
# Verify peer
SSL_verify_mode => '0x01',
);
}
$err = IO::Socket::SSL::errstr ();
if ($err ne '') {
error ($err);
}
}
################################################################################
## SUB auth_pwd
## Authenticate client with server password.
################################################################################
sub auth_pwd {
my $command;
my $pwd_digest;
require Digest::MD5;
$pwd_digest = Digest::MD5::md5 ($t_pwd);
$pwd_digest = Digest::MD5::md5_hex ($pwd_digest);
send_data ("PASS $pwd_digest\n");
$command = recv_command ($t_block_size);
if ($command !~ /^PASS OK$/) {
error ("Authentication failed.");
}
}
################################################################################
## SUB recv_file
## Receive a file from the server
################################################################################
sub recv_file {
my $data = '';
my $file = $_[0];
my $response;
my $size;
# Request file
send_data ("RECV <$file>\n");
# Wait for server response
$response = recv_command ();
if ($response !~ /^RECV SIZE (\d+)$/) {
error ("Server responded $response.");
}
$size = $1;
send_data ("RECV OK\n");
# Receive file
$data = recv_data_block ($size);
# Write it to disk
open (FILE, "> $file") || error ("Cannot open file '$file' for writing.");
binmode (FILE);
print (FILE $data);
close (FILE);
print_log ("Received file '$file'");
}
################################################################################
## SUB send_file
## Send a file to the server
################################################################################
sub send_file {
my $base_name;
my $data = '';
my $response = '';
my $retries;
my $file = $_[0];
my $size;
my $written;
$base_name = basename ($file);
$size = -s $file;
# Request to send file
send_data ("SEND <$base_name> SIZE $size\n");
print_log ("Request to send file '$base_name' size ${size}b");
# Wait for server response
$response = recv_command ();
# Server rejected the file
if ($response ne "SEND OK") {
send_data ("QUIT\n");
error ("Server responded $response.");
}
print_log ("Server responded SEND OK");
# Send the file
open (FILE, $file) || error ("Cannot open file '$file' for reading.");
binmode (FILE);
while ($data = <FILE>) {
send_data ($data);
}
close (FILE);
# Wait for server response
$response = recv_command ();
if ($response ne "SEND OK") {
send_data ("QUIT\n");
error ("Server responded $response.");
}
print_log ("File sent");
}
################################################################################
# Common functions
################################################################################
################################################################################
## SUB print_log
## Print log messages.
################################################################################
sub print_log {
if ($t_log == 1) {
print (STDOUT "[log] $_[0]\n");
}
}
################################################################################
## SUB error
## Print an error and exit the program.
################################################################################
sub error {
if ($t_quiet == 0) {
print (STDERR "[err] $_[0]\n");
}
exit 1;
}
################################################################################
## SUB recv_data
## Read data from the client socket. Returns the number of bytes read and the
## string of bytes as a two element array.
################################################################################
sub recv_data {
my $data;
my $read;
my $retries = 0;
my $size = $_[0];
while (1) {
# Try to read data from the socket
if ($t_select->can_read ($t_timeout)) {
# Read at most $size bytes
$read = sysread ($t_socket, $data, $size);
# Read error
if (! defined ($read)) {
error ("Read error from " . $t_socket->sockhost () . ": $!.");
}
# EOF
if ($read == 0) {
error ("Connection from " . $t_socket->sockhost () . " unexpectedly closed.");
}
return ($read, $data);
}
# Retry
$retries++;
# But check for error conditions first
if ($retries > $t_retries) {
error ("Connection from " . $t_socket->sockhost () . " timed out.");
}
}
}
################################################################################
## SUB send_data
## Write data to the client socket.
################################################################################
sub send_data {
my $data = $_[0];
my $retries = 0;
my $size;
my $total = 0;
my $written;
$size = length ($data);
while (1) {
# Try to write data to the socket
if ($t_select->can_write ($t_timeout)) {
$written = syswrite ($t_socket, $data, $size - $total, $total);
# Read error
if (! defined ($written)) {
error ("Connection error from " . $t_socket->sockhost () . ": $!.");
}
# EOF
if ($written == 0) {
error ("Connection from " . $t_socket->sockhost () . " unexpectedly closed.");
}
}
$total += $written;
# All data was written
if ($total == $size) {
return;
}
# Retry
$retries++;
# But check for error conditions first
if ($retries > $t_retries) {
error ("Connection from " . $t_socket->sockhost () . " timed out.");
}
}
}
################################################################################
## SUB recv_command
## Read a command from the client, ended by a new line character.
################################################################################
sub recv_command {
my $buffer;
my $char;
my $command = '';
my $read;
my $total = 0;
while (1) {
($read, $buffer) = recv_data ($t_block_size);
$command .= $buffer;
$total += $read;
# Check if the command is complete
$char = chop ($command);
if ($char eq "\n") {
return $command;
}
$command .= $char;
# Avoid overflow
if ($total > $t_block_size) {
error ("Received too much data from " . $t_socket->sockhost ());
}
}
}
################################################################################
## SUB recv_data_block
## Read $_[0] bytes of data from the client.
################################################################################
sub recv_data_block {
my $buffer = '';
my $data = '';
my $read;
my $size = $_[0];
my $total = 0;
while (1) {
($read, $buffer) = recv_data ($size - $total);
$data .= $buffer;
$total += $read;
# Check if all data has been read
if ($total == $size) {
return $data;
}
}
}
################################################################################
## SUB ask_passwd
## Asks the user for a password.
################################################################################
sub ask_passwd {
my $msg1 = $_[0];
my $msg2 = $_[1];
my $pwd1;
my $pwd2;
require Term::ReadKey;
# Disable keyboard echo
Term::ReadKey::ReadMode('noecho');
# Promt for password
print ($msg1);
$pwd1 = Term::ReadKey::ReadLine(0);
print ("\n$msg2");
$pwd2 = Term::ReadKey::ReadLine(0);
print ("\n");
# Restore original settings
Term::ReadKey::ReadMode('restore');
if ($pwd1 ne $pwd2) {
# Call print to bypass quiet mode.
print ("[err] Passwords do not match.\n");
exit 1;
}
# Remove the trailing new line character
chop $pwd1;
return $pwd1;
}
################################################################################
# Main
################################################################################
my $file;
# Parse command line options
parse_options ();
# Check command line arguments
if ($t_recv == 0 && $#ARGV == -1) {
error ("No files to send.");
}
# Connect to the server
start_client ();
# Start SSL
if ($t_ssl == 1) {
start_ssl ();
}
# Authenticate with server
if ($t_pwd ne '') {
auth_pwd ();
}
if ($t_recv == 0) {
# Check that all files exist before trying to send them
foreach $file (@ARGV) {
if (! -f $file) {
error ("File '$file' does not exist.");
}
}
# Send the files
foreach $file (@ARGV) {
send_file ($file);
}
}
else {
# Send the files
foreach $file (@ARGV) {
recv_file ($file);
}
}
# Tell the server that we are finished
send_data ("QUIT\n");
stop_client ();
exit 0;