77140B
77140B

Reputation: 41

Expect and Bash script

I'm trying to do an expect script with a loop which tries to connect in ssh and see if it's possible (Good Password and reachable). I tried to put the result into a variable but only the end of the stdout is recorded and not all the stdout. How could I do?

result=$(
(/usr/bin/expect << EOF
    spawn ssh $username@$ip -o StrictHostKeyChecking=no
    set timeout 2
    expect ":"
    send -- "$password\r"
    expect ">"
    send -- "show clock\r"
    expect ">"
EOF
) 2>&1)

Thank you.

Upvotes: 0

Views: 648

Answers (3)

Luchostein
Luchostein

Reputation: 2444

Try using double quotes (") to capture the subshell's output. Maybe you're losing data because of parsing issues:

result="$( ... )"

Upvotes: -1

Nick Bull
Nick Bull

Reputation: 9876

If you're trying to automate sending a command to another server using ssh:

  • Generate an ssh key, instead of using passwords:

    ssh-keygen -t rsa -b 2048
    
  • Copy it to the server:

    ssh-copy-id id@server
    

Now you don't need to worry about the password. ssh keys act as passwords, and generally are much more secure. See these (SSH login without password, Why is using SSH key more secure than using passwords?) for more information about ssh keys.

Then you can just use this command - no expect needed, because you won't be asked for a password. It'll use your ssh key. Mine is located at ~/.ssh/id_rsa. So:

ssh id@server -i ~/.ssh/id_rsa "show clock;"
  • -i stands for the identity file, i.e., your ssh key file.

will send a command to the SSH server.

Altogether now:

ssh-keygen -t rsa -b 2048
ssh-copy-id id@server
ssh id@server -i ~/.ssh/id_rsa "show clock;"

Three commands, and you've done it!

Upvotes: 3

Jitesh Sojitra
Jitesh Sojitra

Reputation: 4043

Calling to expectscript from shell script:

expect "/copySSHKey.exp <machine> <password> </.ssh/id_rsa.pub path>"

Expect script:

#!/usr/bin/expect -f

set machine [lrange $argv 0 0]
set ip [lrange $argv 1 1]
set pass [lrange $argv 2 2]
set path [lrange $argv 3 3]

set timeout -1
spawn ssh-keygen -R ${machine}
spawn ssh-copy-id -i ${path} root@${machine}

match_max 100000

expect {

   sleep 10

   "password" {
            send -- "$pass\r"
            send -- "\r"
            sleep 1
            send_user " SSH key copied to $machine\n"
    }

    "$machine's" {
            send_user " SSH key copied to $machine\n"
    }

    "password:*" {
            send -- "$pass\r"
            send -- "\r"
            sleep 1
            send_user " SSH key copied to $machine\n"
    }

    "machine" {
            sleep 1
            send_user " SSH key copied to $machine\n"
    }
}

interact

Upvotes: 0

Related Questions