Skip to content

Instantly share code, notes, and snippets.

@cameronraysmith
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cameronraysmith/2d3967b5c7e774c9835c to your computer and use it in GitHub Desktop.
Save cameronraysmith/2d3967b5c7e774c9835c to your computer and use it in GitHub Desktop.
Add/remove hosts to/from .ssh/config and etc/hosts files
#!/bin/bash
# initialize help variables
usageHelp="Usage: ${0##*/}
three arguments to add
usage: hostmod -n hostname -i IPaddress -k keyfile
one argument to remove
usage: hostmod -n hostname
"
hostnameHelp="-n memorable name for host"
ipHelp="-i ip address of host"
keyFileHelp="-k name of keyfile in $HOME/.ssh"
# define help functions
printHelpAndExit()
{
echo "$usageHelp"
echo "$hostnameHelp"
echo "$ipHelp"
echo "$keyFileHelp"
exit $1
}
printErrorHelpAndExit()
{
# echo
# echo "$@"
# echo
# echo
printHelpAndExit 1
}
# initialize argument variables
HOSTNAME=""
IPADDRESS=""
KEYFILE=""
# initialize colors
red='\033[0;31m'
green='\033[0;32m'
NC='\033[0m'
# process arguments
while getopts "hn:i:k:" optionName; do
case "$optionName" in
h) printHelpAndExit 0;;
n) HOSTNAME="$OPTARG";;
i) IPADDRESS="$OPTARG";;
k) KEYFILE="$OPTARG";;
[?]) printErrorHelpAndExit "$badOptionHelp";;
esac
done
# execute
if [[ -n $HOSTNAME ]] && [[ -n $IPADDRESS ]] && [[ -n $KEYFILE ]]
then
echo -e "Host $HOSTNAME
User ubuntu
HostName $IPADDRESS
IdentityFile $HOME/.ssh/$KEYFILE
" >> $HOME/.ssh/config
sudo echo -e "$IPADDRESS\t$HOSTNAME" >> /etc/hosts
echo -e "${green}Added host in $HOME/.ssh/config${NC}"
grep -B 1 -A 4 $HOSTNAME $HOME/.ssh/config
echo -e "${green}Added host in /etc/hosts\n${NC}"
grep -B 1 -A 1 $HOSTNAME /etc/hosts
elif [[ -n $HOSTNAME ]] && [[ -z $IPADDRESS ]] && [[ -z $KEYFILE ]]
then
sed -e "/\<$HOSTNAME\>/,+4d" -i.backup $HOME/.ssh/config
sudo sed -e "/\<$HOSTNAME\>/d" -i.backup /etc/hosts
echo -e "${red}Removed host in $HOME/.ssh/config${NC}"
grep -B 1 -A 4 $HOSTNAME $HOME/.ssh/config
echo -e "${red}Removed host in /etc/hosts${NC}"
grep -B 1 -A 1 $HOSTNAME /etc/hosts
else
printErrorHelpAndExit
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment