Search code examples
shellexpect

Linux shell: why "send" command doesn't run


I need some help on below code. I just need to achieve some simpliest task. bakcup and replace some ssl certificate files. but it doesn't seem to work. what is wrong with below code:

import_esx() {
local username=root
local backuptimestamp=$(date +"%m-%d-%y-%I:%M:%S_%p")

/usr/bin/expect << EOF
set timeout 30
spawn ssh -l $username $Ip_Address
expect {
        "(yes/no)?" { send "yes\r"; exp_continue }
        "*?assword: " { send "$CommonPassword\r"; exp_continue}
}

send_user "Backing up current certificates\r"
send "mv /etc/vmware/ssl/rui.key /etc/vmware/ssl/rui.key.$backuptimestamp\r"
send "mv /etc/vmware/ssl/rui.crt /etc/vmware/ssl/rui.crt.$backuptimestamp\r"
send "mv /etc/vmware/ssl/castore.pem /etc/vmware/ssl/castore.pem.$backuptimestamp\r"


EOF
}

thanks Jerry


Solution

  • expect {
            "(yes/no)?" { send "yes\r"; exp_continue }
            "*?assword: " { send "$CommonPassword\r"; exp_continue}
    }
    

    you exp_continue on each branch: You have to expect something else so you can stop looping.

    Before each send, you should expect something, typically the shell prompt. Also, after the last mv command, you need to send "exit\r" and then expect eof

    Assuming your shell prompt ends with "dollar space", you can put it all together:

    set prompt {[$] $}
    
    expect {
        "(yes/no)?" { send "yes\r"; exp_continue }
        "*?assword: " { send "$CommonPassword\r"; exp_continue}
        -re $prompt
    }
    send_user "Backing up current certificates\r"
    send "mv /etc/vmware/ssl/rui.key /etc/vmware/ssl/rui.key.$backuptimestamp\r"
    
    expect -re $prompt
    send "mv /etc/vmware/ssl/rui.crt /etc/vmware/ssl/rui.crt.$backuptimestamp\r"
    
    expect -re $prompt
    send "mv /etc/vmware/ssl/castore.pem /etc/vmware/ssl/castore.pem.$backuptimestamp\r"
    
    expect -re $prompt
    send "exit\r"
    expect eof