文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>[Perl]用Jabber做系统监控和报警(可使用Google ..

[Perl]用Jabber做系统监控和报警(可使用Google ..

时间:2006-08-21  来源:huhuegg

  #client.pl   #!/usr/bin/perl
#version: 0.1
#date:2006-08-25 19:00:00
use Net::Jabber qw(Client);
use Authen::SASL;
use Carp;
#use Net::XMPP qw( Client );
use Config::Tiny;
use strict;
my $Config = Config::Tiny->read( 'config.ini' );
my $hostname=$Config->{Jabber_Server}->{hostname};
my $port=$Config->{Jabber_Server}->{port};
my $componentname=$Config->{Jabber_Server}->{componentname};

my $username = "test";
my $password = "test";
my $resource = "";
my $to_user_account="test\@testjabber.vicp.net";
my @cmdlist;
open (CMDFH,"cmd.ini") || print "can't open cmd.ini:$!";
foreach my $tmpcmd (<CMDFH>) {
 push(@cmdlist,$tmpcmd);
}

$SIG{HUP} = \&Stop;
$SIG{KILL} = \&Stop;
$SIG{TERM} = \&Stop;
$SIG{INT} = \&Stop;
my $Connection = new Net::Jabber::Client(); $Connection->SetXPathCallBacks('/message'=>\&InMessage,
                               '/presence'=>\&InPresence,
                               '/iq'=>\&InIQ);
my $status = $Connection->Connect(hostname=>$hostname,
                                  port=>$port);
##连接成功$status返回1,不成功返回空
if (!(defined($status)))
{
##不成功返回如下两行
##ERROR:  Jabber server is down or connection was not allowed.
##        (拒绝连接)
    print "ERROR:  Jabber server is down or connection was not allowed.\n";
    print "        ($!)\n";
    exit(0);
}
my @result = $Connection->AuthSend(username=>$username,
                                   password=>$password,
                                   resource=>$resource);
##用户名密码错误返回两个信息
##error
##temporary-auth-failure
##验证成功返回一个信息
##ok
  if ($result[0] ne "ok")
{
    print "ERROR: Authorization failed: $result[0] - $result[1]\n";
    exit(0);
}
print "Logged in to $hostname:$port...\n"; #default: $Connection->RosterGet(); #add start
my @onlineuser;
my %Roster =  $Connection->RosterGet();
foreach my $key (keys %Roster) {
 push(@onlineuser,$key);
# print "所有好友:",$key,"\n";
}
#add end
print "Getting Roster to tell server to send presence info...\n"; $Connection->PresenceSend(show=>"away");
print "Sending presence to tell world that we are logged in...\n";
while(defined($Connection->Process())) { } print "ERROR: The connection was killed...\n"; exit(0);     #sub for main ############################################################
sub Stop
{
    print "Exiting...\n";
    $Connection->Disconnect();
    exit(0);
}

sub InMessage
{
    my $sid = shift;
    my $message = shift;
   
    my $type = $message->GetType();
    my $fromJID = $message->GetFrom("jid");
   
    my $from = $fromJID->GetUserID();
    my $resource = $fromJID->GetResource();
    my $subject = $message->GetSubject();
    my $body = $message->GetBody();
    print "===\n";
    print "Message ($type)\n";
    print "  From: $from ($resource)\n";
    print "  Subject: $subject\n";
    print "  Body: $body\n";
    print "===\n";
    print $message->GetXML(),"\n";
    print "===\n";
    my $returnmessages;
    my $eq;
    foreach my $cmd (@cmdlist) {
 chomp $cmd;
print $body . " " . $cmd . "\n";
        if ("$body" eq "$cmd") {
  $eq=1;
 }
    }
    if ($eq == 1) {
        $returnmessages=`$body`;
     chomp $returnmessages;
    } else {
 $returnmessages="This command not allowed!\n";
    }
       &Jabber(
               debuglevel=>0,
                username=>$username,
                password=>$password,
               to=>$to_user_account,
                body=>$returnmessages
               );
}

sub InIQ
{
    my $sid = shift;
    my $iq = shift;
   
    my $from = $iq->GetFrom();
    my $type = $iq->GetType();
    my $query = $iq->GetQuery();
    my $xmlns = $query->GetXMLNS();
    print "===\n";
    print "IQ\n";
    print "  From $from\n";
    print "  Type: $type\n";
    print "  XMLNS: $xmlns";
    print "===\n";
    print $iq->GetXML(),"\n";
    print "===\n";
}
sub InPresence
{
    my $sid = shift;
    my $presence = shift;
   
    my $from = $presence->GetFrom();
    my $type = $presence->GetType();
    my $status = $presence->GetStatus();
    print "===\n";
    print "Presence\n";
    print "  From $from\n";
    print "  Type: $type\n";
    print "  Status: $status\n";
    print "===\n";
    print $presence->GetXML(),"\n";
    print "===\n";
}
##sub for jabber client send messages#############################################
sub Jabber
{
    my %args;
    while($#_ >= 0) { $args{ lc pop(@_) } = pop(@_); }     carp("Jabber requires a username argument") unless exists($args{username});
    carp("Jabber requires a password argument") unless exists($args{password});
    carp("Jabber requires a to argument") unless exists($args{to});
    carp("Jabber requires a body argument") unless exists($args{body});
    $args{debuglevel} = 0 unless exists($args{debuglevel});
    $args{debugfile}  = 'stdout' unless exists($args{debugfile});
    $args{timeout}    = 10 unless exists($args{timeout});
    $args{subject}    = 'Jabber' unless exists($args{subject});
    $args{resource}   = 'Jabber.pl';
    my $client = new Net::XMPP::Client(debuglevel=>$args{debuglevel},
                                       debugfile=>$args{debugfile});
    # Open connection
    my @res = $client->Connect(hostname=>$hostname, port=>$port,
                               timeout=>$args{timeout}, connectiontype=>"tcpip",
                               tls=>1, componentname=>$componentname);
 
    # Modification of XMPP::Protocol::AuthSASL
    &GAuthSASL($client, username=>$args{username}, password=>$args{password},
                        resource=>$args{resource});
    # Send google talk message
    $client->MessageSend(to=>$args{to}, subject=>$args{subject},
                         body=>$args{body}, resource=>$args{resource});
    # Close connection
    $client->Disconnect();
}
###############################################################################
#
# AuthSASL - Try and auth to Jabber using SASL, the XMPP preferred way
#            of authenticating.
#
###############################################################################
sub GAuthSASL
{
    my $self = shift;
    my %args;
    while($#_ >= 0) { $args{ lc pop(@_) } = pop(@_); }     $self->{DEBUG}->Log1("AuthSASL: shiney new auth");     carp("AuthSASL requires a username arguement")
        unless exists($args{username});
    carp("AuthSASL requires a password arguement")
        unless exists($args{password});
    $args{resource} = "" unless exists($args{resource});     #-------------------------------------------------------------------------
    # Create the SASLClient on our end
    #-------------------------------------------------------------------------
    my $sid = $self->{SESSION}->{id};
    # Modification of XML::Stream::SASLClient
    &GSASLClient($self->{STREAM}, $sid,
                                  $args{username},
                                  $args{password}
                                 );
    $args{timeout} = "120" unless exists($args{timeout});     #-------------------------------------------------------------------------
    # While we haven't timed out, keep waiting for the SASLClient to finish
    #-------------------------------------------------------------------------
    my $endTime = time + $args{timeout};
    while(!$self->{STREAM}->SASLClientDone($sid) && ($endTime >= time))
    {
        $self->{DEBUG}->Log1("AuthSASL: haven't authed yet... let's wait.");
        return unless (defined($self->Process(1)));
        &{$self->{CB}->{update}}() if exists($self->{CB}->{update});
    }
   
    #-------------------------------------------------------------------------
    # The loop finished... but was it done?
    #-------------------------------------------------------------------------
    if (!$self->{STREAM}->SASLClientDone($sid))
    {
        $self->{DEBUG}->Log1("AuthSASL: timed out...");
        return( "system","SASL timed out authenticating");
    }
    #-------------------------------------------------------------------------
    # Ok, it was done... but did we auth?
    #-------------------------------------------------------------------------
    if (!$self->{STREAM}->SASLClientAuthed($sid))
    {
        $self->{DEBUG}->Log1("AuthSASL: Authentication failed.");
        return ( "error", $self->{STREAM}->SASLClientError($sid));
    }
   
    #-------------------------------------------------------------------------
    # Phew... Restart the <stream:stream> per XMPP
    #-------------------------------------------------------------------------
    $self->{DEBUG}->Log1("AuthSASL: We authed!");
    $self->{SESSION} = $self->{STREAM}->OpenStream($sid);
    $sid = $self->{SESSION}->{id};
   
    $self->{DEBUG}->Log1("AuthSASL: We got a new session. sid($sid)");
    #-------------------------------------------------------------------------
    # Look in the new set of <stream:feature/>s and see if xmpp-bind was
    # offered.
    #-------------------------------------------------------------------------
    my $bind = $self->{STREAM}->GetStreamFeature($sid,"xmpp-bind");
    if ($bind)
    {
        $self->{DEBUG}->Log1("AuthSASL: Binding to resource");
        $self->BindResource($args{resource});
    }
    #-------------------------------------------------------------------------
    # Look in the new set of <stream:feature/>s and see if xmpp-session was
    # offered.
    #-------------------------------------------------------------------------
    my $session = $self->{STREAM}->GetStreamFeature($sid,"xmpp-session");
    if ($session)
    {
        $self->{DEBUG}->Log1("AuthSASL: Starting session");
        $self->StartSession();
    }
    return ("ok","");
}
###############################################################################
#
# GSASLClient - This is a helper function to perform all of the required steps
#               for doing SASL with the Google Talk server.
#
###############################################################################
sub GSASLClient
{
    my $self = shift;
    my $sid = shift;
    my $username = shift;
    my $password = shift;
 
    my $mechanisms = $self->GetStreamFeature($sid,"xmpp-sasl");
    return unless defined($mechanisms);     my $sasl = new Authen::SASL(mechanism=>join(" ",@{$mechanisms}),
                                callback=>{
                                           user     => $username,
                                           pass     => $password
                                          }
                               );
    $self->{SIDS}->{$sid}->{sasl}->{client} = $sasl->client_new();
    $self->{SIDS}->{$sid}->{sasl}->{username} = $username;
    $self->{SIDS}->{$sid}->{sasl}->{password} = $password;
    $self->{SIDS}->{$sid}->{sasl}->{authed} = 0;
    $self->{SIDS}->{$sid}->{sasl}->{done} = 0;
    $self->SASLAuth($sid);
}
###################################################################################
  #config.ini   [Jabber_Server]
hostname=testjabber.vicp.net
port=5222
componentname=testjabber.vicp.net
   
  #cmd.ini   top -b -n 1
ps x
ps aux
ls
ls -l
hostname
free df -h dmicode ethtool eth0 ethtool eth1 ...
相关阅读 更多 +
排行榜 更多 +
翌日波奇狗的历险记手机版下载

翌日波奇狗的历险记手机版下载

休闲益智 下载
怪兽远征安卓版下载

怪兽远征安卓版下载

角色扮演 下载
谷歌卫星地图免费版下载

谷歌卫星地图免费版下载

生活实用 下载