I often connect through ssh to Docker containers running on a remote server. Every time the container is stopped or removed, I need to copy my ssh key on the container again, in order to connect. For this reason, on my Mac laptop I put this simple bash script, whose goal is simply to add my ssh key to the Docker container to which I want to connect.
#!/bin/bash
# A POSIX variable
OPTIND=1 # Reset in case getopts has been used previously in the shell.
# Default parameter value:
PORT=...
PUBKEY=...
HOST_IP=...
# show_help function
show_help() {
echo "Usage: $(basename "$0") [-h] [-p PORT] [-f PUBKEY] [-i HOST_IP]"
echo
echo " -p PORT add key to container running on port PORT (default: ...)"
echo " -f PUBKEY add key file PUBKEY (default: ...)"
echo " -i HOST_IP connect to host HOST_IP (default: ...)"
echo
return
}
while getopts ":h:p:f:u:" option; do
case "$option" in
?)
echo "invalid argument"
show_help
exit 1
;;
h)
show_help
exit 0
;;
p) PORT=$OPTARG
;;
f) PUBKEY=$OPTARG
;;
;;
i) HOST_IP=$OPTARG
esac
done
shift $((OPTIND-1))
USER_AT_HOST="root@$HOST_IP"
PUBKEYPATH="$HOME/.ssh/$PUBKEY"
ssh-copy-id -i "$PUBKEYPATH" "$USER_AT_HOST" -p "$PORT"
exit 0
I have two problems:
-
(smaller) the arguments have non-intuitive letters (
f
for thePUBKEY
,i
for theHOST_IP
) because if I’m not mistaken,getopts
only support single-letter arguments. Is there any way to circumvent this limitation? If not, could you suggest some more creative/self-explanatory letters for the arguments? 🙂 -
(bigger) currently the
-p
argument (PORT
) is mandatory, and the user used for the ssh connection is alwaysroot
. I would like to modify the script so that, if the-p
argument is not passed, then another argument-u
(USER
) must be passed, and the connection command becomesUSER_AT_HOST="$USER@$HOST_IP" PUBKEYPATH="$HOME/.ssh/$PUBKEY" ssh-copy-id -i "$PUBKEYPATH" "$USER_AT_HOST"
instead than
USER_AT_HOST="root@$HOST_IP" PUBKEYPATH="$HOME/.ssh/$PUBKEY" ssh-copy-id -i "$PUBKEYPATH" "$USER_AT_HOST" -p "$PORT"
How could I modify the script in order to obtain this result?