Use Expect in a Bash script to provide a password to an SSH command

前端 未结 9 689
轮回少年
轮回少年 2020-11-22 06:23

I\'m trying to use Expect in a Bash script to provide the SSH password. Providing the password works, but I don\'t end up in the SSH session as I should. It goes back strait

相关标签:
9条回答
  • 2020-11-22 06:59

    Add the 'interact' Expect command just before your EOD:

    #!/bin/bash
    
    read -s PWD
    
    /usr/bin/expect <<EOD
    spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no usr@$myhost.example.com
    expect "password"
    send "$PWD\n"
    interact
    EOD
    echo "you're out"
    

    This should let you interact with the remote machine until you log out. Then you'll be back in Bash.

    0 讨论(0)
  • 2020-11-22 06:59

    After looking for an answer for the question for months, I finally find a really best solution: writing a simple script.

    #!/usr/bin/expect
    
    set timeout 20
    
    set cmd [lrange $argv 1 end]
    set password [lindex $argv 0]
    
    eval spawn $cmd
    expect "Password:"
    send "$password\r";
    interact
    

    Put it to /usr/bin/exp, then you can use:

    • exp <password> ssh <anything>
    • exp <password> scp <anysrc> <anydst>

    Done!

    0 讨论(0)
  • 2020-11-22 07:01

    Also make sure to use

    send -- "$PWD\r"
    

    instead, as passwords starting with a dash (-) will fail otherwise.

    The above won't interpret a string starting with a dash as an option to the send command.

    0 讨论(0)
提交回复
热议问题