期望SSH上的命令不同步

时间:2015-03-10 18:17:24

标签: unix ssh expect

我创建了一个脚本,我需要使用SSH在远程终端上运行一些命令。所以我使用了expect语句,但问题是,假设我必须在远程终端上运行5个语句,然后6次,大约3-4次,这5个命令不同步,即命令没有以正确的顺序执行,不正确的方式,即首先应该完成第一个命令,然后应该运行第二个命令。 我试图设置超时5或甚至10但它没有帮助。我试过睡2或4,但它也没有帮助。这是我创建的脚本和输出。请帮我。感谢。

脚本:

do some work on current shell
#echo $name 
## ssh part of script starts

/usr/bin/expect<<EXEOF

set timeout -1
match_max 100000
spawn ssh "myuser\@IP_ADDRESS"
expect "*assword:*"
send -- "mypassword\r"
send -- "\r"
#expect -re "(%|*>|#|\\$)"
expect "*>"
#expect "*OFR:offline-ure>"   #actual prompt of ssh terminal
send -- "\r"
set timeout 20
#sleep 1
send -- "tcsh\r"
send -- "\r"
set timeout 2
expect -re "(%|>|#|\\$)"
#set timeout 10
send -- "cd /home/myuser/cap/\r"
send -- "\r"
set timeout 4
expect -re "(%|>|#|\\$)"
send -- "source cap.env\r"
send -- "\r"
set timeout 10
send -- "cd /home/myuser/bin/\r"
set timeout 5
expect -re "(%|>|#|\\$)"
send -- "$myCommand\r"
#set timeout 50
#sleep 40
send -- "exit\r"
expect -re "(%|>|#|\\$)"
send -- "exit\r"
expect eof

EXEOF
echo "end of ssh script"
some task after ssh part of script

当我运行它时,我会看到以下输出:

spawn ssh myuser@IP_ADDRESS
myuser@XX.XX.XX.XXX's password:
Last login: Tue Mar 10 07:56:19 2015 from XX.XX.XX.XX

OFR:offline-ure> tcsh   (see here all commands are sent together)

source ccap.env

cd /home/myuser/bin/
mycommand_String_value
exit
exit
[sncpuser@offline-ure ~]$
[sncpuser@offline-ure ~]$ source ccap.env
ccap.env: No such file or directory.
[sncpuser@offline-ure ~]$
[sncpuser@offline-ure ~]$ cd /home/myuser/bin/
[sncpuser@offline-ure bin]$ mycommand_string_value
some output of my command
[sncpuser@offline-ure bin]$ exit
exit
OFR:offline-ure>
OFR:offline-ure> cd /home/myuser/cap/     (this was second command)
OFR:offline-ure> exit
Connection to xx.xx.xx.xxx closed.
end of ssh script

请注意,在输出中,我需要执行SSH终端的所有命令都是同时发送的,因此无法以正确的顺序正常运行。 请建议我该如何解决这个问题。提前谢谢。

1 个答案:

答案 0 :(得分:1)

这对于评论来说太长了,否则它本来就是一个,但你似乎让自己的生活变得困难。 expect脚本容易出错,因此您希望将它们尽可能地降低。

为什么不:

ssh foo ". /home/myusr/cap/env ; /home/myusr/cap/bin/cmd"

只需使用expect来填写用户名/密码位吗?

或者更好的是,使用公钥身份验证并且根本不执行用户名/密码,并完全删除expect

您在评论中询问如何将多个命令传递给ssh。试试这个:

amb@nimrod-ubuntu:~/so$ ssh 192.200.0.1 'pwd ; ls | wc -l ; cd .. ; pwd ; ls | wc -l'
amb@192.200.0.1's password:
/home/amb
132
/home
2
默认情况下,

ssh将使用您的登录shell。如果你真的需要使用tcsh并且那不是你的登录shell,这是一种方法:

ssh 192.200.0.1 '/bin/sh -c "pwd ; ls | wc -l ; cd .. ; pwd ; ls | wc -l"'

另一种方法是将脚本文件放在远程系统上,例如在/home/myuser/cap/bin/dostuff中写道:

#!/bin/tcsh
cd /home/myuser/cap/
source cap.env
cd /home/myuser/bin/
# next line will run the file given as the first parameter
$1
exit

然后将其调用为:

ssh 192.200.0.1 /home/myuser/cap/bin/dostuff /path/to/file/to/run

我怀疑实际问题与假终端的分配有关。您可能希望将-t-T选项用于ssh