Home > Back-end >  Get password for node-cli and pass it on to next command in nodejs
Get password for node-cli and pass it on to next command in nodejs

Time:12-25

Im trying to build a command line interface using nodejs. I have used enquirer package to prompt users for questions. I have a scenario where i need to write to /etc/hosts file. I tried running the following command using execa package

const {stdout} = await execa.command('echo "192.241.xx.xx  venus.example.com venus" >> /etc/hosts', { cwd: '/etc/'})

But it does not seems to work and tried with sudo command as well

const {stdout} = await execa.command("sudo vim hosts", { cwd: '/etc/'}); 

How to execute it in nodejs. Basically i wanted to prompt the user for password and then need to write it to /etc/hosts file.

FYKI: im using execa for executing shell commands. Tried the hostile.js and it didn't work either.

Here is the full code

async function executeCommand() {
  try {
    const {stdout} = await execa.command("echo '192.34.0.03 subdomain.domain.com' | sudo tee -a /etc/hosts", { cwd: '/etc/'});
    console.log(stdout);
  } catch (error) {
    console.log(error);
    process.exit(1);
  }
}

CodePudding user response:

There is a Node package for this purpose, called password-prompt:

let prompt = require('password-prompt');
let password = prompt('password: ');

And now that you have the password, you can run something like this:

let command = `echo "${password}" | sudo -S -k vim /etc/hosts`;

CodePudding user response:

This solution worked for me

const { promisify } = require('util');
const exec = promisify(require('child_process').exec)
const nameOutput = await exec("echo '127.0.0.1 test.com' | sudo tee -a /etc/hosts")

This would prompt password to enter.

  • Related