// Step 1: Install the 'ssh2' and 'node-ssh' packages using npm
npm install ssh2 node-ssh
// Step 2: Import the required modules in your Node.js script
const { NodeSSH } = require('node-ssh');
// Step 3: Create a new instance of the NodeSSH class
const ssh = new NodeSSH();
// Step 4: Define connection parameters (host, username, and password/key)
const sshConfig = {
host: 'your-ssh-host',
username: 'your-ssh-username',
password: 'your-ssh-password', // OR privateKey: 'path-to-your-private-key.pem'
};
// Step 5: Connect to the SSH server using the provided configuration
ssh.connect(sshConfig)
.then(() => {
// Step 6: Execute an SSH command on the connected server
return ssh.execCommand('your-ssh-command');
})
.then((result) => {
// Step 7: Handle the result of the executed command
console.log('Command Output:', result.stdout);
console.log('Command Error:', result.stderr);
})
.catch((error) => {
// Step 8: Handle errors that may occur during the SSH connection or command execution
console.error('SSH Connection/Command Execution Error:', error);
})
.finally(() => {
// Step 9: Close the SSH connection when done
ssh.dispose();
});