node-ssh provides two primary ways to execute commands:
execCommand(command, options): Best for simple commands. Returns a Promise resolving to an SSHExecCommandResponse containing stdout, stderr, code, and signal. By default, output is trimmed.exec(command, parameters, options): Best for commands with arguments. If options.stream is set to 'stdout', 'stderr', or 'both', it returns a Promise resolving to the output string or an SSHExecCommandResponse respectively.
Running commands with a Pseudo-TTY
For terminal programs like screen or tmux, pass pty: true inside execOptions.
const result = await ssh.execCommand('screen -r', {
execOptions: { pty: true }
})
// Simple command
ssh.execCommand('hh_client --json', { cwd:'/var/www' }).then(function(result) {
console.log('STDOUT: ' + result.stdout)
console.log('STDERR: ' + result.stderr)
})
// Command with arguments and streaming
ssh.exec('hh_client', ['--json'], {
cwd: '/var/www',
onStdout(chunk) {
console.log('stdoutChunk', chunk.toString('utf8'))
}
})