bashrc/.bashrc.d/cnssh.bash

144 lines
2.7 KiB
Bash

cnssh() { # Helper for sshing into Crestron devices
#
# USAGE
#
# cnssh <ip address> [command]
#
#
# OPTIONS
#
# -u <username> Specify the username to use with ssh
# Default: "Crestron"
#
# CONFIG ARRAY: cnssh_conf
#
#
# | Option | Valid Args | Default | Description |
# | ------------- | ------------- | ------------- | --------------------------------------------- |
# | uname | <string> | "Crestron" | The username for use with ssh |
# | pass | <string> | "" | The password for use with ssh (via sshpass) |
# | addr | <string> | <ip address> | The address of the remote device |
# | cmd | <string> | [command] | The command to execute on the remote device |
####
# Config init
# Initialize config array if it doesn't already exist
if [[ ! -v cnssh_conf[@] ]]; then
declare -A cnssh_conf
fi
# Initialize and populate default config array
declare -A dconf
dconf=(
[method]="ssh"
[uname]="Crestron"
[pass]=""
)
declare -A sshopts
sshopts=(
[StrictHostKeyChecking]="no"
[GlobalKnownHostsFile]="/dev/null"
[UserKnownHostsFile]="/dev/null"
[LogLevel]="ERROR"
)
# Config init
####
####
# Option Parsing
while getopts ":u:" opt; do
case $opt in
u)
cnssh_conf[uname]="$OPTARG"
;;
\?)
echo "Unknown option -$OPTARG"
return 1
;;
:)
echo "Option requires argument: -$OPTARG"
return 1
;;
esac
done
# Remove parsed options from $@
shift $((OPTIND -1))
# Set the address based on the first
# arg if not already set in config array
if [[ ! -v cnssh_conf[addr] ]]; then
cnssh_conf[addr]="$1"
shift 1
fi
# Set the command as the rest of argv
# if not already set in config array
if [[ ! -v cnssh_conf[cmd] ]]; then
cnssh_conf[cmd]="$*"
fi
# Apply defaults to running config
for opt in "${!dconf[@]}"; do
# Don't apply the default if it's already set
if [[ ! -v cnssh_conf[$opt] ]]; then
cnssh_conf[$opt]=${dconf[$opt]}
fi
done
# Set ssh user name
sshopts[User]="${cnssh_conf[uname]}"
# Set ssh host if not using sftp mode
case ${cnssh_conf[method]} in
ssh)
sshopts[Host]="${cnssh_conf[addr]}"
;;
sftp)
:
;;
*)
echo "Unknown method: ${cnssh_conf[method]}"
;;
esac
for opt in "${!sshopts[@]}"; do
sshoptstring="$sshoptstring -o $opt=${sshopts[$opt]}"
done
# Option Parsing
####
####
# Main
sshpass -p "${cnssh_conf[pass]}" \
"${cnssh_conf[method]}" \
$sshoptstring \
"${cnssh_conf[cmd]}"
# Main
####
}
cnsftp() {
# Initialize config array if it doesn't already exist
if [[ ! -v cnssh_conf[@] ]]; then
declare -A cnssh_conf
fi
# Set sftp mode instead of ssh
cnssh_conf[method]="sftp"
cnssh_conf[cmd]="$*"
cnssh
}