使用'expect'命令远程将密码传递给SSH运行脚本



我需要创建一个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 "$spassn"
send "n"
EOD

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

你做错了两种方式:

  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 "$Spassr"
expect "$ "
send "/path/to/script/on/remote/server/test.shr"
expect "$ "
interact
EOF
    #!/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 "urpasswordn"
    #add commands to be executed. Also possible to execute bash scripts
    expect "$ " {send "pwdn"} # bash command
    expect "$ " {send "cd mytestn"}
    expect "$ " {send "./first.shn"} # bash scripts
    expect "$ " {send "exitn"}
    interact

最新更新