【问题标题】:How to write bash script that enters password after the first command? [duplicate]如何编写在第一个命令后输入密码的bash脚本? [复制]
【发布时间】:2012-12-10 13:02:48
【问题描述】:

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

我想ssh连接到远程机器,而不是使用ssh命令以及机器地址和密码,我只想写一个小函数,对机器执行ssh命令并在服务器之后输入pass问它。我可以写 ssh 部分,但是当主持人要求时,我怎样才能使脚本也进入通行证?

【问题讨论】:

  • 不要使用随机存储在文本文件中的密码!请改用 ssh 密钥。
  • @gniourf_gniourf 这仅适用于登录密码,不适用于远程命令的密码提示。

标签: linux bash


【解决方案1】:

您可以使用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"
        }
    }

【讨论】:

    【解决方案2】:

    您可以使用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
    

    根据需要解决它

    【讨论】:

    • @Erogol 写 #!/usr/bin/expect 作为第一行
    • 仍然无法正常工作并产生 spawn:找不到命令,而 {1}{:找不到命令无法读取文件“{”:没有这样的文件或目录没有找到命令“eof”,是吗?意思是:来自包'eog'(主)的命令'eog'来自包'keyboards-rg'(universe)的命令'eox':找不到命令*ssword :: command not found
    • @Erogol 我编辑我的帖子现在检查它
    猜你喜欢
    • 1970-01-01
    • 2020-02-10
    • 1970-01-01
    • 2013-12-25
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多