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

时间:2012-12-10 13:02:48

标签: linux bash

  

可能重复:
  Using expect to pass a password to ssh

我希望与远程计算机建立ssh连接,而不是使用ssh命令以及机器地址和密码,我只想编写一个执行ssh命令到机器的小函数并在服务器之后输入传递问它。我可以编写ssh部分,但是当主机要求时,如何使脚本也进入传递?

2 个答案:

答案 0 :(得分:4)

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

#!/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"
        }
    }

答案 1 :(得分:1)

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

修改

#!/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

根据需要解决问题