Advertisement
Guest User

Untitled

a guest
Mar 26th, 2016
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.95 KB | None | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use Net::Domain qw(hostname hostfqdn);
  4. use JSON;
  5. use LWP::UserAgent;
  6. use HTTP::Request;
  7. use HTTP::Status;
  8.  
  9. use Data::Dumper;
  10.  
  11. use strict;
  12.  
  13. my $base = "http://zabbix.fresh";
  14. my $api = $base . "/api_jsonrpc.php";
  15. my $api_user = "_api";
  16. my $api_pass = "_api_pass_word_";
  17.  
  18. my $req_id = 0;
  19. my $auth_token;
  20.  
  21. sub request {
  22.     my ($url, $method, $data) = @_;
  23.  
  24.     my $json = encode_json({"jsonrpc" => "2.0", "method" => $method, "params" => $data, "auth" => $auth_token, "id" => $req_id++});
  25.  
  26.     my $req = HTTP::Request->new(POST => $url);
  27.     $req->content_type('application/json');
  28.     $req->content($json);
  29.  
  30.     my $ua = LWP::UserAgent->new;
  31.     my $res = $ua->request($req);
  32.  
  33.     die "HTTP protocol error: " . $res->code if not is_success($res->code);
  34.     my $resp = decode_json($res->decoded_content);
  35.  
  36.     die "Zabbix API error: " . Dumper($resp->{'error'}) if $resp->{'error'};
  37.  
  38.     return $resp->{'result'};
  39. }
  40.  
  41. $auth_token = request($api, "user.login", { "user" => $api_user, "password" => $api_pass });
  42.  
  43. my @res;
  44.  
  45. @res = `/sbin/ip -o -4 route show to default`;
  46. my ($defgw_dev) = $res[0] =~ / dev (\w+)/;
  47. $defgw_dev = " dev $defgw_dev" if $defgw_dev;
  48.  
  49. @res = `/sbin/ip -o -4 addr show scope global$defgw_dev`;
  50. my ($ip) = $res[0] =~m|inet ([\d\.]+)/\d+ brd|;
  51.  
  52. my $host_config = {
  53.         "host" => hostname,
  54.         "interfaces" => [{
  55.                 "type" => 1,
  56.                 "main" => 1,
  57.                 "useip" => 1,
  58.                 "ip" => $ip,
  59.                 "dns" => hostfqdn,
  60.                 "port" => "10050"
  61.         }],
  62.         "groups" => [
  63.             { "groupid" => "2" },       # Linux Servers
  64.             { "groupid" => "18" }       # PostgreSQL Servers
  65.         ],
  66.         "templates" => [
  67.             { "templateid" => "10109" },# T_Linux
  68.             { "templateid" => "10107" } # T_DiskStats
  69.         ]
  70.     };
  71.  
  72. my $res = request($api, "host.create", $host_config);
  73.  
  74. print Dumper($res);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement