Voiced by Amazon Polly |
Introduction
This blog will walk you through securely accessing your VMs through SSH using automation and scripting techniques. Whether you are a developer, system administrator, or someone looking to streamline their workflow, we have you covered. We will utilize popular programming languages and tools to establish SSH connections programmatically. By the end of this guide, you will have the knowledge and skills to effortlessly automate SSH access to your VMs, enabling seamless remote management and deployment in your projects.
Pioneers in Cloud Consulting & Migration Services
- Reduced infrastructural costs
- Accelerated application deployment
Pre-requisite
- A VM with SSH access from the system running the script
- Username and Private Key file of the VM
- Python 3.x and NodeJS are installed on the system running the script
SSH into the VM
Using Python
We’ll use the “paramiko” library to SSH into the VM. The official documentation of the library can be found here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
import paramiko def ssh_ec2_instance(instance_ip, username, private_key_path, command): # Create an SSH client ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: # Load the private key private_key = paramiko.RSAKey.from_private_key_file(private_key_path) # Connect to the EC2 instance ssh_client.connect(instance_ip, username=username, pkey=private_key) print("Running command: " + command) # Execute the command stdin, stdout, stderr = ssh_client.exec_command(command) # Print the command output print("Command Output:") print(stdout.read().decode()) # Close the SSH connection ssh_client.close() except paramiko.AuthenticationException: print("Authentication failed. Please check your credentials.") except paramiko.SSHException as e: print("Unable to establish SSH connection:", str(e)) except Exception as e: print("An error occurred:", str(e)) # Example usage instance_ip = "<VMs_IP_address>" username = "<username>" private_key_path = "<path_to_the_private_key>" command = "<command_to_run>" ssh_ec2_instance(instance_ip, username, private_key_path, command) |
Here, we are using the ‘paramiko’ library and creating an SSH Client, bypassing the required parameters/inputs to the SSH Client, and we can SSH into the VM and run the specified command.
To run this code, copy and paste it into the ‘main.py’ file. Then install the ‘paramiko’ library using the command ‘pip install paramiko’ and run the ‘main.py’ file using ‘python main.py’.
Using NodeJS
We’ll use the “ssh2” library to SSH into the VM. The official documentation of the library can be found here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
const fs = require('fs'); const { Client } = require('ssh2'); // Configuration const SSHConfig = { host: ‘<VM_ip_address>’, port: 22, username: '<username>', privateKeyPath: '<path_to_private_key_file>' } // Create an SSH client const sshClient = new Client(); // Read the private key file const privateKey = fs.readFileSync(SSHConfig.privateKeyPath); const printData = (command, data) => { console.log(); console.log("------------------------------------------"); console.log(command); console.log("------------------------------------------"); console.log(data); console.log("------------------------------------------"); console.log(); } const executeCommand = (command) => { return new Promise((resolve, reject) => { console.log("Running command:", command); // Execute the command on the VM sshClient.exec(command, (err, stream) => { if (err) { reject(err); }; // Capture the command output stream.on('data', (data) => { // console.log('Output:', data.toString()); resolve(data.toString()); }); // Capture any errors during command execution stream.stderr.on('data', (data) => { console.log(`Error while running '${command}'...`); reject(data.toString()); }); // Close the SSH connection once the command execution is complete stream.on('close', (code, signal) => { if (code === 0) { resolve(null); } else { reject(code); } }); }); }) } // Connect to the VM sshClient.on('ready', async () => { console.log('Connected to the VM'); try { const commandOutput = await executeCommand("ls -l"); printData("ls -l", commandOutput); } catch (err) { console.log(err); } finally { console.info("Ending SSH session..."); sshClient.end(); console.log("SSH Session closed!"); } }); // Connect to the VM using the provided credentials sshClient.connect({ host: SSHConfig.host, port: SSHConfig.port, username: SSHConfig.username, privateKey, }); |
Here, we are using the ‘ssh2’ library and creating an SSH Client, bypassing the required parameters/inputs to the SSH Client, and we can SSH into the VM and run the specified command.
To run this code, copy and paste it into the ‘index.js’ file. Then install the ‘ssh2’ library using the command ‘npm install ssh2’ and run the ‘index.js’ file using ‘node index.js’.
Precaution
If you are executing the script on a Windows system, it is important to handle the file path of the key correctly. Windows systems use backslashes (‘\’) in file paths, which must be properly escaped.
For example, if the file path is ‘C:\Users\AvinashKumar\Downloads\key.pem’, it should be modified to ‘C:\\Users\\AvinashKumar\\Downloads\\key.pem’ to ensure accurate handling of the file path in your script.
Benefits of SSH-ing Programmatically
Programmatically SSH-ing into VMs brings several benefits to developers and system administrators.
- Automation: SSH-ing into VMs programmatically allows you to automate tasks and workflows, saving time and reducing human error. You can write scripts or use tools to establish SSH connections, execute commands, transfer files, and manage multiple VMs simultaneously.
- Efficiency: With programmatic SSH access, you can quickly and easily connect to VMs without manual intervention. This streamlined process improves efficiency and productivity, especially when working with many VMs or in a distributed environment.
- Scalability: As your infrastructure grows, manually SSH-ing into each VM becomes impractical. Programmatically, SSH-ing enables you to scale your operations effortlessly by automating connection and management processes across multiple VMs.
- Integration: By leveraging programming languages like Python or Node.js, you can seamlessly integrate SSH access into your existing workflows, tools, or deployment pipelines. This integration enables a cohesive and unified environment for managing your VMs alongside other automated processes.
Conclusion
Whether you’re a developer deploying applications or a system administrator managing a large-scale infrastructure, programmatically SSH-ing into VMs opens up a world of possibilities for efficient remote access and administration. Embrace the potential of automation and take your VM management to the next level with programmatically SSH-ing into VMs.
Drop a query if you have any questions regarding SSH-ing into VMs and we will get back to you quickly.
Making IT Networks Enterprise-ready – Cloud Management Services
- Accelerated cloud migration
- End-to-end view of the cloud environment
About CloudThat
CloudThat is an official AWS (Amazon Web Services) Advanced Consulting Partner and Training partner and Microsoft Gold Partner, helping people develop knowledge of the cloud and help their businesses aim for higher goals using best in industry cloud computing practices and expertise. We are on a mission to build a robust cloud computing ecosystem by disseminating knowledge on technological intricacies within the cloud space. Our blogs, webinars, case studies, and white papers enable all the stakeholders in the cloud computing sphere.
To get started, go through our Consultancy page and Managed Services Package that is CloudThat’s offerings.
FAQs
1. Is it possible to transfer files programmatically over SSH to VMs?
ANS: – Yes, it is possible to transfer files programmatically over SSH to VMs. Python and Node.js offer libraries that support file transfer over SSH, allowing you to automate uploading or downloading files to and from VMs.
2. Can SSH manage VMs in cloud platforms like AWS, Azure, or Google Cloud?
ANS: – Absolutely. SSH is commonly used to manage VMs in various cloud platforms, including AWS, Azure, and Google Cloud. These platforms provide SSH access to VM instances, allowing you to manage and configure your cloud-based infrastructure remotely.
3. Can I establish SSH connections to VMs located behind firewalls or private networks?
ANS: – Yes, it is possible to establish SSH connections to VMs located behind firewalls or private networks. Techniques such as port forwarding, VPNs (Virtual Private Networks), or SSH bastion hosts can be used to access VMs securely from external networks.
4. Is it possible to schedule automated SSH tasks or scripts for VM management?
ANS: – Yes, you can schedule automated SSH tasks or scripts using CRON jobs (on Linux) or task schedulers (on Windows). By configuring these tools to execute SSH commands or scripts at specific times, you can automate routine tasks, backups, or maintenance activities on your VMs.
WRITTEN BY Avinash Kumar
Avinash Kumar is a Senior Research Associate at CloudThat, specializing in Cloud Engineering, NodeJS development, and Google Cloud Platform. With his skills, he creates innovative solutions that meet the complex needs of today's digital landscape. He's dedicated to staying at the forefront of emerging cloud technologies.
Click to Comment