-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathupdate-opendns.ps1
98 lines (73 loc) · 2.39 KB
/
update-opendns.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# Script to update the dynamic IP address associated with an OpenDNS account.
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$passwordFile,
# Username at OpenDNS
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$username,
# Network name at OpenDNS
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$netname,
# Log file name
[Parameter()]
[string]
$logfile = "~/.local/log/update-opendns.log"
)
# Main body of script
# Get password from file and build credentials
if (test-path $passwordFile) {
$password = Get-Content $passwordFile | ConvertTo-SecureString
} else {
Write-Error "Could not find password file: " + $passwordFile + " Ensure the path is valid."
exit
}
$cred = [System.Management.Automation.PSCredential]::new($username,$password)
# Get current public IP address
$myip = [System.Net.Dns]::GetHostByName("myip.opendns.com").AddressList[0].IPAddressToString
# Build URI
$updateURI = 'https://updates.dnsomatic.com/nic/update?hostname=' + $netname + '&myip=' + $myip
# Check if IP address has changed since we last ran
if (test-path -path $env:TMPDIR/update-opendns_myip.txt) {
if ((Get-Content -Path $env:TMPDIR/update-opendns_myip.txt) -eq $myip) {
$newIP = $false
} else {
$newIP = $true
}
} else {
$newIP = $true
}
# Send update if necessary
if ($newIP) {
try {
$response = Invoke-RestMethod -Uri $updateURI -Method Get -Authentication Basic -Credential $cred
}
catch {
Write-Error "IP address update to OpenDNS failed. See log file."
}
# Write log
[pscustomobject]@{
"Time (UTC)" = ([system.datetime]::Utcnow.tostring('u').replace(' ','T'))
"Network Name" = $netname
"IP Address" = $myip
"Update Required" = $newIP
"Response" = $response
} | Export-Csv -Path $logfile -Append -NoTypeInformation
# Write new IP address to temp file
$myip | Out-File -FilePath $env:TMPDIR/update-opendns_myip.txt
} else {
# Write log
[pscustomobject]@{
"Time (UTC)" = ([system.datetime]::Utcnow.tostring('u').replace(' ','T'))
"Network Name" = $netname
"IP Address" = $myip
"Update Required" = $newIP
"Response" = 'n/a'
} | Export-Csv -Path $logfile -Append -NoTypeInformation
}