Skip to content

Instantly share code, notes, and snippets.

@nazarov-yuriy
Created January 9, 2015 22:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nazarov-yuriy/f8c9c4ded856295325ab to your computer and use it in GitHub Desktop.
Save nazarov-yuriy/f8c9c4ded856295325ab to your computer and use it in GitHub Desktop.
#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long;
use JSON::XS;
use LWP;
use LWP::UserAgent;
use constant {
DNS_API_URI_PREFIX => 'https://pddimp.yandex.ru/api2/admin/dns/',
IP_API_URI => 'http://ipv4.internet.yandex.ru/api/v0/ip',
};
sub get($$%){
my ($ua, $url, %headers) = @_;
my $req = HTTP::Request->new(GET => $url);
$req->header(%headers) if keys %headers;
my $res = $ua->request($req);
return $res->content if $res->is_success;
return undef;
}
sub post($$$%){
my ($ua, $url, $data, %headers) = @_;
my $req = HTTP::Request->new(POST => $url);
$req->header(%headers) if keys %headers;
$req->content_type('application/x-www-form-urlencoded');
$req->content($data);
my $res = $ua->request($req);
return $res->content if $res->is_success;
return undef;
}
sub get_record($$$$){
my ($ua, $token, $domain, $subdomain) = @_;
my $json = get($ua, DNS_API_URI_PREFIX."list?domain=$domain", PddToken => $token) or die "Receiving record id.";
my $records = decode_json($json)->{records};
my ($record) = grep{ $_->{type} eq 'A' && $_->{domain} eq $domain && $_->{subdomain} eq $subdomain } @$records;
return $record;
}
sub get_ip($) {
my ($ua) = @_;
my $response = get($ua, IP_API_URI);
return substr $response, 1, length($response)-2;
}
sub set_domain_ip($$$$$$){
my ($ua, $token, $domain, $subdomain, $record_id , $ip) = @_;
return decode_json post($ua, DNS_API_URI_PREFIX."edit", "domain=$domain&record_id=$record_id&subdomain=$subdomain&ttl=14400&content=$ip", PddToken => $token);
}
sub main(){
my $token = $ENV{token};
my ($domain, $subdomain);
GetOptions (
"domain=s" => \$domain,
"subdomain=s" => \$subdomain,
);
my $ua = LWP::UserAgent->new();
my $ip = get_ip($ua) or die "Getting ip";
my $record = get_record($ua, $token, $domain, $subdomain) or die "Getting record_id";
die "Nothing to change" if $record->{content} eq $ip;
die "Failed to update ip" unless 'ok' eq set_domain_ip($ua, $token, $domain, $subdomain, $record->{record_id}, $ip)->{success};
print "IP was updated successfully";
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment