Michael Wagner
Michael Wagner

Reputation: 1038

How to start interactive ssh terminal from bash script?

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

Upvotes: 5

Views: 10535

Answers (2)

that other guy
that other guy

Reputation: 123450

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

Upvotes: 7

Jakuje
Jakuje

Reputation: 25956

You need to provide to -t switches as described in manual page for ssh:

ssh -tt -l $username $hostname

Description from manual page:

Multiple -t options force tty allocation, even if ssh has no local tty.

Upvotes: 3

Related Questions