linux - 从 Expect 捕获返回码

标签 linux shell powershell ssh expect

尝试从 linux 机器上执行 expect 脚本以捕获放置在 windows 机器上的 powershell 脚本的返回代码。

运行.sh

expect ssh.exp $USER $HOST $PASSWD "PowerShell -NonInteractive -NoProfile -Command test.ps1"

ssh.exp

#!/usr/bin/expect

set user [lindex $argv 0];
set host [lindex $argv 1];
set pass [lindex $argv 2];
set cmd [lindex $argv 3];


spawn ssh -C -oStrictHostKeyChecking=no -oCheckHostIP=no $user@$host

expect "password:"
send "$pass\r"

expect -re ".*?>"
send "$cmd\r"

expect -re ".*?>"
send "exit\r"

interact

test.ps1

function test {
    $i = 1
    if ($i -eq 2) {
        Write-Host "success"
    }
    else {
        Write-Host "failed"
        $host.SetShouldExit(5)
        exit
    }
}
Write-Host "Exiting with code 5"
test

预期返回代码:5

最佳答案

需要查看退出状态:

send "$cmd\r"
expect -re ".*?>"

send "echo \$lastexitcode\r"
expect -re {\y(\d+)\y.*>}
set exit_status $expect_out(1,string)

send "exit\r"
expect eof

关于linux - 从 Expect 捕获返回码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47159725/

相关文章:

linux - 向 bash 数组添加值

python 在 csv 中找到重复项并删除最旧的

linux - 在 Linux 中增加套接字缓冲区大小有什么副作用吗?

c - 使用 C/C++ 的 LibXml2

powershell - 提取两个字符之间的所有字符串powershell

linux - 抑制详细并仅显示 curl 输出命令

regex - 如何使用sed分割字符串?

linux - 是否存在任何神奇的 "stdout"文件?

Powershell PSSession 变量上下文

javascript - (PERCY) 警告 : skipping visual tests. 未提供 PERCY_TOKEN