Hey there, fellow developers! Ready to dive into the world of SSH integrations? You're in for a treat. We'll be using the awesome paramiko package to build a robust SSH API integration in Python. Buckle up!
Before we jump in, make sure you've got:
pip install paramiko
)Let's get this party started:
import paramiko # Create an SSH client object ssh = paramiko.SSHClient() # Set the host key policy ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # Connect to the remote server ssh.connect('hostname', username='your_username', password='your_password')
Easy peasy, right? We've just created an SSH client, told it to automatically add host keys, and connected to our server.
Now for the fun part - running commands:
# Run a single command stdin, stdout, stderr = ssh.exec_command('ls -l') print(stdout.read().decode()) # Multiple commands? No problem! commands = ['echo "Hello"', 'pwd', 'date'] for command in commands: stdin, stdout, stderr = ssh.exec_command(command) print(stdout.read().decode())
Let's move some files around:
# Set up SFTP sftp = ssh.open_sftp() # Upload a file sftp.put('local_file.txt', '/remote/path/file.txt') # Download a file sftp.get('/remote/path/file.txt', 'local_file.txt') sftp.close()
Always be prepared:
try: # Your SSH operations here except paramiko.AuthenticationException: print("Authentication failed!") except paramiko.SSHException as ssh_exception: print(f"SSH exception: {ssh_exception}") finally: ssh.close() # Always close your connections!
Let's wrap this up in a neat little package:
class SSHClient: def __init__(self, hostname, username, password): self.ssh = paramiko.SSHClient() self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.ssh.connect(hostname, username=username, password=password) def execute_command(self, command): stdin, stdout, stderr = self.ssh.exec_command(command) return stdout.read().decode() def upload_file(self, local_path, remote_path): sftp = self.ssh.open_sftp() sftp.put(local_path, remote_path) sftp.close() def close(self): self.ssh.close()
Time to put it all together:
from flask import Flask, request, jsonify from ssh_client import SSHClient app = Flask(__name__) @app.route('/execute', methods=['POST']) def execute_command(): data = request.json client = SSHClient(data['hostname'], data['username'], data['password']) result = client.execute_command(data['command']) client.close() return jsonify({'result': result}) @app.route('/upload', methods=['POST']) def upload_file(): data = request.json client = SSHClient(data['hostname'], data['username'], data['password']) client.upload_file(data['local_path'], data['remote_path']) client.close() return jsonify({'status': 'success'}) if __name__ == '__main__': app.run(debug=True)
Fire up Postman or use curl to test your shiny new API:
curl -X POST http://localhost:5000/execute \ -H "Content-Type: application/json" \ -d '{"hostname": "example.com", "username": "user", "password": "pass", "command": "ls -l"}'
Remember, with great power comes great responsibility:
And there you have it! You've just built a powerful SSH API integration. Pat yourself on the back - you've earned it. Remember, this is just the beginning. There's always room for improvement, like adding more robust error handling or supporting key-based auth.
Now go forth and SSH like a boss! 🚀