Node.js - SSH using node-ssh

by
Jeremy Canfield |
Updated: August 07 2024
| Node.js articles
The node-ssh package can be used to make an SSH connection onto a target system and to issue a command on the target system in Node.js. The npm list command can be used to determine if you have the node-ssh package installed. If not, the npm install command can be used to install the node-ssh package. Once installed, your package.json should include the node-ssh package.
{
"dependencies": {
"node-ssh": "^13.2.0"
}
}
Let's say you have a file named app.js that contains the following. In this example, an SSH connection will be made to server1.example.com as john.doe using John Doe's id_rsa private key file and the ls /tmp command will be issued on the target system.
const {NodeSSH} = require('node-ssh')
const ssh = new NodeSSH()
ssh.connect({
host: 'server1.example.com',
username: 'john.doe',
privateKeyPath: '/home/john.doe/.ssh/id_rsa'
}).then(resp => {
ssh.execCommand('ls', { cwd:'/tmp' }).then(function(result) {
console.log(`STDOUT: ${result.stdout}`)
console.log(`STDERR: ${result.stderr}`)
ssh.dispose();
})
});
Did you find this article helpful?
If so, consider buying me a coffee over at