PuppetHero is a monthly newsletter that will help you supercharge your web-based workflows. With just a little bit of code & time, you can automate repetitive tasks and save time. Sign up, for free, today! The PuppetHero Digest @ PuppetHero.com!

I am converting a Python script to Nodejs. The script SSH’s me into a server in the cloud. In my Python script, I did:

import os
os.system('ssh user@{hostname}:{port}'.format(hostname=hostname, port=port))

I spent some time Googling various ways to get this done in Nodejs. After 30 minutes of unsuccessful attempts at using child_process.exec, I settled on the following code (note, I used zsh as my shell):

const { spawn } = require('child_process');
let shell = spawn('zsh', `ssh user@${hostname}:${port}`,  { stdio: 'inherit' });
shell.on('close',(code) => console.log('SSH terminated :', code));

stdio: 'inherit' passes the standard input/output stream to/from the spawned process.

My new Nodejs script SSH’s me into the server of my choosing and allows for user input as well, which was the reason behind my 30 minutes of failure.