为什么Node.js执行bash时Expect不能在while循环中工作?

问题描述 投票:0回答:1

我正在使用node.js调用我的expect bash文件,但是当node.js执行bash时,Expect无法在while循环中工作。

这是我的node.js代码:

app.post("/sparknode/ssh/setssh", cors(), (req, res) => {
    shell.exec("expect /root/suanchang/set-ssh.sh", { async: false });
    res.send("success");
});

这是我用 tcl 编写的期望 bash 代码:(tcl-ssh.sh)

#!/bin/expect

set file "/usr/local/spark/conf/hosts.txt"
set fp [open $file r]

spawn bash -c "ssh-keygen -t rsa"
expect {
    "Overwrite (y/n)?" {
        send "y\r"
        exp_continue
    }
    "Enter file in which to save the key (/root/.ssh/id_rsa):" {
        send "\r"
        exp_continue
    }
    "Enter passphrase (empty for no passphrase):" {
        send "\r"
        exp_continue
    }
    "Enter same passphrase again:" {
        send "\r";
        exp_continue
    }
}
# exec touch /root/.ssh/a.txt
while {[gets $fp line]!=-1} {
     lassign [split $line " "] ip username password
     spawn bash -c "ssh-copy-id -f $username@$ip"
     expect {
        timeout { send_user "\nFailed to get password prompt\n"; exit 1 }

        "*re you sure you want to continue connecting" {
            exec touch /root/.ssh/1-arrived
            send "yes\r"
            exp_continue
        }
        "*assword*" {
            exec touch /root/.ssh/2-arrived
            send  "$password\r"
            exp_continue
        }
    }

}

我在expect块中添加了两个触摸命令,但它们都不起作用。戏剧性的是,如果我直接在 Node.js 服务器中运行

expect tcl-ssh.sh
,我得到了正确的结果。

我尝试用touch命令替换while循环中的expect块,效果也很好。以下是我的试用。

不是在 while --- Expect --- node.js exec: 工作得很好;

在 while --- touch --- node.js exec 中:效果很好;

在 --- 期待 --- 少量运行中:效果很好;

在 while --- 期待 --- node.js exec: 错误

我很困惑为什么会发生这种情况。

node.js while-loop tcl expect
1个回答
0
投票

问题解决了,原因很简单:我需要在 ssh 命令之前添加 sudo 。感谢@glenn jackman 提供的调试建议。

© www.soinside.com 2019 - 2024. All rights reserved.