Search code examples
linuxshellsshcygwinexpect

Using ssh through an expect script on cygwin


I'm trying to execute commands remotely over ssh using an expect script that will log in with a password. So far I have the following script (details changed of course):

#!/usr/bin/expect

spawn ssh [email protected]
expect "password:"
send "psw123\r"
expect "$"
send "mkdir pswdtest\r"

I name this script testpswd.sh and then runchmod +x testpswd.sh, d2u testpswd.sh and ./testpswd.sh.

Apparently the script manages to login because I get the Last login:... prompt. However, after this the script seems to wait for a bit and then exit back out of ssh, without making a directory called pswdtest (as I can check afterwards).

I have tried looking up tutorials etc and changing the script above in all ways I could think of, e.g. expect "user1@cpu3:~$"instead of expect "$" and so on.

I'm running windows and use cygwin (hence the d2u), and the network I'm logging into uses Linux.

Any ideas?


Solution

  • While developing an expect script, always add exp_internal 1 at the top of the script: expect will show you what it's matching (or not).

    Perhaps you could match the prompt with this: expect -re {\$\s*$}

    After you send something, you should expect something

    exp_internal 1
    set prompt {\$\s*$}
    spawn ssh [email protected]
    expect "password:"
    send "psw123\r"
    expect -re $prompt
    send "mkdir pswdtest\r"
    expect -re $prompt
    send "exit\r"
    expect eof