I've been trying to capture the result of grep, logging into a remote machine, using ssl in Expect command. I read "except_out(buffer)" variable to contain the output of the spawned pr开发者_JAVA技巧ocess, but it seemed empty... A pointer'd be greatly appreciated!
#!/bin/bash
username=hoge
password=hoge
hostname=machine20
prompt="\[$username@$hostname ~\]$"
expect -c "
set timeout -1
spawn ssh -l $username $hostname
expect {
\"$username@$hostname's password:\" {
send \"$password\n\"
} \"Are you sure you want to continue connecting (yes/no)?\" {
send \"yes\n\"
expect \"$username@$hostname's password:\"
send \"$password\n\"
}
}
expect \"$prompt\"
sleep 2
expect \"$prompt\"
send \"ps axuw | grep java | grep -vc grep\n\"
expect -re -indices \"(.*)\"
send \"echo result : $expect_out(buffer)\"
expect version : 5.43.0
That code is a real mess. In particular, you've got interactions between bash and expect/tcl which are causing you trouble because when bash sees $var
for a variable it doesn't know, it replaces it with the empty string.
While you could update things by changing how you do quoting, it's actually better to rewrite things to actually use a direct expect/tcl script, like this:
#!/usr/bin/env expect
set username "hoge"
set password "hoge"
set hostname "machine20"
set prompt "\[$username@$hostname ~\]$"
set timeout -1
spawn ssh -l $username $hostname
expect {
"$username@$hostname's password:" {
send "$password\r"
}
"Are you sure you want to continue connecting (yes/no)?" {
send "yes\r"
exp_continue
}
}
# These next two lines look suspicious, BTW...
expect "$prompt"
sleep 2
expect "$prompt"
send "ps axuw | grep java | grep -vc grep\r"
expect -re -indices "(.*)"
send "echo result : $expect_out(buffer)"
However, I'd actually configure the remote host to use RSA keys for logins (indeed, I'd configure the remote host to only use them as they're much more attack-resistant than passwords and easier to manage too) and then just do this (with a local grep
so it doesn't need to be filtered):
ssh $username@$host ps axuw | grep java
精彩评论