简体   繁体   中英

What's the best way to mix remote expect scripts and local bash commands?

I'm automating tasks on a local and remote machine (behind a firewall). Once I'm done with tasks on the remote machine, I'd like the script to return to executing commands on the local machine.

#!/usr/bin/expect -f
set timeout -1
spawn ssh username@host
expect "Password: "
send "mypassword\r"
expect "username@host:~$"
...do some stuff...
send "exit\r"
expect eof

[then, once on the local machine, change directories and do other things]

What's the best way to append bash commands? I suppose I could start with bash, call expect within it, then simply return to bash once expect is done.

Expect is based on Tcl , so it can run the same commands. But if your goal is to run bash commands, the best bet is to run them from bash as a separate script, exactly as you propose in your last sentence.

It really depends on what your idea of ...do some stuff... is. Here's an example of something I recently did from my OSX w/s to an AWS instance

 export all_status
 init_scripts=($(ssh -q me@somehost 'ls /etc/init.d'))
 for this_init in ${init_scripts[@]};do
    all_status="${all_status}"$'\n\n'"${this_init}"$'\n'"$(ssh -q somehost \'sudo /etc/init.d/${this_init} status\')"
 done
 echo "$all_status" > ~/somehost_StatusReport.txt
 unset all_status

Passing a command at the end of the ssh command will cause the command to be run on the remote host. Or you can scp a script to the remote host and run it with

 ssh somehost '/home/me/myscript'

I met this situation recently too. I make a shell supexpect.sh which could login and execute command automatically. It will return to your local shell at the end.

#!/usr/bin/expect
#Usage:supexpect <host ip> <ssh username> <ssh password> <commands>
set timeout 60
spawn ssh [lindex $argv 1]@[lindex $argv 0] [lindex $argv 3]
expect "yes/no" {
    send "yes\r"
    expect "*?assword" { send "[lindex $argv 2]\r" }
    } "*?assword" { send "[lindex $argv 2]\r" }
send "exit\r"
expect eof

To execute:

./supexpect.sh 10.89.114.132 username password "ls -a;pwd;your_stuff_on_remote_host"

Note: The prompt might need to adapt to your own system, and of course you need to pass execute permission to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM