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

前端 未结 9 687
轮回少年
轮回少年 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:49

    Mixing Bash and Expect is not a good way to achieve the desired effect. I'd try to use only Expect:

    #!/usr/bin/expect
    eval spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no usr@$myhost.example.com
    
    # Use the correct prompt
    set prompt ":|#|\\\$"
    interact -o -nobuffer -re $prompt return
    send "my_password\r"
    interact -o -nobuffer -re $prompt return
    send "my_command1\r"
    interact -o -nobuffer -re $prompt return
    send "my_command2\r"
    interact
    

    Sample solution for bash could be:

    #!/bin/bash
    /usr/bin/expect -c 'expect "\n" { eval spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no usr@$myhost.example.com; interact }'
    

    This will wait for Enter and then return to (for a moment) the interactive session.

提交回复
热议问题