sanketbajoria / ssh2-promise

ssh with promise/async await and typescript support
https://www.npmjs.com/package/ssh2-promise
MIT License
148 stars 25 forks source link

using sudo #58

Closed ionush closed 3 years ago

ionush commented 3 years ago

There is not much guidance on using sudo with the ssh.exec() command.

I have tried

await ssh.exec('sudo mkdir /data/jestdir', { pty: true });

await ssh.exec('sudo mkdir /data/jestdir', null, { pty: true });

documentation isn't too clear about how to use, I either get an error or it hangs.

Please could you advise? Thanks

sanketbajoria commented 3 years ago

@ionush

Does sudo command require password?

Below is sample, how to call it..

ssh.exec("echo sanket | sudo -S sh -c whoami", undefined,{
                pty: true
            })

Here sanket is sudo password

ionush commented 3 years ago

I'm using this to perform mkdir and it still isn't working:

  try {
    const x = await ssh.exec(
      'echo p4$$w0rd | sudo -S sh -c mkdir /data/testdir',
      undefined,
      {
        pty: true
      }
    );
  } catch (error) {
    console.log('error', error.toString());
  }

I have initialised SSH2Promise with host, username, password.

Other non-sudo commands such as ls work e.g. const res = await ssh.exec('ls /data');

ionush commented 3 years ago

Fixed it. This is because I had special characters in my password, escape using " e.g. sudo "p4$$w0rd" | sudo -S mkdir /data/testdir

sanketbajoria commented 3 years ago

@ionush

Did you get any error.

try {
    const x = await ssh.exec(
      "echo p4$$w0rd | sudo -S sh -c 'mkdir /data/testdir'",
      undefined,
      {
        pty: true
      }
    );
  } catch (error) {
    console.log('error', error.toString());
  }

Please notice, how i have wrapped mkdir in single quote and outer command in double quote and also if you do have bash in your machine, then you can use bash instead of sh.