Skip to content

Instantly share code, notes, and snippets.

@CodesOfRishi
Last active July 23, 2022 05:01
Show Gist options
  • Save CodesOfRishi/e2c16d802588c9a3a4fbd06d47ca09a9 to your computer and use it in GitHub Desktop.
Save CodesOfRishi/e2c16d802588c9a3a4fbd06d47ca09a9 to your computer and use it in GitHub Desktop.
Sanitize/Un-sanitize URL/IP
# Sanitize/Un-sanitize a URL/IP - RishiK.
while (1) {
if ($args[0]) {
$url=$args[0]
}
else {
$url = Read-Host "Enter URL/IP >>"
}
$url=$url.Trim()
if (!$url) { continue }
if ($url -match '\[\.\]') {
# Already sanitized
$url=$url.replace('[.]','.')
$url=$url.replace('[:]',':')
write-host "UN-SANITIZED > " -nonewline -Foregroundcolor Red
write-host $url
}
else {
# Needs to sanitize
if ($url -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' -And $url -notmatch "[a-zA-Z]") {
# Input is an IP
$url=$url -replace "(.*)\.(.*)", '$1[.]$2'
}
else {
$url=$url.replace('.','[.]')
$url=$url.replace('[[.]]','[.]')
$url=$url.replace(':','[:]')
$url=$url.replace('[[:]]','[:]')
}
write-host "SANITIZED > " -nonewline -Foregroundcolor Green
write-host $url
}
Set-Clipboard -Value $url # copy the URL/IP to the clipboard
remove-variable url
if ($args[0]) { break }
}
#!/usr/bin/env bash
_san::un_sanitize() {
local _url && _url="$*"
_url=$( printf '%s\n' "${_url}" | sed 's/\[\.\]/\./g' | sed 's/\[:\]/:/g' )
printf '%s\n\n' "${_url}"
}
_san::sanitize() {
local _url && _url="$*"
if [[ "${_url}" =~ ^(([1-9]?[0-9]|1[0-9][0-9]|2([0-4][0-9]|5[0-5]))\.){3}([1-9]?[0-9]|1[0-9][0-9]|2([0-4][0-9]|5[0-5]))$ ]] || \
[[ "${_url}" =~ ^(([1-9]?[0-9]|1[0-9][0-9]|2([0-4][0-9]|5[0-5]))\.){3}([1-9]?[0-9]|1[0-9][0-9]|2([0-4][0-9]|5[0-5]))\/([0-9]|[12][0-9]|3[012])$ ]]; then
# It's an IP Address
_url=$( printf '%s\n' "${_url}" | sed 's/\(.*\)\./\1\[\.\]/' )
elif [[ "${_url}" = *"."* ]]; then
# Could be a URL
_url=$( printf '%s\n' "${_url}" | sed 's/\./[\.]/g' | sed 's/:/[:]/g' )
else
printf '%s\n\n' "ERROR: Doesn't seems to be a URL nor an IP address !!"
return
fi
printf '%s\n\n' "${_url}"
}
while true; do
if [[ -z "$*" ]]; then
# No parameters
read -rp "URL/IP >> " _url
if [[ "${_url}" = "exit" ]]; then
break
elif [[ -z "${_url}" ]]; then
continue
fi
else
# Contains parameters
_url="$*"
fi
if [[ "${_url}" = *"[.]"* || "${_url}" = *"[:]"* ]]; then
# already sanitized
_san::un_sanitize "${_url}"
else
_san::sanitize "${_url}"
fi
unset _url
[[ -n "$*" ]] && break
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment