SSH in Scripts

Automation is a critical aspect of system administration and software development. SSH enables secure remote connections and can be integrated into scripts to automate repetitive tasks. This section outlines how SSH can be used in shell scripts and popular programming languages, such as Python, PHP, and PowerShell, as well as best practices for non-interactive authentication.

Automating SSH Connections with Shell Scripts

Automating SSH connections can save time when running frequent or complex tasks on remote systems. By embedding SSH commands in shell scripts, workflows can be streamlined, whether for system administration, deployments, or backups.

Basic Example of SSH in a Shell Script

#!/bin/bash
# A simple script to update a remote system via SSH

ssh user@remote-host 'sudo apt update && sudo apt upgrade -y'

For more complex workflows, additional logic can be added to the script, such as handling the result of remote commands or executing multiple commands sequentially.

Error Handling in SSH Scripts

#!/bin/bash
# A script to perform updates on a remote server and check for errors

ssh user@remote-host 'sudo apt update && sudo apt upgrade -y'
if [ $? -eq 0 ]; then
    echo "Update successful"
else
    echo "Update failed"
fi

Automating SSH in Python

Python offers the paramiko library, a popular SSH module that allows for remote connections and command execution over SSH.

Example of Using SSH with Python:

import paramiko

# Create SSH client
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# Connect to the remote host
ssh.connect('remote-host', username='user', key_filename='/path/to/private/key')

# Execute a command
stdin, stdout, stderr = ssh.exec_command('sudo apt update && sudo apt upgrade -y')

# Output the result
print(stdout.read().decode())
print(stderr.read().decode())

# Close the connection
ssh.close()

Automating SSH in PHP

PHP has a built-in ssh2 extension that allows SSH functionality for automating tasks and remote execution.

Example of Using SSH with PHP:

<?php
$connection = ssh2_connect('remote-host', 22);
ssh2_auth_password($connection, 'user', 'password');

// Execute the command on the remote server
$stream = ssh2_exec($connection, 'sudo apt update && sudo apt upgrade -y');
stream_set_blocking($stream, true);

// Get the output
$output = stream_get_contents($stream);
fclose($stream);

echo $output;
?>

Automating SSH in PowerShell

PowerShell natively supports SSH, and administrators can use it to automate remote connections and tasks. This is especially useful on Windows systems or in mixed OS environments.

Example of Using SSH with PowerShell:

# A simple SSH example in PowerShell to run remote commands
$session = New-PSSession -HostName 'remote-host' -UserName 'user' -KeyFilePath 'C:\path\to\private\key'

# Execute a command remotely
Invoke-Command -Session $session -ScriptBlock { sudo apt update && sudo apt upgrade -y }

# Close the session
Remove-PSSession -Session $session

In this example, PowerShell's New-PSSession is used to create an SSH session, and Invoke-Command runs the commands on the remote host. This method integrates well with automation workflows in Windows environments.

Best Practices for Non-Interactive Authentication

When automating SSH connections, requiring manual password entry defeats the purpose of automation. Non-interactive authentication methods, such as key-based authentication, allow scripts to connect to remote servers without manual intervention.

Using SSH Keys for Non-Interactive Authentication

To set up key-based authentication for non-interactive SSH connections, generate a key pair and configure the remote server to accept the public key.

Generate SSH keys:

ssh-keygen -t rsa -b 4096

The generated public key (~/.ssh/id_rsa.pub) should be added to the remote server’s ~/.ssh/authorized_keys file.

Copy the public key to the remote server:

ssh-copy-id user@remote-host

With key-based authentication, SSH scripts can connect to the remote server without requiring password input.

Securing SSH Keys

The private key must be securely stored and access restricted. Ensure the private key file has strict permissions:

chmod 600 ~/.ssh/id_rsa

For environments with heightened security requirements, SSH agents (ssh-agent) can be used to manage key passphrases without exposing the private key in scripts.


This section introduces the basics of automating SSH connections in shell scripts, Python, PHP, and PowerShell, along with best practices for non-interactive authentication. More advanced techniques, including SSH configuration file customization, are discussed in the next section to further simplify complex SSH workflows.