使用expect登录后无法执行命令

时间:2015-06-28 11:08:34

标签: bash ssh expect

我有以下脚本:

#!/usr/bin/expect -f

    set timeout 60

    spawn ssh -X user@login.domain.co.uk

    expect "Password:"
    # Send the password, and then wait for a shell prompt.
    send "password\r"
    exp_continue
    expect "user*"
    send "ls -la\r"

然而,我得到以下内容:

Password: command returned bad code: -101
    while executing
"exp_continue"
    (file "./hpclogin.sh" line 10)

如果我删除exp_continue

#!/usr/bin/expect -f

    set timeout 60

    spawn ssh -X user@login.domain.co.uk

    expect "Password:"
    # Send the password, and then wait for a shell prompt.
    send "password\r"
    expect "user*"
    send "ls -la\r"

我可以成功登录,但ls -la命令无法执行。我的程序的流量控制有问题吗?

1 个答案:

答案 0 :(得分:2)

exp_continue仅在expect块内有用。例如:

spawn ssh -X user@example.com
expect {
    "continue connecting (yes/no)? " {
        send "yes\r"
        exp_continue"
    }
    "Password:"
}
send "password\r"

我认为您没有看到ls输出,因为您不希望在发送之后看到任何内容。根据您的工作流程,这里有两个想法:

  1. 将命令添加为ssh

    的参数
    spawn ssh -X user@example.com ls -la
    expect {
        "continue connecting (yes/no)? " {
            send "yes\r"
            exp_continue"
        }
        "Password:"
    }
    send "password\r"
    expect eof
    
  2. 期望在命令后出现提示,然后注销

    spawn ssh -X user@example.com
    expect {
        "continue connecting (yes/no)? " {
            send "yes\r"
            exp_continue"
        }
        "Password:"
    }
    send "password\r"
    expect $theprompt
    send "ls -la\r"
    expect $theprompt
    send "exit\r"
    expect eof
    
  3. 当然,使用ssh键会更简单:

    ssh-keygen
    ssh-copy-id user@example.com
    ssh -X user@example.com ls -la
    
相关问题