Last active
August 16, 2024 19:51
-
-
Save AlexAtkinson/bc765a0c143ab2bba69a738955d90abd to your computer and use it in GitHub Desktop.
BASH Aliases
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# .bashrc QoL adds. | |
# Ultra lazy... | |
alias urc='source ~/.bashrc' | |
# Save history immediately | |
shopt -s histappend | |
#PROMPT_COMMAND="history -a;$PROMPT_COMMAND" | |
# https://askubuntu.com/questions/67283/is-it-possible-to-make-writing-to-bash-history-immediate | |
export PROMPT_COMMAND="history -a; history -c; history -r; $PROMPT_COMMAND" | |
# Change default systemctl editor | |
# NOTE: Must also add to sudoers with 'sudo visudo': `Defaults env_keep += "SYSTEMD_EDITOR"` | |
export SYSTEMD_EDITOR=vim | |
# Change editor to VIM | |
export EDITOR=vim | |
# Make visudo use vim with sudo | |
alias visudo='sudo EDITOR=vim visudo' | |
# Daily Notes | |
# Usage: | |
# Add entry: | |
# dnote Did some thing | |
# Show todays notes | |
# dnotes | |
# Show yesterdays notes | |
# dnotes yesterday | |
# dnotes y | |
# Turn on colors in less | |
alias less='less -R $@' | |
function check_os_distro() { | |
awk -F= '$1=="NAME" { gsub(/"/,"",$2); print $2 }' /etc/*-release | |
} | |
function check_os_arch() { | |
case $(uname -m) in | |
arm64|aarch64) export ARCH="ARM64" ;; | |
armhf|armv7*) export ARCH="ARM32_COMPAT" ;; | |
armv8*) export ARCH="ARM64_COMPAT" ;; | |
i*86*) export ARCH="x86" ;; | |
amd64|x86_64*) export ARCH="x64" ;; | |
*) export ARCH="unknown: $ARCH" ;; | |
esac | |
echo $ARCH | |
} | |
check_os_arch | |
function check_os_type() { | |
case "$OSTYPE" in | |
solaris*) export OS_TYPE="SOLARIS" ;; | |
darwin*) export OS_TYPE="OSX" ;; | |
linux*) export OS_TYPE="LINUX" ;; | |
bsd*) export OS_TYPE="BSD" ;; | |
msys*) export OS_TYPE="WINDOWS" ;; | |
cygwin*) export OS_TYPE="CYGWIN" ;; | |
*) export OS_TYPE="unknown: $OSTYPE" ;; | |
esac; | |
echo $OS_TYPE | |
} | |
check_os_type | |
function logger2() { | |
[[ $1 -eq 0 ]] && echo -e "$(date --utc +'%FT%T.%3NZ') - \e[01;30;41mEMERGENCY\e[0m: ${*:2}" | |
[[ $1 -eq 1 ]] && echo -e "$(date --utc +'%FT%T.%3NZ') - \e[01;31;43mALERT\e[0m: ${*:2}" | |
[[ $1 -eq 2 ]] && echo -e "$(date --utc +'%FT%T.%3NZ') - \e[01;97;41mCRITICAL\e[0m: ${*:2}" | |
[[ $1 -eq 3 ]] && echo -e "$(date --utc +'%FT%T.%3NZ') - \e[01;31mERROR\e[0m: ${*:2}" | |
[[ $1 -eq 4 ]] && echo -e "$(date --utc +'%FT%T.%3NZ') - \e[01;33mWARNING\e[0m: ${*:2}" | |
[[ $1 -eq 5 ]] && echo -e "$(date --utc +'%FT%T.%3NZ') - \e[01;30;107mNOTICE\e[0m: ${*:2}" | |
[[ $1 -eq 6 ]] && echo -e "$(date --utc +'%FT%T.%3NZ') - \e[01;39mINFO\e[0m: ${*:2}" | |
[[ $1 -eq 7 ]] && echo -e "$(date --utc +'%FT%T.%3NZ') - \e[01;97;46mDEBUG\e[0m: ${*:2}" | |
[[ $1 -eq 9 ]] && echo -e "$(date --utc +'%FT%T.%3NZ') - \e[01;32mSUCCESS\e[0m: ${*:2}" | |
} | |
daily_notes_log_file="/home/$USER/DailyNotes.md" | |
function daily_notes() { | |
[[ $# -lt 1 ]] && echo -e "\e[01;31mERROR\e[0m: What's going on?" | |
date=$(date +'%Y-%m-%d') | |
[[ ! -f "$logfile" ]] && echo -e "# Daily Notes\n" > "$daily_notes_log_file" | |
if [[ ! $(head -n 20 $daily_notes_log_file | grep "$date") ]]; then | |
sed -i "2 a \#\# $date" "$daily_notes_log_file" | |
sed -i $'3 a \n' "$daily_notes_log_file" | |
fi | |
if [[ $# -gt 0 ]]; then | |
sed -i "3 a - $*" "$daily_notes_log_file" | |
fi | |
} | |
alias dnote='daily_notes' | |
function daily_notes_today() { | |
if [[ $(awk "/## $(date +'%Y-%m-%d')/,/^$/" $daily_notes_log_file | wc -l) -eq 0 ]]; then | |
echo -e "No entries yet for today. Here are yesterdays notes.\n" | |
awk "/## $(date -d "yesterday" +'%Y-%m-%d')/,/^$/" $daily_notes_log_file | |
else | |
if [[ $1 == 'yesterday' || $1 == 'y' ]]; then | |
awk "/## $(date -d "yesterday" +'%Y-%m-%d')/,/^$/" $daily_notes_log_file | |
else | |
awk "/## $(date +'%Y-%m-%d')/,/^$/" $daily_notes_log_file | |
fi | |
fi | |
} | |
alias dnotes='daily_notes_today' | |
# Sysinfo | |
function os-info() { | |
key=$@ | |
function help { | |
echo -e "Try: NAME, PRETTY_NAME, VERSION_ID, VERSION, ID_LIKE" | |
echo -e "REF: https://www.freedesktop.org/software/systemd/man/os-release.html" | |
return 0 | |
} | |
[[ $key == '-h' ]] && help | |
[[ $# -eq 0 ]] && help | |
for key in "$@"; do | |
sed -ne "s/^$key=//p" /etc/os-release | tr -d '"' | |
done | |
} | |
# JWT | |
jwt_decode_base64_url() { | |
local len=$((${#1} % 4)) | |
local result="$1" | |
if [ $len -eq 2 ]; then result="$1"'==' | |
elif [ $len -eq 3 ]; then result="$1"'=' | |
fi | |
echo "$result" | tr '_-' '/+' | openssl enc -d -base64 | |
} | |
jwt_decode(){ | |
jwt_decode_base64_url $(echo -n $2 | cut -d "." -f $1) | jq . | |
} | |
# Decode JWT header | |
alias jwt_header="jwt_decode 1" | |
# Decode JWT Payload | |
alias jwt_payload="jwt_decode 2" | |
# Create JWT Key/Cert | |
jwt_create(){ | |
# -subj "/C=/ST=/L=/O=/OU=/CN=" \ | |
read -p "Output Key File [id.key]: " output_key; output_key=${output_key:-id.key} | |
read -p "Output Cert File [id.cert]: " output_cert; output_cert=${output_crt:-id.cert} | |
openssl req \ | |
-new \ | |
-newkey rsa:4096 \ | |
-days 3650 \ | |
-nodes \ | |
-x509 \ | |
-keyout $output_key \ | |
-out $output_cert | |
} | |
# File Tools | |
function file-age { | |
[[ ! -f $1 ]] && return 1 | |
b="$(date --date=$(stat $1 | awk '/Birth:/ {print $2"T"$3}' | cut -d. -f1) +%s)" | |
d=$(($(date +%s) - b)) | |
date -d@$d -u +%H:%M:%S | |
} | |
function find-large-dirs() { | |
if [[ $# -ne 1 || $1 == "-h" ]]; then | |
logger2 3 Exactly one argument required: path \(eg: \/ or \/tmp\/\); | |
return 1; | |
fi; | |
du -hsx $1* 2> >(grep -v '^du: cannot \(access\|read\)' >&2) | sort -rh | head -10 | |
} | |
# Cheats/Helpers | |
function color-helper() { | |
echo -e "\nColorized Severity (rfc5424 - https://hackmd.io/@njjack/syslogformat)" ;\ | |
echo -e "\e[01;30;41mEMERGENCY\e[0m \\\e[01;30;41mEMERGENCY\\\e[0m : 0 - Bold BLACK text, RED background" ;\ | |
echo -e "\e[01;31;43mALERT\e[0m \\\e[01;31;43mALERT\\\e[0m : 1 - Bold RED text, YELLOW background" ;\ | |
echo -e "\e[01;97;41mCRITICAL\e[0m \\\e[01;97;41mCRITICAL\\\e[0m : 2 - Bold WHITE text, RED background" ;\ | |
echo -e "\e[01;31mERROR\e[0m \\\e[01;31mERROR\\\e[0m : 3 - Bold RED text" ;\ | |
echo -e "\e[01;33mWARNING\e[0m \\\e[01;33mWARNING\\\e[0m : 4 - Bold YELLOW text" ;\ | |
echo -e "\e[01;30;107mNOTICE\e[0m \\\e[01;30;107mNOTICE\\\e[0m : 5 - Bold BLACK text, WHITE background" ;\ | |
echo -e "\e[01;39mINFORMATIONAL\e[0m \\\e[01;39mINFORMATIONAL\\\e[0m : 6 - Bold WHITE text" ;\ | |
echo -e "\e[01;97;46mDEBUG\e[0m \\\e[01;97;46mDEBUG\\\e[0m : 7 - Bold WHITE text, CYAN background" ;\ | |
echo -e "\e[01;32mSUCCESS\e[0m \\\e[01;32mSUCCESS\\\e[0m : 9 - Bold GREEN text (non-rfc5424)\n" | |
} | |
# System Maintenance | |
function update-ffmpeg() { | |
release=$(git-latest-release nwjs-ffmpeg-prebuilt/nwjs-ffmpeg-prebuilt | tr ' ' '\n' | grep -i $OS_TYPE | grep $ARCH); | |
dir=$(mktemp -d); | |
cd $dir; | |
wget "https://github.com/nwjs-ffmpeg-prebuilt/nwjs-ffmpeg-prebuilt/releases/download/0.88.0/${release}"; | |
unzip -q ${release}; | |
sudo cp libffmpeg.so /usr/lib/chromium-browser/; | |
cd - | |
} | |
# Terraform | |
alias tf='terraform' | |
alias tfc='tf console' | |
alias tfv='tf validate' | |
alias tff='tf fmt $@' | |
alias tfp='tf plan' | |
alias tfi='tf init' | |
alias tfa='tf apply' | |
alias tfw='tf workspace $@' | |
alias tfws='tfw show' | |
alias tfwl='tfw list' | |
alias tfwsl='tfw select' | |
alias tfwn='tfw new $@' | |
alias tfwd='tfw delete $@' | |
# Go | |
export GOPATH=$HOME/go | |
export GOBIN=$HOME/go/bin | |
PATH="$PATH:/usr/local/go/bin" | |
export PATH | |
# Formatting & String Manipulation | |
function lower() { tr '[:upper:]' '[:lower:]' ; } | |
function upper() { tr '[:lower:]' '[:upper:]' ; } | |
function printTitle() { | |
txt="$@" | |
printf '\n%*s' "$((${COLUMNS}-$((${COLUMNS}-$(wc -c<<<$txt)-3))))" | tr ' ' \# | |
printf "\n\e[01;39M# ${txt} #\e[0m" | |
printf '\n%*s' "$((${COLUMNS}-$((${COLUMNS}-$(wc -c<<<$txt)-3))))" | tr ' ' \# | |
printf '\n' | |
} | |
function printHeading() { | |
txt="$@" | |
printf "\n\e[01;39M${txt}\e[0m " | |
printf '\n%*s' "$((${COLUMNS}-$((${COLUMNS}-$(wc -c<<<$txt)+1))))" | tr ' ' - | |
printf '\n' | |
} | |
# See other gist for awesome printSectionheader... | |
# Clipboard | |
[[ ! $(command -v xclip) ]] && echo -e "\e[01;31mERROR:\e[0m ${BASH_SOURCE[0]} - xclip not available!" | |
alias clipc="xclip -selection c" | |
alias clipp="xclip -selection c -o" | |
alias clipv="clipp | less" | |
# PW Generators | |
#alias genpass_alnumspec='pin1="!@#$%^&*()<>[]{}|_+-="; pin2=$(openssl rand -base64 128 | fold -w 20 | head -n 1); pout1=$(openssl rand -base64 128 | tr -dc 'a-zA-Z' | fold -w 1 | head -n 1); pout2=$(echo "${pin1}${pin2}" | fold -w 1 | shuf | tr -d "\n" | fold -w 19 | head -n 1); echo "${pout1}${pout2}"' | |
genpass_alnum () { | |
[[ $1 -gt 128 ]] && echo "ERROR: int must be <= 128, if supplied." && return 1; | |
len=$1; | |
if [[ -z $1 ]]; then | |
openssl rand -base64 128 | tr -dc 'a-zA-Z0-9' | fold -w 20 | head -n 1; | |
else | |
openssl rand -base64 128 | tr -dc 'a-zA-Z0-9' | fold -w $((len)) | head -n 1; | |
pout2=$(echo -n "${pin1}${pin2}" | fold -w 1 | shuf | tr -d "\n" | fold -w $((len - 1)) | head -n 1); | |
fi | |
} | |
genpass_alnumspec () { | |
[[ $1 -gt 128 ]] && echo "ERROR: int must be <= 128, if supplied." && return 1; | |
len=$1; | |
pin1="!@#$%^&*()<>[]{}|_+-="; | |
pin2=$(openssl rand -base64 128 | fold -w 20 | head -n 1); | |
pout1=$(openssl rand -base64 128 | tr -dc 'a-zA-Z' | fold -w 1 | head -n 1); | |
if [[ -z $1 ]]; then | |
pout2=$(echo -n "${pin1}${pin2}" | fold -w 1 | shuf | tr -d "\n" | fold -w 19 | head -n 1); | |
else | |
pout2=$(echo -n "${pin1}${pin2}" | fold -w 1 | shuf | tr -d "\n" | fold -w $((len - 1)) | head -n 1); | |
fi; | |
echo "${pout1}${pout2}" | |
} | |
# Encrypt a password with bcrypt... | |
function encrypt_pass_bcrypt() { | |
read -s -p "Password: " password; | |
computing_time=$1; | |
if [[ -z $computing_time ]]; then | |
logger2 5 "Computing time not supplied. Using Default: 12."; | |
computing_time=12; | |
fi; | |
echo ''; | |
htpasswd -bnBC "$computing_time" "" $password | tr -d ':\n'; | |
echo '' | |
} | |
# Tmux Control | |
alias tmuxn='tmux new-session -s $1' | |
alias tmuxk='tmux kill-session -t $1' | |
alias tmuxa='tmux attach-session -t $1' | |
alias tmuxl='tmux ls' | |
function tmuxwhereami() { | |
if [[ -n $TMUX ]]; then | |
echo -e "\e[01;39mINFO\e[0m: Current TMUX session: $(tmux display-message -p "#S")" | |
else | |
echo -e "\e[01;31mERROR\e[0m: Not in a TMUX session." | |
fi | |
} | |
# Trace redirects | |
function dnsTraceRedirects() { | |
url=$1; | |
totalTime=0; | |
unset run; | |
while [[ "$run" != 'term' ]]; do | |
ts=$(date +%s%N); | |
curl -skI ${url} > /dev/null 2>&1; | |
tt=$((($(date +%s%N) - $ts)/1000000)); | |
totalTime=$((totalTime + tt)); | |
[[ "$run" != 'last' ]] && server=$(wget --server-response --no-check-certificate --max-redirect 0 --tries 1 ${url} 2>&1 | awk '/^ Server:/{print $2}'); | |
[[ "$run" != 'last' ]] && response=$(wget --server-response --no-check-certificate --max-redirect 0 --tries 1 ${url} 2>&1 | awk '/^ HTTP/{print $1 "("$2")"}'); | |
[[ "$run" != 'last' ]] && printf "$tt ms : ${url}"; | |
lastURL=${url}; | |
url=$(wget --server-response --no-check-certificate --tries 1 -O - ${url} 2>&1 | head -n25 | awk '/^Location/{print $2; exit}'); | |
if [[ -n $url ]]; then | |
printf " [ ${server}:${response} ] >> ${url}\n"; | |
else | |
if [[ "$run" != 'last' ]]; then | |
run=last; | |
else | |
if [[ "$run" == 'last' ]]; then | |
printf " [ ${server}:${response} ] (Terminated)\n"; | |
printf "Total Time (initial asset): ${totalTime} ms\n"; | |
run='term'; | |
fi; | |
fi; | |
fi; | |
done | |
} | |
export -f dnsTraceRedirects | |
# Dig, nslooup, etc. | |
alias digna='dig +noall +answer $1' | |
alias digns='dig NS +noall +answer $1' | |
alias digsoa='dig SOA +noall +answer $1' | |
function digsoahost() { | |
digsoa | awk '{gsub(/.$/,"",$5); print $5}' | |
} | |
function digttl() { | |
dig +noall +answer $1 @$(digns $1 | awk 'NR==1 {print $5}') | awk 'NR==1 {print $2}' | |
} | |
function nslookupsoa() { | |
nslookup $1 $(digsoahost $1) | |
} | |
function ssl-get-sans() { | |
printf "Q" | openssl s_client -connect $1:443 -servername $1 2>&1 | \ | |
openssl x509 -in /dev/stdin -text -noout -certopt \ | |
no_header,no_version,no_serial,no_signame,no_validity,no_subject,no_issuer,no_pubkey,no_sigdump,no_aux 2>&1 | \ | |
grep -o -P "DNS:.*" | sed 's/, /\n/g' | tr -d "DNS:" | |
} | |
alias tls-get-sans='ssl-get-sans $1' | |
function tls-get-expiry() { | |
DOMAIN=$1 | |
EXP_DATE_RAW=$((echo -n Q \ | |
| openssl s_client --servername $DOMAIN --connect $DOMAIN:443 \ | |
| openssl x509 --noout -dates) 2>&1 \ | |
| grep notAfter | cut -d= -f2- | head -n1) | |
EXP_DATE=$(date -d"$EXP_DATE_RAW" --utc +"%FT%T.%3NZ") | |
echo Expiry date for $DOMAIN is $EXP_DATE $([[ "$EXP_DATE" < $(date --utc +"%FT%T.%3NZ") ]] && echo -e "-- \e[01;97;41mEXPIRED\e[0m") | |
} | |
function url_profile() { | |
for i in $@; do | |
printHeading "$i" | |
echo -e "\e[01;39mDNS Records:\e[0m" | |
digna "$i" | |
echo -e "\n\e[01;39mRedirects:\e[0m" | |
dnsTraceRedirects "$i" | |
echo -e "\n\e[01;39mTLS SANS:\e[0m" | |
tls-get-sans "$i" | |
echo -e "\n\e[01;39mTLS EXPIRY:\e[0m" | |
tls-get-expiry "$i" | |
#Start the report generation. | |
curl -X GET "https://www.ssllabs.com/ssltest/analyze.html?d=${i}&hideResults=on&latest" > /dev/null 2>&1 | |
echo -e "\n\e[01;39mQualys SSL Test:\e[0m" | |
echo -e "https://www.ssllabs.com/ssltest/analyze.html?d=${i}&hideResults=on&latest\n" | |
done | |
} | |
function geoip_lookup() { | |
curl -sS "http://api.ipstack.com/$1?access_key=<yourkey>&output=json&fields=country_code,city" | jq -r '"\(.city), \(.country_code)"' | |
} | |
function constat() { | |
# Requires net-tools procps | |
tmpfile='/tmp/connections.out' | |
netstat -antu > $tmpfile | |
printf "CONNECTION COUNTS (UDP,TCP):\n" | |
printf -- "-----------------\n" | |
for i in CLOSE_WAIT CLOSED ESTABLISHED FIN_WAIT_1 FIN_WAIT_2 LISTEN SYN_RECEIVED SYN_SEND TIME_WAIT UDP ; do | |
echo -e "${i}: $(grep -ci ${i} ${tmpfile})" | |
done | |
echo -e "TOTAL: $(grep -c ^ ${tmpfile})" | |
#rm -f $tmpfile | |
} | |
# Git | |
function git-c-prefix() { | |
unset branch | |
unset c_message | |
unset branch_pass | |
unset c_message_pass | |
branch=$(git rev-parse --abbrev-ref HEAD) | |
c_message=$@ | |
reg='[A-Z]{2,10}-[0-9]{1,7}' | |
#c_prefix='DEVOPS-00: ' # Always insert a valid issue ID... | |
[[ $branch =~ $reg ]] && branch_pass='true' | |
if [[ $branch =~ $reg ]] && ! [[ $c_message =~ $reg ]]; then | |
jira_id=$(sed 's/,$//' <<< $(for i in $(grep -Eo $reg <<< "$branch"); do printf "%s" "$i,"; done)) | |
c_message="${jira_id}: ${c_message}" | |
fi | |
[[ $c_message =~ $reg ]] && c_message_pass="true" | |
if [[ $branch_pass != "true" ]] && [[ $c_message_pass != "true" ]] ; then | |
logger2 3 "No Jira Issue ID Found!" | |
read -p "Enter Jira ID: " jira_id | |
if [[ $jira_id =~ $reg ]]; then | |
c_message="${jira_id}: ${c_message}" | |
else | |
logger2 3 "PEBCAK DETECTED! Quitting!" | |
return 1 | |
fi | |
fi | |
export c_message | |
} | |
function git_push_handler() { | |
result=$(git push 2>&1) | |
if grep -q "no upstream branch" <<< "$result" ; then | |
cmd=$(tail -n 1 <<< "$result") | |
cmd="${cmd#"${cmd%%[![:space:]]*}"}" | |
logger2 5 "Pushing to new remote upstream" | |
eval "$cmd" | |
else | |
echo "$result" | |
fi | |
} | |
alias gitsuno='git status -uno' | |
alias gitsu='git status -u' | |
alias gits='git status .' | |
function gitrhard() { git reset --hard HEAD^; } | |
function gitrohard() { git reset --hard origin/$(git rev-parse --abbrev-ref HEAD); } | |
function gitc() { git-c-prefix $@ && git commit -m "$c_message"; } | |
function gitcp() { git-c-prefix $@ && git commit -m "$c_message"; git_push_handler; } | |
function gitce() { git-c-prefix $@ && git commit --allow-empty -m "$c_message"; } | |
function gitcep() { git-c-prefix $@ && git commit --allow-empty -m "$c_message"; git_push_handler; } | |
function gitdb() { git branch -d $1; git push -d origin $1; } | |
alias git-commit-tree='git log --graph --pretty=oneline --abbrev-commit' | |
function git-commit-grep() { 'git log --oneline | grep $1' ;} | |
#alias git-diff='git difftool -y -x sdiff HEAD^ $1 | pygmentize | less -R' | |
function git-diff() { | |
git difftool -y -x sdiff HEAD^ $1 | \ | |
pygmentize | \ | |
less -R | |
} | |
alias find-the-empty-tree='the_empty_tree=$(git hash-object -t tree /dev/null)' | |
# bytes to human | |
function bytesToHumanReadable() { | |
if test -n "$1"; then | |
input="$@" | |
elif test ! -t 0; then | |
input="$(</dev/stdin)" | |
fi | |
local i=${input:-0} d="" s=0 S=("Bytes" "KiB" "MiB" "GiB" "TiB" "PiB" "EiB" "YiB" "ZiB") | |
while ((i > 1024 && s < ${#S[@]}-1)); do | |
printf -v d ".%02d" $((i % 1024 * 100 / 1024)) | |
i=$((i / 1024)) | |
s=$((s + 1)) | |
done | |
echo "$i$d ${S[$s]}" | |
} | |
alias b2H='bytesToHumanReadable' | |
# Watch Colorizer | |
alias watch='watch --color' | |
# Docker | |
function dockerhub-total-pulls() { | |
image=$(cut -d: -f1 <<< $1) | |
curl -s https://hub.docker.com/v2/repositories/$image | \ | |
jq -r '(paths(scalars) | select(.[-1] == "pull_count")) as $p | [ ( [ $p[] | tostring ] | join(".") ) , ( getpath($p) | tojson ) ] | join(": ")' | \ | |
awk '{s+=$2} END {print s}' | \ | |
xargs printf "%'d" | |
} | |
# EG: dockerhub-total-pulls-report debian:latest ubuntu:latest fedora:latest archlinux:latest opensuse/leap:latest rockylinux:latest almalinux:latest | |
function dockerhub-total-pulls-report() { | |
images=$@ | |
width=50 | |
echo "TOTAL PULLS:" | |
echo "------------" | |
for image in ${images[@]}; do | |
pulls=$(dockerhub-total-pulls $image) | |
printf "%s" "$image" | |
printf "%*s" "$((${COLUMNS}-$((${COLUMNS}-$(wc -c<<<${image}${pulls})+${width}))))" # | tr ' ' - | |
printf "%s\n" "${pulls}" | |
done | |
} | |
function dockerhub_tags() { | |
# List tags for a given docker image | |
if [[ $# -lt 1 ]]; then | |
logger2 2 image basename must be supplied! | |
return 1 | |
fi | |
image=$1 | |
tag_count=$(curl -sS "https://registry.hub.docker.com/v2/repositories/library/$image/tags" | jq -r '.count') | |
total_pages=$(( $tag_count / 100 + 1)) | |
page=1 | |
while [ $page -le $total_pages ]; do | |
curl -sS "https://registry.hub.docker.com/v2/repositories/library/$image/tags?page_size=100&page=$page" | jq -r '."results"[]["name"]' | |
(( page++ )) | |
done | |
} | |
#alias di="docker images | grep -v '^<none>' | grep $1" | |
function di() { | |
# A `docker images` wrapper | |
[[ $# = 0 ]] && docker images | grep -v '^<none>' | |
[[ $# = 0 ]] && return | |
docker images | grep -v '^<none>' | grep $1 | |
} | |
# `docker ps` formated as I prefer | |
alias dps='docker ps --format "table {{.Names}}\t{{.Image}}\t{{.RunningFor}}\t{{.Status}}\t{{.Ports}}"' | |
function dpsw() { | |
# watch `dps` | |
watch -n2 'docker ps --format "table {{.Names}}\t{{.Image}}\t{{.RunningFor}}\t{{.Status}}\t{{.Ports}}"' | |
} | |
# Misc | |
alias timer-start='timer_start=$SECONDS' | |
function timer_handler() { | |
if [[ -n $timer_start ]]; then | |
timer_now_s=$SECONDS | |
timer_duration_s=$(( timer_now_s - timer_start )) | |
else | |
echo "timer not started" | |
exit 1 | |
fi | |
timer_output="$timer_duration_s seconds" | |
if [[ $1 -eq "8601" ]]; then | |
timer_duration_hours=$(( timer_duration_s/3600 )) | |
timer_duration_minutes=$(( timer_duration_s%3600 / 60 )) | |
timer_duration_seconds=$(( timer_duration_s%60%3600 )) | |
timer_duration="$(printf "%02d" $timer_duration_hours):$(printf "%02d" $timer_duration_minutes):$(printf "%02d" $timer_duration_seconds)" | |
timer_output="$timer_duration" | |
fi | |
} | |
function timer_duration() { | |
timer_handler $1 | |
echo $timer_output | |
unset timer_now timer_duration timer_output | |
} | |
function timer-stop() { | |
timer_duration $1 | |
unset timer_start | |
} | |
# Detect File Hogs | |
function detect_file_hogs() { | |
output_lines=10 | |
[[ $1 =~ ^[0-9]+$ ]] && output_lines=$1 | |
tmp=$(mktemp) | |
echo PID OPEN_FILES PROC_HARD_LIMIT PROC-NAME >> $tmp | |
while read line; do | |
open_files=$(echo $line | cut -f1 -d' ') | |
pid=$(echo $line | cut -f2 -d' ') | |
proc_name=$(ps aux | grep "\s$pid\s" | grep -v grep | awk '{print $11}') | |
proc_hard_limit=$(cat /proc/$pid/limits | grep 'files' | awk '{print $5}') | |
echo "$pid $open_files $proc_hard_limit $proc_name" >> $tmp | |
done <<< $(lsof 2>/dev/null | awk '{print $2}' | sort | uniq -c | sort -rn | head -n $output_lines) | |
column -t $tmp | |
rm -f $tmp | |
} | |
# AWS | |
function awscli-update () { | |
# Works for Ubuntu. | |
dir=$(mktemp -d); | |
cd $dir; | |
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"; | |
unzip awscliv2.zip; | |
./aws/install --update; | |
version=$(aws/dist/aws --version | awk '{print $1}' | cut -d/ -f2); | |
sudo rm /usr/local/aws-cli/v2/current/bin/aws; | |
sudo ln -s /usr/local/aws-cli/v2/${version}/bin/aws /usr/local/aws-cli/v2/current/bin/aws; | |
cd - | |
} | |
function awsvpn-update () { | |
if [[ "$(lsb_release -ds)" =~ "22.04" ]]; then | |
if [[ ! -n $(dpkg -S "libssl1.1" 2> /dev/null) ]]; then | |
logger2 2 "libssl1.1 is required for awsvpn to operate in $(lsb_release -ds)! See here: https://blog.reinhard.codes/2023/11/09/using-the-aws-vpn-client-on-ubuntu-22-04/ ."; | |
return 1; | |
fi; | |
fi; | |
dir=$(mktemp -d); | |
cd $dir; | |
curl "https://d20adtppz83p9s.cloudfront.net/GTK/latest/awsvpnclient_amd64.deb" -o "awsvpnclient_amd64.deb"; | |
sudo dpkg -i awsvpnclient_amd64.deb; | |
cd - | |
} | |
function awsWhoAmI() { | |
if [[ $# -ne 1 ]]; then | |
logger2 3 Exactly one argument required: aws_profile_name | |
return 1 | |
fi | |
aws --profile $1 iam get-user --query User.UserName --output text | |
} | |
function awsAccountId() { | |
if [[ $# -ne 1 ]]; then | |
logger2 3 Exactly one argument required: aws_profile_name | |
return 1 | |
fi | |
aws --profile $1 sts get-caller-identity --query "Account" --output text | |
} | |
function awsGetMyTags() { | |
if [[ $# -ne 1 ]]; then | |
logger2 3 Exactly one argument required: aws_profile_name | |
return 1 | |
fi | |
aws --profile $1 iam list-user-tags --user-name $(awsWhoAmI) | |
} | |
function awsEcrLogin() { | |
if [[ $# -ne 1 ]]; then | |
logger2 3 Exactly one argument required: aws_profile_name | |
return 1 | |
fi | |
aws --profile $1 ecr get-login-password | docker login --username AWS --password-stdin $(awsAccountId $1).dkr.ecr.$(aws configure get region --profile $1).amazonaws.com | |
} | |
function awslogin() { | |
if [[ $# -ne 2 ]]; then | |
logger2 3 Exactly two arguments required: aws_profile_name token_code | |
return 1 | |
fi | |
response=$(aws --profile $1 sts get-session-token --serial-number arn:aws:iam::$(awsAccountId $1):mfa/mfa --token-code $2) | |
export AWS_ACCESS_KEY_ID=$(jq -r .Credentials.AccessKeyId <<< $response) | |
export AWS_SECRET_ACCESS_KEY=$(jq -r .Credentials.SecretAccessKey <<< $response) | |
export AWS_SECURITY_TOKEN=$(jq -r .Credentials.SessionToken <<< $response) | |
#. ~/.scripts/aws_get_session_token.sh -a $(awsAccountId $1) -u $(awsWhoAmI $1) -c $2 | |
} | |
function aws-do-all() { | |
for env in devops dev stag prod; do | |
printHeading $env: "$@" | |
aws --profile $env "$@" | |
done | |
} | |
alias awssso='aws sso login --profile $1' | |
alias awsprofiles='aws configure list-profiles' | |
function aws_list_all_actions() { | |
curl --header 'Connection: keep-alive' \ | |
--header 'Pragma: no-cache' \ | |
--header 'Cache-Control: no-cache' \ | |
--header 'Accept: */*' \ | |
--header 'Referer: https://awspolicygen.s3.amazonaws.com/policygen.html' \ | |
--header 'Accept-Language: en-US,en;q=0.9' \ | |
--silent \ | |
--compressed \ | |
'https://awspolicygen.s3.amazonaws.com/js/policies.js' | | |
cut -d= -f2 | | |
jq -r '.serviceMap[] | .StringPrefix as $prefix | .Actions[] | "\($prefix):\(.)"' | | |
sort | | |
uniq | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment