1

I'm using the Node JS Child Process to run a command, I need to somehow automatically enter some text when prompted and press enter automatically from within my stdout, not sure how to do that...

var child = spawn('COMMAND-TO-RUN', {
  shell: true
});

child.stdout.on('data', function (data) {
  // when prompted in the terminal, need to input something automatically from here...
  console.log(data)
  console.log("STDOUT:", data.toString());
});

UPDATE

I've already tried to use child.stdin.write and this didn't work in the context of my problem where the terminal is prompting for a SSH password since I'm trying to automate inputting a password into the terminal through the JS, not sure why this doesn't work.

8
  • child.stdin.write(stuff to write) Commented Sep 20, 2020 at 15:11
  • @shamsup I've already tried this, it doesn't write anything when I'm prompted in the terminal. For context (on a mac terminal) it's trying to connect to a server through SSH and prompts me for the password to that sever after some time. stdin.write appears not to write anything. Commented Sep 20, 2020 at 15:31
  • If you append a '\n' to the input does it work? The line feed signifies the submission of the prompt. Commented Sep 20, 2020 at 15:39
  • Appears not to work, tried adding a setTimeout as well Commented Sep 20, 2020 at 16:12
  • 1
    There is probably not a generic way to do that. ssh doesn't read the password from standard input, otherwise something like echo password | ssh host would work. Instead standard input gets passed to the command on the remote side. This may or may not help: serverfault.com/questions/241588/… Commented Sep 21, 2020 at 14:32

1 Answer 1

1
+50

You can pipe the child's stdin and stderr to the parent process. For example:

var child = spawn('ps', {
    shell: true
});

child.stdout.on('data', function (data) {
    // when prompted in the terminal, need to input something automatically from here...
    process.stdout.write('Something I want to print\n\n');
    console.log(data)
    console.log("STDOUT:", data.toString());
});

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

@ryan-holton, here is the screenshot of the output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.