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

wmtdaxz3  于 2023-08-04  发布在  Node.js
关注(0)|答案(1)|浏览(79)

我正在使用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编写的expect 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块中添加了两个touch命令,但它们都不起作用。戏剧性的是,如果我直接在node.js服务器中运行expect tcl-ssh.sh,我会得到正确的结果。
我尝试用touch命令替换while循环中的expect块,它也工作得很好。下面是我的审判。
Not in while - expect - node.js exec:运作良好;
在while -touch- node.js exec中:运作良好;
在while - expect - handful运行中:运作良好;
在while - expect - node.js exec中:断层
我不明白为什么会这样。

dxxyhpgq

dxxyhpgq1#

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

相关问题