首页 > 解决方案 > 远程运行 bash 命令并模拟击键

问题描述

在 NodeJS 中,我可以生成一个进程并使用spawn().stdout. 我正在尝试创建一个将与这个 shell 交互的在线终端。我不知道如何将击键发送到 shell 进程。

我试过这个:

echo -e "ls\n" > /proc/{bash pid}/fd/0

除了输出 ls 和换行符之外,这实际上并没有做任何事情。当我尝试这样做时tail -f /proc/{bash pid}/fd/0,我什至无法将击键发送到打开的bash终端。

我真的只是在试图了解该bash过程将如何解释 ENTER 键。我不知道这是否通过标准输入完成,因为换行符不起作用。

标签: node.jsbashterminalshtty

解决方案


I don't believe you can "remote control" an already started normal Bash session in any meaningful way. What you can do is start a new shell which reads from a named pipe; you can then write to that pipe to run commands:

$ cd "$(mktemp --directory)"
$ mkfifo pipe1
$ bash < pipe1 &
$ echo touch foo > pipe1
[1]+  Done                    bash < pipe1
$ ls
foo  pipe1

See How to write several times to a fifo without having to reopen it? for more details.


推荐阅读