如何编写在第一个命令后输入密码的 bash 脚本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13801513/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:59:02  来源:igfitidea点击:

How to write bash script that enters password after the first command?

linuxbash

提问by erogol

Possible Duplicate:
Using expect to pass a password to ssh

可能的重复:
使用 expect 将密码传递给 ssh

I want to have ssh connection to a remote machine and instead of using ssh command along with the machine address and password, I just want to write a little function that executes the ssh command to the machine and enters the pass after the server asks it. I can write the ssh part but how can I make the script that enters also the pass when the host ask for it?

我想与远程机器建立 ssh 连接,而不是使用 ssh 命令以及机器地址和密码,我只想编写一个小函数,该函数对机器执行 ssh 命令并在服务器询问后输入通行证。我可以写ssh部分,但是当主机要求它时,我如何制作进入的脚本?

回答by louxiu

You may use expectscript. You can pass arguments from cmd line. Sample code I write:

您可以使用expect脚本。您可以从 cmd 行传递参数。我写的示例代码:

#!/usr/bin/expect

set timeout 100
set host [lindex $argv 0]
set username [lindex $argv 1]
set password [lindex $argv 2]
set command [lindex $argv 3]

spawn ssh $username@$host $command
#puts $command
expect {
    "(yes/no)?"
        {
            send "yes\n"
            expect "*assword:" { send "$password\n"}
        }
    "*assword:"
        {
            send "$password\n"
        }
    }

回答by Pepelac

You can use Expect tool
It's exactly what you need:

您可以使用 它正是您所需要的:Expect tool

EDIT

编辑

#!/usr/bin/expect
set timeout 60
set user "yourName"
set machine "nameOfYourMachine"
set password "yourPassword"
set command "command that you want execute via ssh"
spawn ssh $user@$machine 
while {1} {
expect {
      eof                          {break}
      "The authenticity of host"   {send "yes\r"}
      "password:"                  {send "$password\r"}
      "*\]"                        {send "exit\r"}
      "bash"                        {send "$command"}
}
}
wait
close $spawn_id

Just workaround it as you need

只需根据需要解决它