简体   繁体   English

混合远程期望脚本和本地bash命令的最佳方法是什么?

[英]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? 追加bash命令的最佳方法是什么? I suppose I could start with bash, call expect within it, then simply return to bash once expect is done. 我想我可以从bash开始,在其中调用Expect,然后在完成期望后简单地返回bash。

Expect is based on Tcl , so it can run the same commands. Expect基于Tcl ,因此它可以运行相同的命令。 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. 但是,如果您的目标是运行bash命令,那么最好的选择就是从bash作为单独的脚本运行它们,就像您在上一句中建议的那样。

It really depends on what your idea of ...do some stuff... is. 这实际上取决于您对...do some stuff...想法。 Here's an example of something I recently did from my OSX w/s to an AWS instance 这是我最近从OSX w / s到AWS实例所做的一些示例

 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. ssh命令末尾传递命令将导致该命令在远程主机上运行。 Or you can scp a script to the remote host and run it with 或者,您可以将脚本scp到远程主机,然后使用

 ssh somehost '/home/me/myscript'

I met this situation recently too. 我最近也遇到过这种情况。 I make a shell supexpect.sh which could login and execute command automatically. 我制作了一个shell supexpect.sh,它可以自动登录并执行命令。 It will return to your local shell at the end. 它将在最后返回您的本地shell。

#!/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. 注意:提示可能需要适应您自己的系统,当然您需要将执行权限传递给它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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