预期脚本等待命令挂起

我有一个embedded到bash脚本中的期望脚本:

#! /bin/bash # this function runs a command like 'ssh' and provides the password function with_password { expect << END spawn $2 expect *assword:* send -- $1 interact wait END } # run "long_running_command" on the remote server with_password my_password "ssh my_user@some-server long_running_command" # rsync some data to the remote server with_password my_password "rsync /some/dir my_user@some-server:/remote/dir" # run some other random command with_password my_password "ssh my_user@some-server some_other_command" 

问题在于,有时脚本会在等待生成的命令时挂起。 如果我将wait命令离开expect脚本,命令将继续在远程服务器上运行,但bash脚本将继续运行,并且我无法知道何时完成。

为什么我的期望脚本似乎是随机悬挂?

expect here-doc中的interact命令是问题。 我需要等待EOF:

 #! /bin/bash # this function runs a command like 'ssh' and provides the password function with_password { expect << END set timeout 900 spawn $2 expect *assword:* send -- $1 expect EOF END } # run "long_running_command" on the remote server with_password my_password "ssh my_user@some-server long_running_command" # rsync some data to the remote server with_password my_password "rsync /some/dir my_user@some-server:/remote/dir" # run some other random command with_password my_password "ssh my_user@some-server some_other_command" 

当ssh / rsync命令在正确的时间(可能?)closuresinput时, interact命令有时似乎有效,但它不可靠。

如何使用ssh密码使用无密码login?

您可以使用ssh-keygen创build您的密钥,然后将您的公钥放在远端: ~/.ssh/authorized_keys

你甚至可以使用密码创build密钥(如果你想添加某种安全性),你可以使用ssh-agent bash在你的shell中加载你的密码,然后将你的密码保存在内存中,以便以后密码无误的login。

你错过了这里最后的doc分隔符。

 expect << END spawn $2 expect *assword:* send -- $1 interact wait END