bash - 期望登录后无法执行命令

标签 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命令。我的程序的流程控制有问题吗?

最佳答案

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

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

我认为您没有看到ls输出,因为您不希望在发送后看到任何东西。根据您的工作流程,这里有两个想法:
  • 将命令添加为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
    
  • 在命令后会出现提示,然后注销
    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
    

  • 当然,使用ssh键会更简单:
    ssh-keygen
    ssh-copy-id user@example.com
    ssh -X user@example.com ls -la
    

    关于bash - 期望登录后无法执行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31099103/

    相关文章:

    linux - 休息时的 at 命令可以简化吗?

    bash - 在脚本内的ssh上捕获bash脚本的输出

    shell - 无法解析 GitLab 的主机名

    expect - 使用 Expect 脚本将 IP 地址提取到变量

    bash - 捕获期望的 ssh 输出到变量

    bash - 如何获取匹配的行号?

    bash - 删除模式之间的空格

    linux - 在 Linux VM 中退出 bash 模式

    Powershell 豪华 ssh : How to store results of Invoke-SSHCommand?

    shell - 如何让expect -c在单行而不是脚本中工作