Última atividade 2 months ago

Revisão 33a2f9e48fd01eb9a043a8ec766f33fdb26ce1ad

Capture.PNG Bruto
Capture.PNG
update-ddns.rb Bruto
1#!/usr/bin/env ruby
2#
3# Original, including IsoLinearCHiP's improvements: https://gist.github.com/IsoLinearCHiP/d6bc594143102e6acd131fc65c080f64
4# Current version, adapted to Hetzner phasing out dns.h.d for console.h.d:
5
6API="https://api.hetzner.cloud/v1"
7
8require 'json'
9require 'socket'
10require 'net/http'
11require 'fileutils'
12require 'pstore'
13
14FileUtils.mkdir_p "#{Dir.home}/.local/share/update-ddns"
15@pstore = PStore.new "#{Dir.home}/.local/share/update-ddns/cache.pstore"
16
17def api(path, records=nil)
18 cmd = if records
19 "curl -s -X POST -H 'Authorization: Bearer #{@token}' -H 'Content-Type: application/json' -d '{\"records\": #{records.to_json}}' #{API}#{path}"
20 else
21 "curl -s -H 'Authorization: Bearer #{@token}' #{API}#{path}"
22 end
23 json = JSON.parse `#{cmd}`
24 if json['error']
25 warn "Error: #{json['error']['message']}"
26 exit!
27 end
28 json
29end
30
31def cache(key, value=nil)
32 if value
33 @pstore.transaction{@pstore[key] = value}
34 end
35 @pstore.transaction(true){return @pstore[key]}
36end
37
38def current_public_ip
39 Socket.getifaddrs
40 .map{|iface| [iface.name, iface.addr.ip_address] if iface.addr.ipv4? if iface.addr}
41 .compact
42 .find{|x| x[0]=='ppp0'}[1]
43end
44
45def query
46 @token = cache('api_token')
47 zone = ARGV[0]
48 rrset_name = ARGV[1]
49 zone_id = cache('zone_id')
50 zone_id ||= cache('zone_id', api('/zones').find{|x| x['name'] == @zone}['id'])
51 public_ip = cache('current_public_ip', current_public_ip)
52 puts "Current WAN IP: #{public_ip}"
53 ips_on_record = api("/zones/#{zone_id}/rrsets/#{rrset_name}/A")['rrset']['records'].collect{|x| x['value']}
54 if ips_on_record.last != public_ip
55 api("/zones/#{zone_id}/rrsets/#{rrset_name}/A/actions/set_records", [{value: public_ip, comment: 'dynamically updated'}])
56 puts "record updated"
57 else
58 puts "no update necessary"
59 end
60end
61
62case ARGV.size
63 when 1
64 cache('api_token', ARGV[0])
65 puts "API token set"
66 when 2
67 (warn "Error: API token not set"; exit!) unless cache('api_token')
68 query
69 else
70 warn "Usage: update-ddns <zone> <record> | update-ddns <api token>"
71 exit!
72end