【问题标题】:Using 'expect' command to pass password to SSH running script remotely使用“expect”命令将密码远程传递给 SSH 运行脚本
【发布时间】:2023-03-17 02:15:01
【问题描述】:

我需要创建一个 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,而且我很肯定我的语法已经过时了。

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

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

【问题讨论】:

  • 您的 SSH 公钥是否在每台机器的根目录的 .ssh/authorized_keys 文件中?我认为在这里拍摄的最佳情况是弄清楚为什么在尝试使用密钥对进行 ssh 身份验证时会遇到问题。
  • 您可以尝试手动与ssh -v {port} root@{ip} 连接,以更好地了解正在发生的事情。
  • 修复关键问题是一个比破解密码提示更好的解决方案
  • @Jnevill 和 Etan 我同意这两个帐户。 SSH 可以在除这里以外的所有其他地方使用,我终其一生都无法弄清楚原因。迈克感谢您的提示。明天上班我得试试看。

标签: linux bash ssh expect


【解决方案1】:

你做错了有两种方式:

  1. 如果您希望expectssh 交互,您需要从expect 脚本而不是之前启动ssh

  2. 如果把脚本(/path/to/script/test.sh)放到sshstdin,就不能再和ssh进程通信了。

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

预期脚本可能如下所示:

/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

【讨论】:

  • 缺少interactEOF
  • @szpal 谢谢。现已修复。
  • 谢谢,这确实成功了。有没有办法让它在继续之前等待其他脚本完成?我通常使用source,它会和expect很好吗?
  • 我不明白你的意思。我会查阅手册页,了解这段代码 sn-p 的作用,然后尝试编写另一个问题,如果有不清楚的地方。
【解决方案2】:
    #!/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

【讨论】:

  • 请描述你的答案
  • Expect 工具可用于自动化交互式应用程序,例如 ssh、telnet、ftp、passwd、fsck、rlogin、tip 等。从下面的 url 中尝试一些示例。 thegeekstuff.com/2010/10/expect-examples
猜你喜欢
  • 1970-01-01
  • 2011-06-14
  • 2015-08-27
  • 2015-07-05
  • 2017-08-02
  • 2012-07-18
  • 1970-01-01
相关资源
最近更新 更多