[英]How to write expect snippet in bash script to run remote command?
Currently I am running this script to print directories on a remote box but I am not sure this code is working. 目前,我正在运行此脚本以在远程机器上打印目录,但是我不确定此代码是否有效。
#!/bin/bash
PWD="test123"
ip="10.9.8.38"
user=$1
/usr/bin/expect <<EOD
spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no $user@$ip df -h
expect "*assword:"
send "$PWD\n"
interact
EOD
expect
spawns a new sub-shell, hence your local bash
variables lose their scope, one way to achieve this is to export
your variables to make it available for the sub-shell. Expect expect
产生一个新的子shell,因此您的本地bash
变量会失去作用域,一种实现方法是export
变量以使其可用于子shell。 Use the Tcl env
built-in to import such variables in your script. 使用内置的Tcl env
在脚本中导入此类变量。
#!/bin/bash
export pwdir="test123"
export ip="10.9.8.38"
export user=$1
/usr/bin/expect <<EOD
spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no "$env(user)"@"$env(ip)" df -h
expect "*assword:"
send "$env(pwdir)\n"
interact
EOD
(Or) If you are not interested in using an expect
script directly with a #!/usr/bin/expect
she-bang, you can do something like (或者)如果您不expect
直接在#!/usr/bin/expect
she-bang中使用expect
脚本,则可以执行以下操作
#!/usr/bin/expect
set pwdir [lindex $argv 0];
set ip [lindex $argv 1];
set user [lindex $argv 2];
spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no $user@$ip df -h
expect "*assword:"
send "$pwdir\n"
interact
and run the script as 并运行脚本为
./script.exp "test123" "10.9.8.38" "johndoe"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.