Skip to content

Instantly share code, notes, and snippets.

@sayz
Created May 11, 2013 20:16
Show Gist options
  • Select an option

  • Save sayz/5561283 to your computer and use it in GitHub Desktop.

Select an option

Save sayz/5561283 to your computer and use it in GitHub Desktop.
A simple way of connecting to SSH servers
#!/bin/bash
# A simple way of connecting to SSH servers
#
# Usage:
# sssh host_codename [USER]
#
# Configuration file:
# codename host [username]
CONF="$HOME/.sssh_hosts"
_sssh_connect() {
local host address ssh_user
host=$(cat "$CONF" | grep "^$1 ")
if [ -n "$host" ]; then
address=$(echo "$host" | cut -d ' ' -f 2)
if [ $# -lt 2 ]; then
ssh_user=$(echo "$host" | cut -d ' ' -f 3)
else
ssh_user="$2"
fi
# Use default user if none could be found
if [ -n "$ssh_user" ]; then
ssh $ssh_user@$address
else
ssh $address
fi
else
echo "Host not found"
return 1
fi
}
_sssh_help() {
cat << EOF
`basename $0`:
A simple way of connecting to SSH servers
`basename $0` codename [user]
`basename $0` -i codename host [user]
`basename $0` -x codename
`basename $0` -l
`basename $0` --help
Given a codename, connects to the server associated with it using a default
username or the user passed as argument.
-i Insert a new host to the bookmark
-x Remove a saved host
-l List saved connections
-h Help
EOF
}
_sssh_insert() {
if [ "$#" -gt 1 ]; then
echo "$@" >> "$CONF"
else
echo "Insufficient arguments"
return 1
fi
}
_sssh_remove() {
if [ "$#" -eq 1 ]; then
local host=$(cat "$CONF" | grep "^$1 ")
if [ -n "$host" ]; then
local tmpfile=$(mktemp)
cat "$CONF" > "$tmpfile"
sed "/^${1} /d" "$tmpfile" > "$CONF"
rm "$tmpfile"
else
echo "Host not found"
return 1
fi
else
echo "Wrong arguments"
return 1
fi
}
case "$1" in
-i)
shift
_sssh_insert "$@"
;;
-x)
shift
_sssh_remove "$@"
;;
-l)
cat "$CONF"
;;
-h|--help)
_sssh_help
;;
*)
_sssh_connect "$@"
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment