From c2ddb0184a8259208412431d79917e88f580c474 Mon Sep 17 00:00:00 2001 From: David Thurstenson Date: Thu, 6 May 2021 14:25:10 -0500 Subject: [PATCH] cnssh: Refactored to support authentication on remote devices --- .bashrc.d/cnssh.bash | 107 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 97 insertions(+), 10 deletions(-) diff --git a/.bashrc.d/cnssh.bash b/.bashrc.d/cnssh.bash index 2a2eb24..278efd1 100644 --- a/.bashrc.d/cnssh.bash +++ b/.bashrc.d/cnssh.bash @@ -1,16 +1,103 @@ -cnssh() { - # Usage: cnssh [command] - local uname="Crestron" - local pass="" - local addr="$1" - shift - local cmd="$@" +cnssh() { # Helper for sshing into Crestron devices + # + # USAGE + # + # cnssh [command] + # + # + # OPTIONS + # + # -u Specify the username to use with ssh + # Default: "Crestron" + # + # CONFIG ARRAY: cnssh_conf + # + # + # | Option | Valid Args | Default | Description | + # | ------------- | ------------- | ------------- | --------------------------------------------- | + # | uname | | "Crestron" | The username for use with ssh | + # | pass | | "" | The password for use with ssh (via sshpass) | + # | addr | | | The address of the remote device | + # | cmd | | [command] | The command to execute on the remote device | - sshpass -p "$pass" ssh \ + + #### + # 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=( + [uname]="Crestron" + [pass]="" + ) + + # 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 + + # Option Parsing + #### + + + #### + # Main + + sshpass -p "${cnssh_conf[pass]}" ssh \ -o StrictHostKeyChecking=no\ -o GlobalKnownHostsFile=/dev/null\ -o UserKnownHostsFile=/dev/null\ -o LogLevel=ERROR\ - -o User="$uname"\ - "$addr" "$cmd" + -o User="${cnssh_conf[uname]}"\ + "${cnssh_conf[addr]}" "${cnssh_conf[cmd]}" + + # Main + #### }