I want to start an SSH session from a bash script. After $username and $hostname are read from a file, an interactive SSH session should start like if it was started manually. The login is done using public key.
My code:
ssh -t -l $username $hostname
This makes me see the SSH session, but I can't interact with it. How can I solve this?
Thanks!
Full script:
#!/bin/bash
HOSTS_FILE=".mloginconnections"
echo ""
echo " *****************************"
echo " * *"
echo " * MICWAG SSH LOGIN SYSTEM *"
echo " * *"
echo " *****************************"
echo ""
function handleAdd {
echo "Add remote host"
echo ""
echo "Enter connection alias:"
read aliasname
echo "Enter hostname:"
read hostname
echo "Enter username:"
read username
if [ ! -f $HOSTS_FILE ]
then
touch $HOSTS_FILE
fi
echo "$aliasname:$hostname:$username" > $HOSTS_FILE
}
function handleConnect {
if [ $# -ne 1 ]
then
echo "Usage:"
echo "connect [serveralias]"
else
echo "Try to connect to server $1"
cat $HOSTS_FILE | while read line
do
IFS=':' read -ra conn <<< $line
aliasname=${conn[0]}
hostname=${conn[1]}
username=${conn[2]}
if [ "$aliasname" == "$1" ] || [ "$hostname" == "$1" ]
then
echo "Found host: $username@$hostname"
ssh -tt -l $username $hostname
fi
done
fi
}
function handleCommand {
echo "Enter command:"
read command
case $command in
add)
handleAdd
;;
exit)
exit
;;
*)
handleConnect $command
;;
esac
echo ""
}
while [ 1 ]
do
handleCommand
done
The problem is that you give ssh
input from your cat $HOSTS_FILE
command instead of from your keyboard. That's why you can't interact with it.
The easiest, ugliest fix is to redirect from the current tty:
ssh -t -l $username $hostname < /dev/tty
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With