Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start interactive ssh terminal from bash script?

Tags:

linux

bash

ssh

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
like image 705
Michael Wagner Avatar asked Feb 10 '23 10:02

Michael Wagner


1 Answers

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
like image 196
that other guy Avatar answered Feb 13 '23 03:02

that other guy