SSH/Expect How does "expect" work in expect shell script?

Viewed 41

I try to use ssh remote login with expect. It works, but some outputs are not expected and I do not know why. This is my shell script:

#!/bin/sh
expect -c ' spawn ssh USER@ADDRESS ; 
            expect "?assword:" ; 
            send "MyPassword\r" ;
            expect "?" ;
            send "logout\r" ; 
            interact'

This is the output in my MacOS terminal:

ip87-114:Downloads tasiyuchien$ ./test.sh 
spawn ssh USER@ADDRESS
Password:
logout
Last login: Tue Sep 13 18:17:21 2022 from ADDRESS
xdn42o221:~ USER$ logout
Connection to ADDRESS closed.
ip87-114:Downloads tasiyuchien$ 

The first question is why there is a "logout" output after "Password:"? Isn't the question mark represents any single character? Is there any implicit output or pattern I don't see cause I see nothing after "Password:". (Also strangely, when I replace "?" as "*", nothing will be output after "Password:" and the automatic logout also failed.) The same question can be asked when I login, cause I also see nothing but the "logout" is output.

The second question is why are there two "logout" outputted, I thought the except argument can be reused only if "except continue" is added.

Can anyone explain to me what's happening. Thanks!

1 Answers

As part of the login process, after the Password: prompt is shown, you enter your password and hit Enter, then the login process prints a newline. This newline is the character matched by "?".

Changing "?" to "*" works better: the asterisk is more greedy probably. Instead of matching exactly one character, it matches one or more characters, so it will try to collect as many as possible.

Why two "logout"s appear? I don't know. Perhaps your shell re-prints user input after displaying your prompt..

Related