How to create an else statement with the expect command?
I have the follow expect script which adds a known host if a known host does not exist.
#!/usr/bin/expect
spawn ssh user@domain "cd /home/user"
expect "Are you sure you want to continue connecting (yes/no)?"
send "yes\r"
interact
The script works fine the first time I ssh into a device however if I ssh into a device for a nth + 1 time, it throws an error
send: spawn id exp6 not open
while executing
"send "yes\r""
(file "./testing_spawn.sh" line 4)
presumably because it continues to expect the string Are you sure you want to continue connecting (yes/no)?
How can I tell the script to just interact
if that message does not show up?
Solution 1:
Use expect_before
to match the "unknown host" question only if it comes before the command prompt:
#!/usr/bin/expect
spawn ssh user@domain
expect_before "*(yes/no)?" {
send "yes\r"
}
expect "*# "
interact