使用 'expect' 命令将密码远程传递给 SSH 运行 脚本
Using 'expect' command to pass password to SSH running script remotely
我需要创建一个 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
我拥有对所有机器的 root 访问权限,只要代码保留在 bash 内,任何解决方案都可以。请记住,这将在一个循环中完成,其中包含从父脚本传递的全局变量($spass、$ip、$port 等)。
你在两个方面做错了:
如果您希望 expect
与 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
我需要创建一个 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
我拥有对所有机器的 root 访问权限,只要代码保留在 bash 内,任何解决方案都可以。请记住,这将在一个循环中完成,其中包含从父脚本传递的全局变量($spass、$ip、$port 等)。
你在两个方面做错了:
如果您希望
expect
与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