⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 snmptosql

📁 snmp的源代码,已经在我的ubuntu下编译通过
💻
📖 第 1 页 / 共 2 页
字号:
#!/usr/bin/perluse NetSNMP::manager::getValues qw(getValues);use SNMP;use DBI;use Net::SMTP;#===========================================================================#  Global defines#===========================================================================$hostname = 'localhost';          # Host that serves the mSQL Database$dbname = 'snmp';                 # mySQL Database name$smtpserver = 'localhost';$smtpfrom   = 'Net-SNMP Manager <wjhardaker@ucdavis.edu>';	# <===  CHANGE ME  ========$doit = 1;$somehosts = 0;sub usage {    print "$0 [-H host] [-u user] [-p password] [-l hostlist,...] [-v] [-h] [-n] [-d] [-m mib-to-load] <-m mibnode>\n";    exit 0;}while ($#ARGV > -1) {    $_ = shift @ARGV;    usage if (/-h/);    $hostname = shift if (/-H/);    if (/-l/) {	my $arg = shift;	my @a = split(/,/,$arg);	my $i;	$somehosts = 1;	foreach $i (@a) {	    $dohost{$i} = 1;	}    }    $user = shift if (/-u/);    $pass = shift if (/-p/);    $verbose = 1 if (/-v/);    $delete = 1 if (/-d/);    $doit = 0 if (/-n/);    $tableexpr = shift if (/-t/);    if (/-m/) {	# load some mibs	# SNMP::loadModules(shift);	$ENV{'MIBS'} = shift;    }    if (/-M/) {	# add a mib directory to look in	$ENV{'MIBDIRS'} = shift;	# SNMP::addMibDirs(shift);    }}init_mib;#===========================================================================# Connect to the mSQL database with the appropriate driver( $dbh = DBI->connect("DBI:mysql:database=$dbname;host=$hostname", $user, $pass))    or die "\tConnect not ok: $DBI::errstr\n";## delete history rows every so often.#my %count = getValues($dbh, 'setup', 'deletecount');if (!defined($count{'max'})) {    # default is to delete history rows once an hour.    $dbh->do("insert into setup values('deletecount','max','6')");    $count{'max'} = 6;}if (!defined($count{'current'})) {    $dbh->do("insert into setup values('deletecount','current','0')");} else {    $count{'current'}++;    if ($count{'max'} <= $count{'current'}) {	$count{'current'} = 0;	$deletehist = 1;    }    $dbh->do("update setup set valcol = $count{'current'} where lookup = 'deletecount' and varcol = 'current'");}#===========================================================================# Get host records from database and process$cursor = getcursor("SELECT distinct host FROM hosttables");nexthost: while (  $hostrow = $cursor->fetchrow_hashref ) {    my $host = $hostrow->{'host'};    next if ($somehosts && !defined($dohost{$host}));    #set up the session    print STDERR " starting $host\n" if ($verbose);    my $x = $dbh->prepare("select groupname from hostgroups where host = '$host'");    my $y = $x->execute();    my $group = ${$x->fetchrow_hashref}{'groupname'};    my @args = ('authgroup','default');    print STDERR "$host...$y\n" if ($verbose);    if (defined($y) && "$y" ne "0E0") {        push @args,'authgroup',$group;    }    push @args,'authhost',$host;    print STDERR "$host: $group\n" if ($verbose);    print STDERR "authvals: ", join(", ", @args), "\n" if ($verbose);    my %authvals = getValues($dbh, @args);    if ($verbose) {	print STDERR "parms for $host:";	foreach my $i (keys(%authvals)) {	    print STDERR "$i => $authvals{$i}, ";	}	print STDERR "\n";    }    my $sess = new SNMP::Session (  DestHost => $host, 				    UseSprintValue => 1,				    %authvals );    print STDERR "Sess ($host): $sess, ref=" . ref($sess). "\n" if ($verbose);    if (ref ($sess) ne "SNMP::Session") {#	print STDERR "ack: \$sess not a SNMP::Session for $host ($!)\n";	hosterror("$host");	next nexthost;    }    # get various bits of system information.    my $sysDescr = $sess->get('sysDescr.0');    my $sysId = SNMP::translateObj($sess->get('sysObjectID.0'));    my $versiontag = $sess->get('versionTag.0');    my $sysuptime = $sess->get('sysUpTime.0');    if ($sysDescr eq "" || $sysId eq "" || $versiontag eq "" || 	$sysuptime eq "") {	hosterror("$host","Problem collecting basic info");	next;    }    $dbh->do("update hostgroups set sysObjectId = '$sysId', sysDescr = '$sysDescr', versionTag = '$versiontag', sysUpTime = '$sysuptime' where host = '$host'");    # translate the sysUpTime to a real number for future use:    {	my ($d,$h,$m,$s,$fs) = ($sysuptime =~ /^(\d+):(\d+):(\d+):(\d+)\.(\d+)$/);	$sysuptime = $fs + $s*100 + $m*100*60 + $h*100*60*60 + $d*100*60*60*24;    }    # get a list of tables we want to store    $cmd = "SELECT * FROM hosttables where (host = '$host')";    print STDERR " $cmd\n" if ($verbose);    ( $tblh = $dbh->prepare( $cmd ) )	or warn "\nnot ok: $DBI::errstr\n";    ( $tblh->execute )	or print( "\tnot ok: $DBI::errstr\n" );    while (  $tablelist = $tblh->fetchrow_hashref ) {	next if (defined($tableexpr) && $tablelist->{'tablename'} !~ /$tableexpr/);	print STDERR "starting table $tablelist->{'tablename'}\n" if ($verbose);	my $mib = $SNMP::MIB{SNMP::translateObj($tablelist->{'tablename'})};	if (!$mib) {	    warn "mib node $tablelist->{'tablename'} doesn't exist";	    next;	}	my $children = get_children($mib);	# create the table in our database if it doesn't exist.	setuptable($dbh, $tablelist->{tablename}, $delete);	if ($tablelist->{'keephistory'} > 0) {	    setuptable($dbh, $tablelist->{tablename}, $delete, "hist");	}		$var = 	    new SNMP::Varbind([SNMP::translateObj($tablelist->{'tablename'})]);	my $void = SNMP::translateObj($tablelist->{'tablename'});	my $val = $sess->getnext($var);	print STDERR "init err: $sess->{'ErrorStr'}\n" if ($verbose);	if ($sess->{'ErrorStr'} =~ /Timeout/) {	    print STDERR "$host timed out\n" if ($verbose);	    hosterror($host);	    next nexthost;	}	$initlabel = "";	print STDERR " starting $tablelist->{tablename}\n" if ($verbose);	my %tbl_ids;	while (1) {	    my $varlabel = $var->[$SNMP::Varbind::tag_f];	    print STDERR "last $host " . SNMP::translateObj($varlabel) . ": $void\n" if ($verbose && SNMP::translateObj($varlabel) !~ /^$void/);	    last if (SNMP::translateObj($varlabel) !~ /^$void/);	    $varlabel = SNMP::translateObj($var->[$SNMP::Varbind::tag_f]) if ($varlabel =~ /^[\.0-9]+$/);	    $initlabel = $varlabel if ($initlabel eq "");	    my $val = $sess->getnext($var);	    if ($sess->{'ErrorStr'} =~ /Timeout/) {		print STDERR "$host timed out\n" if ($verbose);		hosterror($host);		next nexthost;	    }	    last if ($sess->{'ErrorStr'});	    my $id = $var->[$SNMP::Varbind::iid_f];	    print STDERR "$initlabel = $varlabel\n" if ($verbose);	    last if ($varlabel ne $initlabel);	    my %vals;	    $tbl_ids{$id} = 1;	    foreach $c (@$children) {		my $oid = $$c{'objectID'} . "." . $id;		my $newvar = new SNMP::Varbind([$oid]);		my $val = $sess->get($newvar);		my $label = SNMP::translateObj($$c{'objectID'});		$vals{$label} = $val;	    }	    my $cmd;	    # check to see if the error previously existed and then	    # delete the old entry.	    my $olderr =		checkrowforerrors($tablelist->{'tablename'}, $host, $id);	    $dbh->do("delete from $tablelist->{tablename} where ( host = '$host'  and oidindex = '$id')");	    $res = $dbh->do("select * from $tablelist->{'tablename'} where ( host = '$host' and oidindex = '$id')");	    print STDERR "  result: $res\n" if ($verbose);	    if ($res ne "0E0") {		$cmd = "update $tablelist->{'tablename'} set ";		foreach $h (keys(%vals)) {		    $cmd .= "$h = '$vals{$h}', ";		}		$cmd .= " updated = NULL where (host = '$host' and oidindex = '$id')";			    } else {		$cmd = "insert into $tablelist->{'tablename'}(host, oidindex, " . join(", ",keys(%vals)) .		    ") values('$host', '$id', '" .			join("', '",values(%vals)). "')";	    }	    print STDERR "  $cmd\n" if ($verbose);	    $dbh->do("$cmd")		or warn "\nnot ok: $cmd => $DBI::errstr\n" if ($doit);	    if ($tablelist->{'keephistory'} > 0) {		$cmd = "insert into $tablelist->{'tablename'}hist (host, oidindex, sysUpTime, " 		    . join(", ",keys(%vals))		    . ") values('$host', '$id', $sysuptime, '"		    . join("', '",values(%vals)). "')";		print STDERR "  $cmd\n" if ($verbose);		$dbh->do("$cmd")		    or warn "\nnot ok: $cmd -> $DBI::errstr\n" if ($doit);			    }	    my $newerr = 		checkrowforerrors($tablelist->{'tablename'}, $host, $id);	    if ($newerr->{retval} != $olderr->{retval}) {		 logerror($host, $newerr->{retval}, $newerr->{errfield}, 			  $newerr->{errvalue});	     }	} # snmp loop	# delete the data beyond the number of days requested.	if ($deletehist && $tablelist->{'keephistory'} > 0) {	    $dbh->do("delete from $tablelist->{'tablename'}hist where (unix_timestamp() - unix_timestamp(updated)) > $tablelist->{'keephistory'}*24*60*60 and host = '$host'") or warn "\nnot ok: $DBI::errstr\n" if ($doit);	}	my $curs = getcursor("select oidindex from $tablelist->{tablename} where host = '$host'");	my $row;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -