Using 'expect' command to pass password to SSH running script remotely

15,576

You are doing it wrong in two means:

  1. If you want expect to interact with ssh, you need to start ssh from expect script and not before.

  2. If you put the script (/path/to/script/test.sh) to stdin of ssh, you can't communicate with the ssh process any more.

You should rather copy the script to remote host using scp and then run it.

Expect script might look like this:

/usr/bin/expect <<EOF
spawn ssh -p$port root@$ip
expect "password"
send "$Spass\r"
expect "$ "
send "/path/to/script/on/remote/server/test.sh\r"
expect "$ "
interact
EOF
Share:
15,576
Acrid_Soul
Author by

Acrid_Soul

Updated on August 21, 2022

Comments

  • Acrid_Soul
    Acrid_Soul over 1 year

    I need to create a bash script that will remotely run another script on a batch of machines. To do so I am passing a script through SSH.

    ssh -p$port root@$ip 'bash -s' < /path/to/script/test.sh
    

    I thought it would use my RSA keys but I am getting error:

    "Enter password: ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)"
    

    I tried using sshpass to no avail. So my next solution was using expect. I have never used expect before and I'm positive my syntax is way off.

    ssh -p$port root@$ip 'bash -s' < /path/to/script/test.sh
    /usr/bin/expect <<EOD
    expect "password"
    send "$spass\n"
    send "\n"
    EOD
    

    I have root access to all machines and ANY solution will do as long as the code remains within bash. Just keep in mind that this will be done in a loop with global variables ($spass, $ip, $port, etc) passed from a parent script.

  • szpal
    szpal about 8 years
    missing interact and EOF
  • Jakuje
    Jakuje about 8 years
    @szpal Thanks. Fixed now.
  • Acrid_Soul
    Acrid_Soul about 8 years
    Thanks, that certainly did the trick. Is there a way to make it wait for the other script to finish before it moves on? I usually use source, will that play nice with expect?
  • Jakuje
    Jakuje about 8 years
    I have no idea what you mean. I would consult with manual page, understand what this code snippet do and then try to compose another question, if there will be something unclear.
  • Saurabh Bhandari
    Saurabh Bhandari almost 7 years
    Please provide description of your answer
  • Admin
    Admin almost 7 years
    Expect tool can be used for automating interactive applications such as ssh,telnet, ftp, passwd, fsck, rlogin, tip, etc. Try some examples from below url. thegeekstuff.com/2010/10/expect-examples