Skip to content

Instantly share code, notes, and snippets.

@LamberKeep
Last active August 24, 2023 06:05
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 LamberKeep/3d14e6943bda3084a9efe5f62f545b2c to your computer and use it in GitHub Desktop.
Save LamberKeep/3d14e6943bda3084a9efe5f62f545b2c to your computer and use it in GitHub Desktop.
Simple SSH/SFTP manager
#!/bin/sh
# Simple SSH/SFTP manager
#
# Created: 2023.05.23
# Updated: 2023.08.24
#
# Author: Alexey Savin (LamberKeep)
# To run connection manager just run this file.
#
# Connection list file example:
# user1@hostname1
# user2@hostname1
# user1@hostname2
# user2@hostname2
connection_manager()
{
cat -n $2
echo -ne "\nChoose connection: "
read answer
if [ $answer -gt $(wc -l < $2) ]
then
echo -e "\nNot a option.\n"
exit 1
fi
remote=$(head -n $answer $2 | tail -n 1)
remoteAddress=$(echo $remote | sed -n 's|.*@||p')
if ! try_to_reach $remoteAddress
then
echo "Target not reached"
exit 1
fi
clear
eval $1 $remote
}
try_to_reach()
{
for attempts in $(seq 1 3)
do
echo "[$attempts] Trying to connect: $1"
if ping -c 1 $1 &> /dev/null
then
return 0
fi
sleep 10s
done
return 1
}
try_help()
{
echo -e "Try 'sh $(basename $0) --help' for more information.\n"
}
echo -e "\nSimple SSH/SFTP manager\n"
if [ ! -z "$2" ]
then
if [ -z "$SSH_LIST" ]
then
SSH_LIST=$2
fi
if [ -z "$SFTP_LIST" ]
then
SFTP_LIST=$2
fi
fi
if [[ $@ =~ "--help" ]]
then
echo -e "Usage: $(basename $0) [OPTIONS] [FILE]\n\nOptions, with no OPTIONS will use '--ssh' by default:\n\t--help\toutput this help\n\t--ssh\tSSH manager\n\t--sftp\tSFTP manager\n\nWith no FILE will use files with SSH and SFTP addresses from following enviroment variables:\n\tSSH_LIST\n\tSFTP_LIST\n"
exit 0
fi
if [ ! -f $SSH_LIST -o ! -f $SFTP_LIST ]
then
echo -e "$(basename $0): no connection list file"
try_help
exit 1
fi
case "$1" in
""|--ssh)
connection_manager ssh $SSH_LIST
exit 0
;;
--sftp)
connection_manager sftp $SFTP_LIST
exit 0
;;
--*)
echo -e "$(basename $0): unrecognized option '$1'"
try_help
exit 1
;;
*)
connection_manager ssh $1
exit 0
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment