使用“expect”命令远程运行脚本并传递密码给SSH

5

我需要创建一个 bash 脚本,可以远程在一批机器上运行另一个脚本。为了实现这个目的,我通过 SSH 传递了一个脚本。

ssh -p$port root@$ip 'bash -s' < /path/to/script/test.sh

我以为它会使用我的RSA密钥,但是我收到了错误信息:
"Enter password: ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)"

我尝试使用sshpass,但无效。所以我的下一个解决方案是使用expect。我以前从未使用过expect,我确定我的语法有很大的偏差。

ssh -p$port root@$ip 'bash -s' < /path/to/script/test.sh
/usr/bin/expect <<EOD
expect "password"
send "$spass\n"
send "\n"
EOD

我可以访问所有机器的根权限,只要代码仍在bash中,任何解决方案都可以。请记住,这将在循环中完成,并传递全局变量($ spass,$ ip,$ port等)从父脚本。


1
你的SSH公钥是否在每台机器的root用户的.ssh/authorized_keys文件中?我认为最好的情况是找出为什么在尝试使用密钥对进行ssh身份验证时会遇到问题。 - JNevill
你可以尝试手动连接 ssh -v {port} root@{ip} 以更好地了解正在发生的情况。 - Mike
2
解决关键问题比绕过密码提示要好得多。 - Etan Reisner
@Jnevill 和 Etan 我在两个方面都同意。SSH 在其他地方都可以使用,就是在这里不行,我真的弄不明白为什么。Mike,谢谢你的提示。我明天上班后会尝试一下。 - Acrid_Soul
2个回答

4
你有两种错误做法:
  1. 如果你希望expectssh交互,你需要从expect脚本启动ssh,而不是在之前。

  2. 如果你把脚本(/path/to/script/test.sh)作为stdin传递给ssh,就不能再与ssh进程通信了。

你应该使用scp将脚本复制到远程主机上,然后运行它。

Expect脚本可能如下所示:

/usr/bin/expect <<EOF
spawn ssh -p$port root@$ip
expect "password"
send "$Spass\r"
expect "$ "
send "/path/to/script/on/remote/server/test.sh\r"
expect "$ "
interact
EOF

1
缺少 interactEOF - szpal
@szpal 谢谢。现在已经修复了。 - Jakuje
谢谢,那确实解决了问题。有没有办法让它在继续之前等待另一个脚本完成?我通常使用source,这样做会对expect友好吗? - Acrid_Soul
我不知道你的意思。我会参考手册页,理解这段代码片段的含义,然后再提出另一个问题,如果还有什么不清楚的地方。 - Jakuje

0
    #!/usr/bin/expect
    #Replace with remote username and remote ipaddress
    spawn /usr/bin/ssh -o StrictHostKeyChecking=no username@IPAddress
    #Replace with remote username and remote ipaddress
    expect "username@IPAddress's password: "
    #Provide remote system password
    send "urpassword\n"
    #add commands to be executed. Also possible to execute bash scripts
    expect "$ " {send "pwd\n"} # bash command
    expect "$ " {send "cd mytest\n"}
    expect "$ " {send "./first.sh\n"} # bash scripts
    expect "$ " {send "exit\n"}
    interact

请提供您答案的描述 - Saurabh Bhandari
Expect 工具可用于自动化交互式应用程序,例如 ssh、telnet、ftp、passwd、fsck、rlogin、tip 等。请尝试以下 URL 中的一些示例。 http://www.thegeekstuff.com/2010/10/expect-examples - Shebin Jacob

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接