bash 使用“expect”命令将密码传递给 SSH 远程运行脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36630516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using 'expect' command to pass password to SSH running script remotely
提问by Acrid_Soul
I need to create a bash script that will remotely run another script on a batch of machines. To do so I am passing a script through SSH.
我需要创建一个 bash 脚本,该脚本将在一批机器上远程运行另一个脚本。为此,我通过 SSH 传递了一个脚本。
ssh -p$port root@$ip 'bash -s' < /path/to/script/test.sh
I thought it would use my RSA keys but I am getting error:
我以为它会使用我的 RSA 密钥,但出现错误:
"Enter password: ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)"
I tried using sshpass to no avail. So my next solution was using expect. I have never used expect before and I'm positive my syntax is way off.
我尝试使用 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
I have root access to all machines and ANY solution will do as long as the code remains within bash. Just keep in mind that this will be done in a loop with global variables ($spass, $ip, $port, etc) passed from a parent script.
我对所有机器都有 root 访问权限,只要代码保留在 bash 中,任何解决方案都可以。请记住,这将在具有从父脚本传递的全局变量($spass、$ip、$port 等)的循环中完成。
回答by Jakuje
You are doing it wrong in two means:
你在两个方面做错了:
If you want
expect
to interact withssh
, you need to startssh
fromexpect
script and not before.If you put the script (
/path/to/script/test.sh
) tostdin
ofssh
, you can't communicate with thessh
process any more.
如果要
expect
与 交互ssh
,则需要ssh
从expect
脚本开始,而不是从之前开始。如果将脚本 (
/path/to/script/test.sh
) 置于stdin
ofssh
,则无法再与该ssh
进程通信。
You should rather copy the script to remote host using scp and then run it.
您应该使用 scp 将脚本复制到远程主机,然后运行它。
Expect script might look like this:
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
回答by Shebin Jacob
#!/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