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
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" )