SSH command works in terminal, but fails with nodejs / ssh2

Viewed 1371

In terminal if I login with ssh and run a command like service something reload it runs just fine, but when I execute the same command in a nodejs script with the ssh2 library (.exec function) it doesn't run and i get an error "ash: command not found".

Tried with sudo service.. but it's same thing.

Some commands do work tho, like uptime or ifconfig, but service doesn't and I need that one. The server to which I am connecting is a router that runs open wrt.


this is the nodejs script:

const Client = require('ssh2').Client;
const conn = new Client();

conn.on('ready', async() => {

  conn.exec('service network reload', {
    env: {'PATH': '/usr/sbin:/usr/bin:/sbin:/bin'},
  }, (err, stream) => {
    if(err)
      return console.log(err);

    stream.on('close', () => console.log('ok'));
    stream.stderr.on('data', data => console.log(data.toString()));
  }); 

}).connect({
  host: ROUTER_HOST,
  port: 22,
  username: 'root',
  password: '1234'
});

A screenshot of the terminal output for which:

wtf

3 Answers

You get "bash command not found error." because your PATH does not include the location of the service executable.

Compare result of echo $PATH; from ssh2 with your terminal. if your ssh2 miss some paths update your environment.

You have to pass an options object that includes the key env whose value is itself an object of key value pairs.

exec('sudo service something reload', {env: {'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:'}}, function (error, stdout, stderr) 
{
    console.log(stdout, stderr, error);
});

If you're getting a command not found error, it simply means your command, in this case service, is not found within the environment's $PATH.

Either, set your environment properly for your connection, or use absolute paths for the commands.

For systemd service, use /usr/sbin/service something reload, or /bin/systemctl reload something etc.

You can find paths of your executables with which command, like which service or which systemctl.

For older init script services, run /etc/init.d/something restart.

Related