commit message

This commit is contained in:
Tomasz Kostrzewa 2024-05-01 14:11:08 +02:00
commit f55b2de680
5 changed files with 395 additions and 0 deletions

11
CloudFlare/README.md Normal file
View File

@ -0,0 +1,11 @@
# cloudflare_ddns.ps1
Script is designed for users sharing their services 'to the internet' using Cloudflare and having dynamic IP addresses. It serves as an alternative to using DDNS. When executed, the script verifies the current public IP based on a defined list of websites. In case of an error, it moves on to the next website, searching for a correct response with the public IP. If it fails to obtain an IP, it terminates with an error. If it finds the same IP as the last time, it terminates. The script consistently uses the next service returning information about the public IP.
On Linux with PowerShell, the script should be invoked via CRON. On Windows, the script should be scheduled using Task Scheduler. If the script proceeds to verify entries from a specific DNS ZONE in Cloudflare, then:
It will verify whether the obtained external IP is the same or different from the defined IP in Cloudflare.
If it is the same, the script will terminate with recording information in the log file.
If it is different, it will update all entries, setting the A address to the current external IP.
## NOTE
The script assumes that all entries point to one host - one IP.

View File

@ -0,0 +1,236 @@
# gitea.RdzeN.net
# DDNS Cloudflare - KeepUpIP
#
<#
The script checks the current external IP based on defined websites.
In case of a change in the external IP, it updates the CloudFlare service using a dedicated API.
It requires providing 'api_key' and 'dns_zone' IDs.
Parameters, such as the number of logs set to 10k lines, can be customized.
The frequency of execution should be defined in cron/schedule.
#>
# Variable section
$location = Get-Location
$path_ip = "$($location)\cloudflare_ddns_ip" # store last set IP
$path_log = "$($location)\cloudflare_ddns_log" # store logs
$path_sites = "$($location)\cloudflare_ddns_sites"
$log_limit = 10000
$ip = $null
$ip_actuall = $null
$ip_ddns = $null
$api_key = 'enter_api_key' # https://dash.cloudflare.com/profile/api-tokens
$dns_zone = 'enter_dns_zone_id' # cloudflare -> websites -> your site -> dns_zone
# if as Page list;
# Alternatively, it checks whether the file already exists.
# The file changes the order of pages by rotating like a die.
# The first element becomes the last, and so on, in a rolling cube fashion.
if (-not (Test-Path $path_sites)) {
$ip_sites = @(
'http://ipinfo.io/ip'
'http://ifconfig.me/ip'
'http://icanhazip.com'
'http://ident.me'
'https://api.ipify.org'
'https://ip2location.io/ip'
)
} else {
[array]$ip_sites = Get-Content $path_sites
}
# function for logs.
$logs = @()
function log {
param (
$l_level,
$l_message
)
$l_timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss.ffff K"
switch ($l_level) {
0 {
$log_message = "$($l_timestamp) | [INFO] | $($l_message)"
}
1 {
$log_message = "$($l_timestamp) | [WARNING] | $($l_message)"
}
2 {
$l_error = $Error[0].Exception
$log_message = "$($l_timestamp) | [ERROR] | $($l_message) | $l_error"
}
}
return $log_message
}
# function for storing logs.
function log_store {
$logs >> $path_log
if (Test-Path $path_log) {
$tmp = Get-Content $path_log -Tail $log_limit
$tmp | Set-Content $path_log
}
}
# 01 - Get the actual IP
function get-ip {
for ($i = 0; $i -lt $ip_sites.Count; $i++) {
switch ($ip_sites[$i]) {
'http://ipinfo.io/ip' {
$uri = $ip_sites[$i]
try {
$test = Test-Connection -TargetName $uri.Replace("http://","").Split("/")[0] -Count 2
$ip = (Invoke-RestMethod -Uri $uri -Method Get).Trim()
}
catch {
$global:logs += log -l_level 1 -l_message "IP: $($Error[0].Exception) | URL: $($uri)"
continue
}
}
'http://ifconfig.me/ip' {
$uri = $ip_sites[$i]
try {
$test = Test-Connection -TargetName $uri.Replace("http://","").Split("/")[0] -Count 1
$ip = (Invoke-RestMethod -Uri $uri -Method Get).Trim()
}
catch {
$global:logs += log -l_level 1 -l_message "IP: $($Error[0].Exception) | URL: $($uri)"
continue
}
}
'http://icanhazip.com' {
$uri = $ip_sites[$i]
try {
$test = Test-Connection -TargetName $uri.Replace("http://","").Split("/")[0] -Count 1
$ip = (Invoke-RestMethod -Uri $uri -Method Get).Trim()
}
catch {
$global:logs += log -l_level 1 -l_message "IP: $($Error[0].Exception) | URL: $($uri)"
continue
}
}
'http://ident.me' {
$uri = $ip_sites[$i]
try {
$test = Test-Connection -TargetName $uri.Replace("http://","").Split("/")[0] -Count 1
$ip = (Invoke-RestMethod -Uri $uri -Method Get).Trim()
}
catch {
$global:logs += log -l_level 1 -l_message "IP: $($Error[0].Exception) | URL: $($uri)"
continue
}
}
'https://api.ipify.org' {
$uri = $ip_sites[$i]
try {
$test = Test-Connection -TargetName $uri.Replace("https://","").Split("/")[0] -Count 1
$ip = (Invoke-RestMethod -Uri $uri -Method Get).Trim()
}
catch {
$global:logs += log -l_level 1 -l_message "IP: ERROR | URL: $($uri)"
continue
}
}
'https://ip2location.io/ip' {
$uri = $ip_sites[$i]
try {
$test = Test-Connection -TargetName $uri.Replace("https://","").Split("/")[0] -Count 1
$ip = (Invoke-RestMethod -Uri $uri -Method Get).Trim()
}
catch {
$global:logs += log -l_level 1 -l_message "IP: ERROR | URL: $($uri)"
continue
}
}
}
if ($null -ne $ip) {
$global:logs += log -l_level 0 -l_message "IP: $($ip) | URL: $($uri)"
$ip_sites = $ip_sites[1..($ip_sites.Count)] + $ip_sites[0]
$ip_sites > $path_sites
break
}
}
return $ip
}
$ip_actuall = get-ip
# If the retrieved IP is NULL or does not match the regex, then...
if (($null -eq $ip_actuall) -or ($ip_actuall -notmatch "^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$")) {
$logs += log -l_level 2 -l_message "Error durring geting public IP | EXIT"
log_store
exit
}
# Verification of the existence of a file with the saved IP;
# If the file exists, then verify if the received IP matches the saved one. If yes, close.
if (Test-Path $path_ip) {
$tmp = Get-Content $path_ip
if ($tmp -eq $ip_actuall) {
$logs += log -l_level 0 -l_message "IP MATCH! | EXIT"
log_store
exit
}
}
# 02 - Get the actuall DNS record from cloudflare
$headers= @{
"Content-Type" = "application/json"
"Authorization" = "Bearer $api_key"
}
# "Try" for fetching a list of DNS records from Cloudflare.
try {
$response = Invoke-RestMethod -Uri "https://api.cloudflare.com/client/v4/zones/$($dns_zone)/dns_records" -Method GET -Headers $headers
$cloudflare_dns = $response.result
$logs += log -l_level 0 -l_message "Downloaded $([array]$cloudflare_dns.count) records."
}
# In case of an error, log the details to a file and close.
catch {
$logs += log -l_level 2 -l_message "Error durring geting dns_records from cloud_flare | EXIT"
log_store
exit
}
# "Processing each entry from Cloudflare.
# If the script encounters the current IP, it will terminate with log recording.
# The script is designed to update all entries with a consistent IP in case of a change.
for ($i = 0; $i -lt $cloudflare_dns.Count; $i++) {
$id = $cloudflare_dns[$i].id
$address = $cloudflare_dns[$i].name
$ip_ddns = $cloudflare_dns[$i].content
$proxied = $cloudflare_dns[$i].proxied
if ($ip_ddns -eq $ip_actuall) {
$logs += log -l_level 0 -l_message "IP MATCH! | EXIT"
log_store
exit
}
$body = @{
content = $ip_actuall
name = $address
type = "A"
proxied = $proxied
comment = log -l_level 0 -l_message "Updated from $($ip_ddns)"
}
$body = $body | ConvertTo-Json
$url = "https://api.cloudflare.com/client/v4/zones/$($dns_zone)/dns_records/$($id)"
try {
$response = Invoke-RestMethod -Uri $url -Method Put -Headers $headers -Body $body
$logs += log -l_level 0 -l_message "Updated from $($ip_ddns) to $($ip_actuall) at $($address)"
}
catch {
$logs += log -l_level 2 -l_message "Not updated from $($ip_ddns) to $($ip_actuall) at $($address)"
}
}
# Saving the new IP to a file for future verification.
$ip_actuall > $path_ip
log_store
exit

View File

@ -0,0 +1,137 @@
# gitea.RdzeN.net
# HP Smart Tank Plus 555 head clean.
#
# requere installed snmp
# set time when printer can run head cleanning
$running_time_start = 10
$running_time_stop = 20
# set day interval between last print and head cleannig
$days_between = 7
$sec_per_day = 86400
$days_between = $days_between * $sec_per_day
$location = Get-Location
$path_last_run = "$($location)/hp_clean_last_run"
$path_log = "$($location)/hp_clean_log"
$snmp_ver = "2c"
$snmp_community = "public"
$snmp_code = "iso.3.6.1.2.1.43.10.2.1.4.1.1" # OID for printed pages durring actuall sesion
$printer_ip = "" # printer IP
$url = "http://$($printer_ip)/DevMgmt/InternalPrintDyn.xml" # url where we need to POST body for start HEAD cleaning.
$body = "<ipdyn:InternalPrintDyn xmlns:ipdyn=`"http://www.hp.com/schemas/imaging/con/ledm/internalprintdyn/2008/03/21`" xmlns:copy=`"http://www.hp.com/schemas/imaging/con/copy/2008/07/07`" xmlns:dd=`"http://www.hp.com/schemas/imaging/con/dictionaries/1.0/`" xmlns:dd3=`"http://www.hp.com/schemas/imaging/con/dictionaries/2009/04/06`" xmlns:fw=`"http://www.hp.com/schemas/imaging/con/firewall/2011/01/05`"><ipdyn:JobType>cleaningVerificationPage</ipdyn:JobType></ipdyn:InternalPrintDyn>"
$headers = @{
"Content-Type" = "text/xml"
}
$logs = @()
$log_limit = 10000
function log {
param (
$l_level,
$l_message
)
$l_timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss.ffff K"
switch ($l_level) {
0 {
$log_message = "$($l_timestamp) | [INFO] | $($l_message)"
}
1 {
$log_message = "$($l_timestamp) | [WARNING] | $($l_message)"
}
2 {
$l_error = $Error[0].Exception
$log_message = "$($l_timestamp) | [ERROR] | $($l_message) | $l_error"
}
}
return $log_message
}
function log_store {
$logs >> $path_log
if (Test-Path $path_log) {
$tmp = Get-Content $path_log -Tail $log_limit
$tmp | Set-Content $path_log
}
}
$logs += log -l_level 0 -l_message "Script Started"
$actual_time = get-date
# check if hour of running isnt restricted by $running_time_start and $running_time_stop
if (($actual_time.hour -lt $running_time_start) -and ($actual_time.hour -gt $running_time_stop)) {
$logs += log -l_level 0 -l_message "Hours between >= $running_time_start and <= $running_time_stop are restricted. EXIT"
$logs += log -l_level 0 -l_message "Script Stopped"
log_store
exit
}
$actual_time = get-date -Format "yyyy-MM-dd HH:mm:ss.ffff"
# check / create last run control file
if (-not(Test-Path $path_last_run)) {
$logs += log -l_level 1 -l_message "$($path_last_run) Does not exists - CREATING."
$last_run = [PSCustomObject]@{
date = Get-Date -Format "yyyy-MM-dd HH:mm:ss.ffff"
p_count = (snmpget -v $snmp_ver -c $snmp_community $printer_ip $snmp_code).Split(" ")[-1]
}
$logs += log -l_level 0 -l_message "Actual date and printed documents count are stored in $($path_last_run)"
$last_run | Export-Csv -Path $path_last_run -NoTypeInformation
# Get last run date and amount of printed documents
} else {
$last_run = Import-Csv $path_last_run
$logs += log -l_level 0 -l_message "Last Run Date: $($last_run.date), Last printed documents count: $($last_run.p_count)"
}
# Get actuall amount of printed pages
try {
$actual_p_count = (snmpget -v $snmp_ver -c $snmp_community $printer_ip $snmp_code).Split(" ")[-1]
} catch {
$logs += log -l_level 2 -l_message "Getting printed page count got ERROR. EXIT"
$logs += log -l_level 0 -l_message "Script Stopped"
log_store
exit
}
# Check if printed page count changed
if ($actual_p_count -gt $last_run.p_count) {
$logs += log -l_level 0 -l_message "Printed page count changed from $($last_run.p_count) to $actual_p_count. Changing last run time from $($last_run.date) to $actual_time"
$last_run.p_count = $actual_p_count
$last_run.date = $actual_time
$last_run | Export-Csv -Path $path_last_run -NoTypeInformation
$logs += log -l_level 0 -l_message "Script Stopped"
log_store
exit
}
# Check if between $last_run.date and $actual_time passed $days_between
$difference = [DateTime]$actual_time - [DateTime]$last_run.Date | Select-Object TotalSeconds -ExpandProperty TotalSeconds
if ($difference -gt $days_between) {
$logs += log -l_level 0 -l_message "Difference between Actual Time and Last Run Time is greater than $($days_between/$sec_per_day) days, is it: $($difference/$sec_per_day) days"
# start head cleaning
try {
$tmp = Invoke-RestMethod -Method Post -Body $body -Headers $headers -Uri $url
$logs += log -l_level 0 -l_message "Head Cleaning Started"
$actual_time = get-date -Format "yyyy-MM-dd HH:mm:ss.ffff"
$last_run.date = $actual_time
} catch {
$logs += log -l_level 2 -l_message "Error durring connecting to printer."
$logs += log -l_level 0 -l_message "Script Stopped"
log_store
exit
}
} else {
$logs += log -l_level 0 -l_message "Difference between Actual Time and Last Run Time is less than $($days_between/$sec_per_day) days, is it: $($difference/$sec_per_day) days"
}
# store actuall amount of printed pages and actuall date
$actual_p_count = (snmpget -v $snmp_ver -c $snmp_community $printer_ip $snmp_code).Split(" ")[-1]
$last_run.p_count = $actual_p_count
$last_run | Export-Csv -Path $path_last_run -NoTypeInformation
$logs += log -l_level 0 -l_message "Head Cleaning Stopped. Actual date: $actual_time. Actuall printed page count: $actual_p_count."
$logs += log -l_level 0 -l_message "Script Stopped"
log_store
exit

9
LICENSE Normal file
View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) 2023 najlepszytomasz
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

2
README.md Normal file
View File

@ -0,0 +1,2 @@
# PowerShell