使用Expect通过SSH管理计算机,但不完成所有任务

*请不要堆积并告诉我只使用SSH密钥。如果它让你觉得这就是我这样做的方式,假装我试图telnet in。 :-) * 我正在使用expect脚本在我控制的一组服务器上通过ssh运行一些例程命令。脚本应该在每台机器上运行一组命令(例如svn update~ / folderx r“)。我当前的脚本会执行我想要它做的所有事情...有时候。有时它会在完成一个ssh连接之前退出ssh连接最后几个命令。 关于如何在所有命令完成之前保持连接的任何想法?下面的代码成功登录,成功运行前两个命令(ap-get update和其中一个svn更新),然后断开连接。
#!/usr/bin/expect -f

spawn ssh username@ipaddress
set timeout -1
expect "Are you sure you want to continue connecting" {send "yesr"; exp_continue} "password:" {send "*******r"; exp_continue
    } "username@machine" {send "sudo apt-get updater"}
expect "password" {send "*******r"; exp_continue} "username@machine" {send "sudo svn update ~/folder1r"}
expect "password" {send "*******r"; exp_continue} "username@machine" {send "sudo svn update ~/folder2r"}
expect "password" {send "*******r"; exp_continue} "username@machine" {send "sudo svn update ~/folder3r"}
expect "password" {send "*******r"; exp_continue} "username@machine" {send "sudo rebootr"}
close
    
已邀请:
使用Expect通常是做这种事情的错误方法。 正确的方法是设置ssh密钥,以便您可以在远程计算机上ssh并运行命令而无需提供密码。以下是如何做到这一点:
0. Create public/private key pair on local machine.
   (Only needs to be done once on local machine for all remote machines.)
   Go to the ~/.ssh directory on your local machine and do this:
   % ssh-keygen -t rsa
1. Copy the public key to the remote machine:
   % scp ~/.ssh/id_rsa.pub you@foo.com:.
2. Append that key to the authorized_keys file on the remote machine:
   % ssh you@foo.com 'cat id_rsa.pub >> .ssh/authorized_keys; /bin/rm id_rsa.pub'
3. Finally, in case it doesn't work, check permissions, which must be just so: 
   (or maybe it's just that they can't be group/world writeable)
   % cd ~; ls -ld . .ssh .ssh/authorized_keys
     drwxr-xr-x  .
     drwxr-xr-x  .ssh
     -rw-r--r--  .ssh/authorized_keys
这是一个完成上述操作的脚本: http://jakehofman.com/code/sshkey 然后,您可以在远程计算机上运行命令,如下所示:
ssh alice@remote.com ./foo args
但是,要使用sudo在远程计算机上运行命令,可能是另一个故事。 希望其他人可以对此提出异议。 但作为第一步,您应该避免Expect进行初始登录。     
事实证明它之前退出的原因是我匹配的提示模式不仅匹配了提示,还匹配了我正在运行的svn命令的一些输出。我只匹配提示模式的“用户名”部分(提示形式为“username @ machine:〜$”)。一旦我将脚本更改为仅匹配“username @”,它就会按预期开始工作。 附: dreeves链接到上面的ssh脚本非常好用。     

要回复问题请先登录注册