user3115222
user3115222

Reputation: 85

Handle multiple statements in an Expect script

I am new to Expect scripting.

I wrote an Expect script for ssh in a Linux machine, where I am facing a problem in ssh'ing to different Linux machines. Below I have copied the script.

!/usr/local/bin/expect

set LinuxMachine [lindex $argv 0]

spawn ssh root@$LinuxMachine


expect "root@$LinuxMachine's password:"

send "root123\n"

expect "[root@Client_FC12_172_85 ~]#"

send "ls"

interact

When I supply 10.213.172.85 from command line the expect in the 4th line, it reads as "[email protected]'s password:" and logs in successfully

But some Linux will expect

The authenticity of host '10.213.172.108 (10.213.172.108)' can't be established.
RSA key fingerprint is da:d0:a0:e1:d8:7a:23:8b:c7:d8:40:8c:b2:b2:9b:95.
Are you sure you want to continue connecting (yes/no)

In this case the script will not work.

How can I have two Expect statements in one Expect command?

Upvotes: 5

Views: 26451

Answers (2)

Justin
Justin

Reputation: 1

We like to call it "long log in". There are ssh options that don't check the host keys:

send -- "ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no username@host\n"
expect {
        "Password" {
                send -- "$passwd\n"
        }

Part of the Bash script that calls on the expect sets the password:

echo -n "Enter LDAP password: "
read -s passwd
echo

Upvotes: -1

James
James

Reputation: 1236

You can use exp_continue in such a case:

expect {
      "Are you sure you want to continue connecting (yes/no)" {
            send "yes\r"
            exp_continue
      }
      "root@$LinuxMachine's password:" {
            send "root123\r"
            expect "[root@Client_FC12_172_85 ~]#"
            send "ls\r"
            interact
      }
}

In the above, the Expect block waits for either the yes/no question OR the prompt for password. If the latter, it moves on with providing password, expecting prompt, sending ls command and giving control back.

If the former, it will answer 'yes' and repeat the expect block, ready to find the prompt for a password (or even the yes/no question again, for that matter - not that you will need that).

I would also include some timeouts with meaningful messages in case some expect option does not match as expected, but the above should work.

As a side comment, you don't want to set a root password in a script... I recommend using ssh key authentication.

Upvotes: 11

Related Questions