Search code examples
bashexpect

How do I automate a remote login with a bash script


I'm trying to automate a remote login and I wrote the following bash script:

#! /bin/bash
PWD=abc
kinit -f user@domain.com
expect "Password for user@domain.com: "
send "$PWD\n"
ssh -x user@dom.com
interact
cd user/user

My understanding being that "expect" is waiting for the terminal to output something and "interact" should give control of the logged-in terminal to the user. Why doesn't this script work?


Solution

  • This is not the way to mix shell and expect code. You can't just invoke expect commands from the shell, you need to launch an expect process.

    Something like this:

    #! /bin/bash
    export PWD=abc
    expect <<'END_EXPECT'
        spawn kinit -f user@domain.com
        expect "Password for user@domain.com: "
        send "$env(PWD)\r"
        expect "this is some prompt you see after running kinit: edit this string"
        send " ssh -x user@dom.com\r"
        expect "this is the pattern for the remote prompt: edit this string"
        send "cd user/user\r"
        interact
    END_EXPECT