我需要创build一个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无济于事。 所以我的下一个解决scheme是使用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权限访问所有机器,任何解决scheme只要代码仍然在bash中就可以。 只要记住,这将在一个从父脚本传递的全局variables($ spass,$ ip,$ port等)的循环中完成。
你用两种方法做错了:
如果你希望与ssh
交互,你需要从expect
脚本启动ssh
,而不是之前。
如果将脚本( /path/to/script/test.sh
)放到ssh
stdin
中,就不能再与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
#!/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