Skip to content

Instantly share code, notes, and snippets.

@zAbuQasem
Last active April 19, 2024 04:43
Show Gist options
  • Save zAbuQasem/ba1c6ecded25b646a884c72943321113 to your computer and use it in GitHub Desktop.
Save zAbuQasem/ba1c6ecded25b646a884c72943321113 to your computer and use it in GitHub Desktop.
Add an entry to ssh config
#!/bin/bash
if [[ $# -lt 2 ]]; then
echo -e "\e[31m[Error]: Not enough arguments!\e[0m"
echo -e "\e[31m[!] Position Matters!\e[0m"
echo -e "\e[32m[+] Usage: ssh-config.sh [-i identity_file] [-p port] user@host alias\e[0m"
exit 1
fi
while getopts "i:p:" opt; do
case ${opt} in
i )
PRIVATE_KEY=${OPTARG}
;;
p )
CONF_PORT=${OPTARG}
;;
\? )
echo -e "\e[31m[Error]: Invalid option!\e[0m"
echo -e "\e[31mUsage: SSHCONFIG [-i identity_file] [-P port] user@host alias\e[0m"
echo -e "\e[31m[!] Position Matters!\e[0m"
exit 1
;;
esac
done
shift $((OPTIND -1))
SSH_ARGS=$1
HOST=$(echo $1 | cut -d '@' -f 2)
ALIAS=$2
PORT="${CONF_PORT:-22}"
if [[ -n "$PRIVATE_KEY" ]]; then
cat <<EOF >> "/home/${USER}/.ssh/config"
Host $ALIAS
HostName ${HOST}
User ${SSH_ARGS%@*}
Port ${PORT}
IdentityFile $(pwd)/$PRIVATE_KEY
EOF
echo -e "\e[32m[Success]: SSH configuration added for $ALIAS\e[0m"
else
cat <<EOF >> "/home/${USER}/.ssh/config"
Host $ALIAS
HostName ${HOST}
User ${SSH_ARGS%@*}
Port ${PORT}
EOF
echo -e "\e[32m[Success]: SSH configuration added for $ALIAS\e[0m"
fi
@zAbuQasem
Copy link
Author

zAbuQasem commented Feb 19, 2024

Install

wget https://gist.githubusercontent.com/zAbuQasem/ba1c6ecded25b646a884c72943321113/raw/50022809d8fac526ab7c6865492e035340461bef/ssh-config.sh
chmod +x ssh-config.sh
sudo mv ssh-config.sh /usr/bin

Usage:

ssh-config.sh [-i identity_file] [-p port] user@host ALIAS
# Host will be added to ~/.ssh/config
cat ~/.ssh/config

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment