python LogoParamiko

Paramiko is a Python (2.7, 3.4+) implementation of the SSHv2 protocol, providing both client and server functionality. It's built on top of `cryptography`, `pynacl`, and `pyasn1`, ensuring secure and robust cryptographic operations. Paramiko allows Python programs to connect to SSH servers, execute commands, transfer files using SFTP, and even implement SSH server-like behavior.

Key features and use cases of Paramiko:

1. SSH Client Functionality: The most common use case is establishing SSH connections to remote servers. This enables:
- Command Execution: Programmatically run shell commands on the remote machine and capture their standard output, standard error, and exit status.
- Interactive Shell: Create an interactive SSH shell session, similar to what you'd get with `ssh` from the command line.
- Port Forwarding: Set up local or remote port forwarding.
- Authentication: Supports various authentication methods including password, public/private key pairs, and agent forwarding.

2. SFTP Client Functionality: Paramiko includes a full-featured SFTP client, allowing for secure file transfers:
- Upload/Download Files: Transfer files from the local machine to the remote server and vice-versa.
- Directory Management: Create, list, rename, and delete directories on the remote server.
- File Attributes: Get and set file permissions and other attributes.

3. SSH Server Functionality: Although less common, Paramiko can also be used to create custom SSH servers. This allows you to implement your own logic for handling SSH connections, authentication, and command execution, acting as an SSH endpoint for clients.

4. Integration: Paramiko serves as a foundational library for many higher-level automation and deployment tools in Python (e.g., Fabric, Ansible's underlying SSH connection).

Paramiko is highly valuable for tasks like automating system administration, deploying applications, orchestrating remote tasks, building backup solutions, and any scenario requiring secure remote access from a Python script.

Example Code

import paramiko
import time

 --- Configuration --- 
HOSTNAME = 'your_ssh_server_ip_or_hostname'
PORT = 22
USERNAME = 'your_username'
PASSWORD = 'your_password'  Or use key_filename for key-based auth
 KEY_FILENAME = '/path/to/your/private_key'

 --- SSH Client Example --- 
def run_ssh_command(hostname, port, username, password, command):
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())  Be cautious in production, prefer known_hosts
    
    try:
        print(f"Connecting to {username}@{hostname}:{port}...")
        client.connect(hostname=hostname, port=port, username=username, password=password, timeout=10)
         For key-based authentication:
         client.connect(hostname=hostname, port=port, username=username, key_filename=KEY_FILENAME, timeout=10)
        
        print(f"Executing command: '{command}'")
        stdin, stdout, stderr = client.exec_command(command)
        
         Read command output
        output = stdout.read().decode().strip()
        error = stderr.read().decode().strip()
        
        if output:
            print("--- STDOUT ---")
            print(output)
        if error:
            print("--- STDERR ---")
            print(error)
        
         Optional: Get exit status (requires waiting for command to finish)
        exit_status = stdout.channel.recv_exit_status()
        print(f"Command exited with status: {exit_status}")
        
    except paramiko.AuthenticationException:
        print("Authentication failed. Please check username and password/key.")
    except paramiko.SSHException as e:
        print(f"SSH error: {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
    finally:
        if client:
            client.close()
            print("SSH connection closed.")

 --- SFTP Client Example (Upload a file) --- 
def upload_file_sftp(hostname, port, username, password, local_path, remote_path):
    transport = paramiko.Transport((hostname, port))
    try:
        print(f"Connecting for SFTP to {username}@{hostname}:{port}...")
        transport.connect(username=username, password=password)  Or pkey=paramiko.RSAKey.from_private_key_file(KEY_FILENAME)
        
        sftp = paramiko.SFTPClient.from_transport(transport)
        print(f"Uploading '{local_path}' to '{remote_path}'...")
        sftp.put(local_path, remote_path)
        print("File uploaded successfully.")
        
    except paramiko.AuthenticationException:
        print("SFTP authentication failed. Please check username and password/key.")
    except Exception as e:
        print(f"SFTP error: {e}")
    finally:
        if transport:
            transport.close()
            print("SFTP connection closed.")

 --- Main execution --- 
if __name__ == "__main__":
    print("--- Running SSH Command Example ---")
    run_ssh_command(HOSTNAME, PORT, USERNAME, PASSWORD, "ls -la /tmp")
    print("\n" + "="-40 + "\n")
    
     Create a dummy local file for SFTP upload
    local_test_file = "./local_test_file.txt"
    with open(local_test_file, "w") as f:
        f.write("This is a test file created by Paramiko example.\n")
        f.write(f"Timestamp: {time.ctime()}\n")
    
    print("--- Running SFTP Upload Example ---")
    remote_upload_path = f"/tmp/paramiko_uploaded_file_{int(time.time())}.txt"
    upload_file_sftp(HOSTNAME, PORT, USERNAME, PASSWORD, local_test_file, remote_upload_path)
    
     Clean up local test file (optional)
    import os
    if os.path.exists(local_test_file):
        os.remove(local_test_file)
        print(f"Removed local test file: {local_test_file}")

    print("\n" + "="-40 + "\n")
    print("--- Verifying SFTP upload with SSH Command ---")
    run_ssh_command(HOSTNAME, PORT, USERNAME, PASSWORD, f"cat {remote_upload_path}; rm {remote_upload_path}")