【问题标题】:Bash, Expect : Execution of command after SSH is not workingBash,Expect:在 SSH 不工作后执行命令
【发布时间】:2018-04-25 11:50:16
【问题描述】:

我需要登录一个虚拟机并在那里执行一些命令。我已经完成了与同一主题相关的所有问题,但没有找到任何 EXPECT 解决方案。我正在使用 EXPECT,因为我需要在使用 SSH 时传递密码。

我在执行我的脚本时收到“命令未找到错误”,但手动运行,它工作正常。

#!/usr/bin/expect -f

set user [lindex $argv 0]
set to [lindex $argv 1]
set pass [lindex $argv 2]
set command [lindex $argv 3]
puts "$user, $to , $command and $pass ."
# connect via scp
spawn sudo ssh -t -t -v $user@$to << EOF
    ls
EOF

#######################
expect {
-re ".*es.*o.*" {
exp_send "yes\r"
exp_continue
}
-re ".*sword.*" {
exp_send $pass\n
}
}
interact

收到错误:

spawn sudo ssh -t -t -v username@server_ip

【问题讨论】:

    标签: bash shell expect


    【解决方案1】:

    您似乎正试图在“此处”文档中向远程系统发送命令:

    spawn sudo ssh -t -t -v $user@$to << EOF
        ls
    EOF
    

    相反,您应该在 'interact' 之前使用 'exp_send' 发送 ls 命令,即删除 'here' 文档:

    spawn sudo ssh -t -t -v $user@$to
    

    并将 ls 命令放在最后:

    expect {
        -re ".*es.*o.*" {
            exp_send "yes\r"
            exp_continue
        }
        -re ".*sword.*" {
            exp_send "$pass\r"
        }
    }
    exp_send "ls\r"
    interact
    

    编辑:

    啊,我误会了。如果您只想运行命令,则需要告诉另一端关闭连接:

    expect {
        -re ".*es.*o.*" {
            exp_send "yes\r"
            exp_continue
        }
        -re ".*sword.*" {
            exp_send "$pass\r"
        }
    }
    exp_send "ls\r"
    exp_send "exit\r"
    expect {
        eof {puts "Connection closed"}
        timeout {puts "Connection timed out"}
    }
    

    【讨论】:

    • 感谢杰夫的帮助。我根据您的建议更改了代码,但它仍然没有执行命令,它只是通过 SSH 连接到服务器并让终端对服务器保持打开状态。
    【解决方案2】:

    Expect(构建在 Tcl 之上)没有此处的文档。

    如果要远程执行命令然后结束 ssh 会话,请执行

    set command "ls -lrt"  ; # for example
    spawn sudo ssh -t -t -v $user@$to $command
    # ... log in logic
    expect eof
    

    【讨论】:

      猜你喜欢
      • 2014-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-29
      • 2014-01-28
      • 2019-11-27
      • 1970-01-01
      • 2011-06-14
      相关资源
      最近更新 更多