+ -
当前位置:首页 → 问答吧 → Perl 监控Mysql主从问题.

Perl 监控Mysql主从问题.

时间:2010-10-19

来源:互联网

本人想用perl来监控Mysql主从的,便从网上copy下来一些代码,稍稍的修改下,发现报错错误是,
Can't call method "prepare" on an undefined value at duplicate.pl line 39.   查了半天还是差不出来。望高手出马.
  1. #!/usr/bin/perl
  2. # Use mandatory external modules
  3. use strict;
  4. use warnings;
  5. use DBI;
  6. use Time::HiRes;
  7. use POSIX "strftime";
  8. my $host         = '192.168.1.240';
  9. my $user         = 'dodo';
  10. my $pass         = 'dodo';
  11. my $port         = '3306';
  12. my $max_behind_m = 120;
  13. my $check_log    = '/var/log/mysql_check_log';

  14. # open  log--file
  15. open (FH, ">> $check_log") or die $!;

  16. # connect to servers (this)
  17. my $this_dbh = &MysqlConnect( $host, $port, $user, $pass );

  18. # Get slave info
  19. my $slave_status = &MysqlQuery( $this_dbh, 'show slave status' );
  20. print FH "ERROR: SQL Query Error: " . $this_dbh->errstr unless ($slave_status);
  21. my $Slave_IO              = $slave_status->{Slave_IO_Running};
  22. my $Slave_SQL             = $slave_status->{Slave_SQL_Running};
  23. my $Seconds_Behind_Master = $slave_status->{Seconds_Behind_Master};
  24. print "IO:\t\t $Slave_IO\n";
  25. print "SQL:\t\t $Slave_SQL\n";
  26. print "Behind_Master:\t $Seconds_Behind_Master\n";

  27. sub MysqlConnect {
  28.     my ( $host, $port, $user, $pass ) = @_;
  29.     my $dsn = "DBI:mysql:host=$host;port=$port";
  30.     return DBI->connect( $dsn, $user, $pass, { PrintError => 0 } );
  31. }

  32. sub MysqlQuery {
  33.     my ( $dbh, $query ) = @_;
  34.     my $sth = $dbh->prepare($query);
  35.     my $res = $sth->execute;
  36.     return undef unless ($res);
  37.     my $row = $sth->fetchrow_hashref;
  38.     $sth->finish;
  39.     return $row;
  40. }

  41. #-----------------------------------------------------------------
  42. sub ExecuteQuery {
  43.     my ( $dbh, $query ) = @_;
  44.     my $sth = $dbh->prepare($query);
  45.     return $sth->execute;
  46. }

  47. #-----------------------------------------------------------------
  48. sub current_time {
  49.     my $time_now = POSIX::strftime( "[%Y-%m-%d %H:%M:%S]", localtime );
  50.     return $time_now;
  51. }
复制代码

作者: mitmax   发布时间: 2010-10-19

19. my $this_dbh = &MysqlConnect( $host, $port, $user, $pass );
这里连接失败返回 undef 了应该,你应该检查这个错误的

作者: zhlong8   发布时间: 2010-10-19

Thank 是连接数据库问题

作者: mitmax   发布时间: 2010-10-19