2

I want to pass the $SPACE variable into an Expect script and get the output and again pass into the shell script.

#!/bin/bash -x

    SPACE=$(df -h | awk '{ print $5 }' | grep -v Use |sort -n |tail -1 | cut -d % -f1)
    #set user "root"
    #set ip "192\.168\.53\.197"
    #echo $SPACE

    expect<<EOF

    spawn ssh "root\@192\.168\.53\.197"

    expect "Password:"

    send "Karvy123$\r";

    expect "prompt"

    send "$SPACE\r";

    expect "prompt"

    EOF
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user2932003
  • 171
  • 2
  • 4
  • 14

1 Answers1

8

Oh, I see. You want $SPACE to hold the COMMAND, not the VALUE. This construct will execute the command and save the output in the variable: x=$(cmd arg arg). So you are finding the space used on your local host and sending that value to the remote host.

You need something like this:

#!/bin/bash
export cmd="df -h | awk '{ print \$5 }' | grep -v Use |sort -n |tail -1 | cut -d % -f1"
remote_usage=$(
    expect <<'EOF'
    log_user 0
    spawn -noecho ssh "root@192.168.53.197"
    expect "Password:"
    send "*****\r"
    expect "prompt"
    send "$env(cmd)\r"
    expect -re {(?n)^(\d+)$.*prompt}
    send_user "$expect_out(1,string)\n"
    send "exit\r"
    expect eof
EOF
)
echo "disk usage on remote host: $remote_usage"

However, you don't have to do any of that. Set up SSH keys (with ssh-keygen and ssh-copy-id) and do

remote_usage=$( ssh root@192.168.53.197 sh -c "df -h | awk '{ print \$5 }' | grep -v Use |sort -n |tail -1 | cut -d % -f1" )
user2932003
  • 171
  • 2
  • 4
  • 14
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • thanks for ur reply...@glenn I'm getting following error--> can't read "expect_out(buffer)": no such variable while executing "send_user "$expect_out(buffer)\n"" – user2932003 Feb 21 '14 at 14:28
  • #!/bin/bash export cmd="df -h | awk '{ print \$5 }' | grep -v Use |sort -n |tail -1 | cut -d % -f1" remote_usage=$( expect <<'EOF' log_user 0 spawn -noecho ssh "root@192.168.53.197" expect "Password:" send "Karvy123$\r" expect "prompt" send "$env(cmd)\r" expect -re {(?n)^(\d+)$.*prompt} set results $expect_out(buffer) send "exit\r" expect eof EOF ) – user2932003 Feb 24 '14 at 19:22
  • use `expect_out(1,string)` instead of `expect_out(buffer)` -- the former will just be the digits output by the command; the latter will include the command, the prompt, etc – glenn jackman Feb 24 '14 at 19:42
  • i'm using same code which you provide after that same error---> can't read "expect_out(1,string)": no such variable while executing "send_user "$expect_out(1,string)\n"" – user2932003 Feb 25 '14 at 03:55