Complete Guide to Bash ssh Command

Introduction to ssh

SSH (Secure Shell) is a cryptographic network protocol for operating network services securely over an unsecured network. The ssh command is the OpenSSH client that allows secure remote login, command execution, and file transfer. It's the standard for remote system administration and secure communications.

Key Concepts

  • Encryption: All traffic is encrypted to prevent eavesdropping
  • Authentication: Multiple methods including passwords, keys, and certificates
  • Port Forwarding: Create secure tunnels for other applications
  • X11 Forwarding: Run graphical applications remotely
  • Agent Forwarding: Forward authentication credentials
  • Jump Hosts: Connect through intermediate servers

1. Basic Usage

Simple SSH Connections

#!/bin/bash
# Basic SSH connection to remote host
ssh user@hostname
ssh [email protected]
ssh [email protected]
# Using default port (22) or custom port
ssh -p 2222 user@hostname
# Connect with specific username (if different from local)
ssh -l username hostname
ssh username@hostname
# Execute a single command remotely
ssh user@hostname 'ls -la /var/log'
ssh user@hostname 'df -h' 'free -m'
# Run multiple commands
ssh user@hostname '
cd /var/log
grep ERROR *.log
tail -n 50 syslog
'
# Interactive session with command
ssh -t user@hostname 'sudo systemctl restart nginx'
# Verbose mode (for debugging)
ssh -v user@hostname
ssh -vvv user@hostname  # Even more verbose
# Quiet mode (suppress warnings)
ssh -q user@hostname

Common Examples

#!/bin/bash
# Check system info on remote host
ssh admin@server 'uname -a; uptime; df -h'
# Copy SSH key to remote (automate with ssh-copy-id)
ssh-copy-id user@hostname
# Test connection without executing commands
ssh -o ConnectTimeout=5 user@hostname exit
# Run local script on remote
ssh user@hostname 'bash -s' < local_script.sh
# Pass arguments to remote script
ssh user@hostname 'bash -s' arg1 arg2 arg3 < script.sh
# Background SSH session (with pseudo-terminal)
ssh -fNT user@hostname
# Escape sequences (in SSH session)
# ~. - terminate connection
# ~^Z - background SSH
# ~? - list escapes
# Example: Monitor remote log
ssh user@hostname 'tail -f /var/log/syslog'

2. Authentication Methods

Password Authentication

#!/bin/bash
# Basic password authentication (interactive)
ssh user@hostname
# Disable password authentication (force key-based)
ssh -o PasswordAuthentication=no user@hostname
# Expect script for automated password entry (not recommended)
# Use sshpass (not secure) for testing only
sshpass -p 'password' ssh user@hostname 'command'
# Better: Use SSH keys

Key-Based Authentication

#!/bin/bash
# Generate SSH key pair
ssh-keygen -t rsa -b 4096 -C "[email protected]"
ssh-keygen -t ed25519 -C "[email protected]"  # Modern, more secure
# Generate with specific filename
ssh-keygen -t rsa -f ~/.ssh/mykey -C "[email protected]"
# Set passphrase
ssh-keygen -t rsa -b 4096 -N "mypassphrase" -f ~/.ssh/id_rsa
# Copy public key to remote server
ssh-copy-id user@hostname
ssh-copy-id -i ~/.ssh/mykey.pub user@hostname
# Manual key copy
cat ~/.ssh/id_rsa.pub | ssh user@hostname 'mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys'
# Use specific identity file
ssh -i ~/.ssh/mykey user@hostname
# Add key to SSH agent
eval $(ssh-agent)
ssh-add ~/.ssh/id_rsa
ssh-add -l  # List loaded keys
ssh-add -d ~/.ssh/id_rsa  # Delete key
# Agent forwarding (use with caution)
ssh -A user@hostname

SSH Agent and Key Management

#!/bin/bash
# Start SSH agent
eval $(ssh-agent -s)
# Add keys
ssh-add ~/.ssh/id_rsa
ssh-add ~/.ssh/work_key
# List keys in agent
ssh-add -l
ssh-add -L  # List public keys
# Remove keys
ssh-add -d ~/.ssh/id_rsa  # Remove specific
ssh-add -D  # Remove all
# Time-limited key addition
ssh-add -t 3600 ~/.ssh/id_rsa  # Expires after 1 hour
# Agent forwarding (forward authentication)
ssh -A user@hostname
# Check if agent is running
if [ -n "$SSH_AUTH_SOCK" ]; then
echo "SSH agent is running"
fi
# Use keychain for persistent agent
# Install: apt-get install keychain
keychain ~/.ssh/id_rsa
source ~/.keychain/$(hostname)-sh

Certificate Authentication

#!/bin/bash
# Create CA key
ssh-keygen -t rsa -b 4096 -f ca_key
# Sign user public key
ssh-keygen -s ca_key -I user_id -n username -V +52w user_key.pub
# Configure server to trust CA
# In /etc/ssh/sshd_config:
# TrustedUserCAKeys /etc/ssh/ca_key.pub
# Use certificate
ssh -i user_key-cert.pub user@hostname

3. SSH Configuration File

Client Configuration (~/.ssh/config)

# ~/.ssh/config examples
# Global options
Host *
ServerAliveInterval 60
ServerAliveCountMax 3
ConnectTimeout 10
Compression yes
ExitOnForwardFailure yes
# Specific host configuration
Host myserver
HostName server.example.com
User admin
Port 2222
IdentityFile ~/.ssh/server_key
ForwardAgent no
Compression yes
# Multiple names for same host
Host dev staging prod
HostName %h.internal.company.com
User deploy
IdentityFile ~/.ssh/deploy_key
# Jump host configuration
Host behind-firewall
HostName 10.0.0.100
User internal
ProxyJump jumpbox.example.com
# Wildcard for subdomains
Host *.dev.example.com
User developer
IdentityFile ~/.ssh/dev_key
StrictHostKeyChecking no
# Git-specific configuration
Host github.com
User git
IdentityFile ~/.ssh/github_key
IdentitiesOnly yes
# Reuse connection (speed up multiple connections)
Host *
ControlMaster auto
ControlPath ~/.ssh/controlmasters/%r@%h:%p
ControlPersist 10m

Using Configuration

#!/bin/bash
# Create control directory
mkdir -p ~/.ssh/controlmasters
# Connect using config shortcuts
ssh myserver
ssh dev
ssh behind-firewall
# Override config options
ssh -o "Port=2222" myserver
ssh -F ~/custom_ssh_config myserver
# Check configuration
ssh -G myserver  # Print effective configuration
# Test configuration parsing
ssh -T [email protected]  # Test GitHub connection

4. Port Forwarding (Tunneling)

Local Port Forwarding

#!/bin/bash
# Forward local port to remote service
# Syntax: ssh -L local_port:destination_host:destination_port user@gateway
# Access remote MySQL (on server) via local port 3306
ssh -L 3306:localhost:3306 user@server
# Now connect to mysql -h 127.0.0.1 -P 3306
# Forward to different remote host
ssh -L 8080:internal-server:80 user@gateway
# Multiple forwards
ssh -L 8080:web:80 -L 3306:db:3306 user@gateway
# Bind to specific local interface
ssh -L 127.0.0.1:8080:localhost:80 user@server
# Background tunnel
ssh -fN -L 3306:localhost:3306 user@server
# Example: Access internal web server
ssh -L 8080:intranet.company.com:80 bastion.company.com
echo "Open browser at http://localhost:8080"

Remote Port Forwarding

#!/bin/bash
# Forward remote port to local service
# Syntax: ssh -R remote_port:localhost:local_port user@gateway
# Expose local web server to remote
ssh -R 8080:localhost:80 user@public-server
# Now remote can access local server at localhost:8080
# Multiple remote forwards
ssh -R 8080:localhost:80 -R 2222:localhost:22 user@public-server
# Gateway ports (allow others to use forward)
ssh -R 0.0.0.0:8080:localhost:80 user@public-server
# Need GatewayPorts yes on server
# Example: Share local development server
ssh -R 3000:localhost:3000 user@server
echo "Remote can access your dev server at localhost:3000"

Dynamic Port Forwarding (SOCKS Proxy)

#!/bin/bash
# Create SOCKS proxy on local port
ssh -D 1080 user@gateway
# Use with applications
# Configure browser to use SOCKS proxy localhost:1080
# Background SOCKS proxy
ssh -fN -D 1080 user@gateway
# With compression
ssh -C -D 1080 user@gateway
# Example: curl through SOCKS
curl --socks5 localhost:1080 http://internal-site.local
# Firefox configuration
# Network Settings > Manual proxy > SOCKS Host: localhost Port: 1080

Advanced Tunneling

#!/bin/bash
# Jump host (multiple hops)
ssh -J user1@jump1,user2@jump2 user@target
# Old style with ProxyCommand
ssh -o ProxyCommand="ssh -W %h:%p jumpbox" target
# SSH through bastion
ssh -o ProxyJump=bastion.internal.com target.internal.com
# Tunnel with local and remote forwards
ssh -L 8080:localhost:80 -R 3306:localhost:3306 user@server
# X11 forwarding (run GUI apps remotely)
ssh -X user@server  # Trusted X11 forwarding
ssh -x user@server  # Disable X11 forwarding
ssh -Y user@server  # Enable trusted X11 forwarding
# Example: Run Firefox remotely
ssh -X user@server firefox
# Keep tunnel alive
autossh -M 0 -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" \
-L 3306:localhost:3306 user@server

5. File Transfer with SSH

SCP (Secure Copy)

#!/bin/bash
# Copy local file to remote
scp file.txt user@hostname:/path/to/destination/
scp -r directory/ user@hostname:/path/
# Copy remote file to local
scp user@hostname:/path/file.txt ./
scp -r user@hostname:/path/directory/ ./
# Copy between two remote hosts
scp user1@host1:/path/file.txt user2@host2:/path/
# Use specific port
scp -P 2222 file.txt user@hostname:/path/
# Preserve attributes
scp -p file.txt user@hostname:/path/
# Limit bandwidth
scp -l 1000 largefile.iso user@hostname:/path/
# Quiet mode
scp -q file.txt user@hostname:/path/
# Use specific identity
scp -i ~/.ssh/mykey file.txt user@hostname:/path/
# Examples
scp -r ~/project/ user@server:/backups/
scp -C largefile.dat user@server:/tmp/  # Compression

SFTP (SSH File Transfer Protocol)

#!/bin/bash
# Interactive SFTP session
sftp user@hostname
# Batch mode with commands
echo "put file.txt" | sftp -b - user@hostname
# Download directory recursively
sftp -r user@hostname:/remote/dir/ ./local/
# Upload directory recursively
sftp -r ./local/dir/ user@hostname:/remote/
# SFTP commands in script
sftp user@hostname << EOF
cd /remote/path
put localfile.txt
get remotefile.txt
ls -la
bye
EOF
# SFTP with key and port
sftp -P 2222 -i ~/.ssh/mykey user@hostname
# Mount remote directory via SSHFS
# Install: apt-get install sshfs
sshfs user@hostname:/remote/path /local/mountpoint
fusermount -u /local/mountpoint  # Unmount

Rsync over SSH

#!/bin/bash
# Sync directory over SSH
rsync -avz -e ssh /local/dir/ user@hostname:/remote/dir/
# With specific port
rsync -avz -e 'ssh -p 2222' /local/dir/ user@hostname:/remote/dir/
# With identity file
rsync -avz -e 'ssh -i ~/.ssh/mykey' /local/dir/ user@hostname:/remote/dir/
# Incremental backup
rsync -avz --delete -e ssh /source/ user@hostname:/backup/
# Resume interrupted transfer
rsync -avzP -e ssh largefile.iso user@hostname:/remote/

6. SSH Options and Security

Common SSH Options

#!/bin/bash
# Connection options
ssh -o ConnectTimeout=10 user@hostname
ssh -o ConnectionAttempts=3 user@hostname
ssh -o ServerAliveInterval=60 user@hostname
ssh -o ServerAliveCountMax=3 user@hostname
# Authentication options
ssh -o PasswordAuthentication=no user@hostname
ssh -o PubkeyAuthentication=yes user@hostname
ssh -o IdentitiesOnly=yes -i ~/.ssh/key user@hostname
ssh -o PreferredAuthentications=publickey user@hostname
# Host key checking
ssh -o StrictHostKeyChecking=no user@hostname
ssh -o UserKnownHostsFile=/dev/null user@hostname
ssh -o GlobalKnownHostsFile=/dev/null user@hostname
# Logging and debugging
ssh -o LogLevel=DEBUG user@hostname
ssh -o LogLevel=QUIET user@hostname
# Compression and performance
ssh -o Compression=yes user@hostname
ssh -o CompressionLevel=9 user@hostname
ssh -o [email protected] user@hostname
# Multiplexing (reuse connection)
ssh -o ControlMaster=auto -o ControlPath=~/.ssh/ctl/%r@%h:%p user@hostname
# Escape character
ssh -o EscapeChar='~' user@hostname
# Combine multiple options
ssh -o "ConnectTimeout=5" -o "PasswordAuthentication=no" user@hostname

Security Best Practices

#!/bin/bash
# 1. Disable root login (server side)
# In /etc/ssh/sshd_config:
# PermitRootLogin no
# 2. Use key-based authentication only
# PasswordAuthentication no
# 3. Limit users who can SSH
# AllowUsers user1 user2
# AllowGroups sshusers
# 4. Use strong ciphers and MACs
ssh -o Ciphers="[email protected],[email protected]" \
-o MACs="[email protected]" user@hostname
# 5. Set idle timeout
ssh -o ClientAliveInterval=300 -o ClientAliveCountMax=0 user@hostname
# 6. Disable forwarding if not needed
ssh -o AllowAgentForwarding=no -o AllowTcpForwarding=no user@hostname
# 7. Use SSH certificates
ssh-keygen -s ca_key -I user_id -n username -V +52w user_key.pub
# 8. Implement two-factor authentication
# Install google-authenticator on server
# In sshd_config:
# AuthenticationMethods publickey,keyboard-interactive
# 9. Log all SSH connections
# In sshd_config:
# LogLevel VERBOSE
# 10. Use fail2ban to block brute force
# apt-get install fail2ban

7. SSH Escape Sequences

Using Escape Characters

#!/bin/bash
# SSH escape sequences (default ~)
# Type ~ followed by a command
# ~. - Terminate connection (force quit)
# After typing ~, press . to disconnect
# ~^Z - Background SSH
# After ~, press Ctrl+Z to suspend
# ~? - List available escapes
# After ~, press ? to see help
# ~B - Send BREAK to remote system
# ~C - Open command line (for port forwarding)
# ~R - Request rekey
# ~V - Decrease verbosity
# ~v - Increase verbosity
# Example: Add port forward in existing session
# Type ~C to open command line
# -L 8080:localhost:80
# Check if escape character is working
echo "~?" | ssh user@hostname  # Won't work, must be interactive

8. SSH Jump Hosts

Connecting Through Bastion Hosts

#!/bin/bash
# Method 1: ProxyJump (modern)
ssh -J [email protected] [email protected]
# Method 2: ProxyCommand (traditional)
ssh -o ProxyCommand="ssh -W %h:%p [email protected]" \
[email protected]
# Method 3: Multiple jumps
ssh -J jump1,jump2,jump3 user@target
# With different users
ssh -J user1@jump1,user2@jump2 user3@target
# Using config file
cat >> ~/.ssh/config << EOF
Host target
HostName 10.0.1.100
User appuser
ProxyJump bastion
IdentityFile ~/.ssh/app_key
Host bastion
HostName bastion.example.com
User jumpuser
IdentityFile ~/.ssh/jump_key
EOF
# Now simply
ssh target
# With port forwarding through jump
ssh -J bastion -L 8080:localhost:80 target
# Script to find best route
find_route() {
local target="$1"
local gateways=("gw1.example.com" "gw2.example.com" "gw3.example.com")
for gw in "${gateways[@]}"; do
if nc -z -w 2 "$gw" 22 2>/dev/null; then
echo "Using gateway: $gw"
ssh -J "user@$gw" "$target"
return 0
fi
done
echo "No gateway reachable"
return 1
}

9. Automation with SSH

Expect Scripts (Use with caution)

#!/usr/bin/expect -f
# Automated SSH with password (not secure, avoid)
set timeout 10
set host [lindex $argv 0]
set user [lindex $argv 1]
set password [lindex $argv 2]
spawn ssh $user@$host
expect "password:"
send "$password\r"
interact
# Better: Use keys

SSH in Scripts

#!/bin/bash
# Run commands on multiple servers
for host in server{1..5}.example.com; do
ssh user@"$host" 'uptime; df -h /' &
done
wait
# Check service status on multiple servers
check_service() {
local service="$1"
shift
local hosts=("$@")
for host in "${hosts[@]}"; do
if ssh "$host" "systemctl is-active $service" >/dev/null 2>&1; then
echo "$host: $service is running"
else
echo "$host: $service is NOT running"
fi
done
}
# Parallel execution with xargs
seq 1 10 | xargs -P 5 -I {} ssh server{} 'hostname'
# Error handling
if ! ssh user@hostname 'test -f /important/file'; then
echo "File missing on remote host"
exit 1
fi
# Collect output
output=$(ssh user@hostname 'cat /var/log/app.log' 2>&1)
if [ $? -eq 0 ]; then
echo "Log content: $output"
else
echo "Failed to retrieve log: $output"
fi
# Check SSH availability
wait_for_ssh() {
local host="$1"
local timeout="${2:-60}"
local interval="${3:-5}"
local elapsed=0
while [ $elapsed -lt $timeout ]; do
if nc -z -w 2 "$host" 22 2>/dev/null; then
echo "SSH available on $host"
return 0
fi
sleep "$interval"
elapsed=$((elapsed + interval))
done
echo "Timeout waiting for SSH on $host"
return 1
}

10. SSH Tips and Tricks

Productivity Enhancements

#!/bin/bash
# 1. SSH aliases
alias dev='ssh dev.example.com'
alias prod='ssh prod.example.com'
# 2. Function to run on multiple hosts
run_on() {
local cmd="$1"
shift
for host in "$@"; do
echo "=== $host ==="
ssh "$host" "$cmd"
done
}
# Usage
run_on 'uptime' server1 server2 server3
# 3. Copy SSH key to multiple hosts
copy_ssh_key() {
local key="${1:-~/.ssh/id_rsa.pub}"
shift
for host in "$@"; do
ssh-copy-id -i "$key" "$host"
done
}
# 4. SSH with auto-completion
_ssh_complete() {
COMPREPLY=($(compgen -W "$(grep ^Host ~/.ssh/config | awk '{print $2}')" \
-- "${COMP_WORDS[COMP_CWORD]}"))
}
complete -F _ssh_complete ssh scp sftp
# 5. Quick SSH to last used host
alias lastssh='ssh $(history | grep -E "^ *[0-9]+ +ssh" | tail -1 | sed "s/^ *[0-9]* *ssh //")'
# 6. SSH with automatic retry
ssh_with_retry() {
local host="$1"
local max_attempts="${2:-5}"
local attempt=1
while [ $attempt -le $max_attempts ]; do
echo "Attempt $attempt to connect to $host"
if ssh "$host" exit 2>/dev/null; then
ssh "$host"
return 0
fi
sleep $((attempt * 2))
attempt=$((attempt + 1))
done
echo "Failed to connect after $max_attempts attempts"
return 1
}
# 7. Monitor SSH connections
watch_ssh() {
watch -n 1 'ss -tnp | grep :22'
}
# 8. Quick tunnel creation
tunnel() {
local local_port="$1"
local remote_host="$2"
local remote_port="$3"
local gateway="${4:-$REMOTE_GATEWAY}"
ssh -fN -L "$local_port:$remote_host:$remote_port" "$gateway"
echo "Tunnel created: localhost:$local_port -> $remote_host:$remote_port via $gateway"
}
# 9. SSH with environment variables
ssh user@hostname "FOO=bar command"
ssh user@hostname "export FOO=bar; command"
# 10. Preserve environment (use SendEnv on client, AcceptEnv on server)
# In ~/.ssh/config:
# Host *
#     SendEnv MYVAR
# On server in /etc/ssh/sshd_config:
# AcceptEnv MYVAR

Debugging SSH Issues

#!/bin/bash
# Verbose mode for debugging
ssh -vvv user@hostname
# Check SSH configuration
sshd -T  # On server
# Test authentication methods
ssh -o PreferredAuthentications=publickey user@hostname
ssh -o PreferredAuthentications=password user@hostname
# Check if host key matches
ssh-keygen -F hostname  # Check known_hosts
ssh-keygen -R hostname  # Remove host key
# Debug connection issues
debug_ssh() {
local host="$1"
echo "Testing connection to $host"
echo "1. DNS resolution:"
host "$host"
echo "2. Port 22 connectivity:"
nc -zv -w 5 "$host" 22
echo "3. SSH banner:"
echo -n | timeout 5 telnet "$host" 22 2>/dev/null | head -1
echo "4. SSH verbose connection:"
ssh -v -o ConnectTimeout=5 "$host" exit 2>&1 | tail -5
}
# Test SSH throughput
test_ssh_speed() {
local host="$1"
local size="${2:-100M}"
dd if=/dev/zero bs=1M count=100 2>/dev/null | \
ssh "$host" 'dd of=/dev/null' 2>&1 | tail -1
}

11. Advanced SSH Features

SSH Command Escaping

#!/bin/bash
# Complex command escaping
ssh user@hostname "echo 'Single quotes inside double quotes'"
ssh user@hostname 'echo "Double quotes inside single quotes"'
# Commands with pipes and redirections
ssh user@hostname 'cat /var/log/syslog | grep ERROR > /tmp/errors.txt'
# Commands with variables (local vs remote)
local_var="value"
ssh user@hostname "echo $local_var"  # Local variable expanded locally
ssh user@hostname 'echo $local_var'  # Remote variable (empty)
# Escaping for nested SSH
ssh user@host1 "ssh user@host2 'echo Hello from host2'"
# Here document for complex commands
ssh user@hostname << 'EOF'
for i in 1 2 3; do
echo "Count: $i"
if [ $i -eq 2 ]; then
echo "Special"
fi
done
EOF

SSH with Multiplexing

#!/bin/bash
# Enable multiplexing (reuse connection)
mkdir -p ~/.ssh/controlmasters
# In ~/.ssh/config:
cat >> ~/.ssh/config << EOF
Host *
ControlMaster auto
ControlPath ~/.ssh/controlmasters/%r@%h:%p
ControlPersist 10m
EOF
# Check active connections
ls -la ~/.ssh/controlmasters/
# Terminate master connection
ssh -O stop user@hostname
# Check status
ssh -O check user@hostname
# Force new connection
ssh -o ControlMaster=no user@hostname
# Manual master connection
ssh -M -S ~/.ssh/controlmasters/socket user@hostname
# Other sessions can use: ssh -S ~/.ssh/controlmasters/socket user@hostname

12. Integration with Other Tools

SSH in DevOps

#!/bin/bash
# Ansible uses SSH
ansible all -i inventory -m ping
# Git over SSH
git clone [email protected]:user/repo.git
# Rsync backup with SSH
rsync -avz -e ssh /data/ backup@server:/backup/
# Docker context over SSH
docker -H ssh://user@hostname ps
# Kubernetes with SSH tunnel
ssh -L 6443:localhost:6443 user@k8s-master &
kubectl get nodes
# Database backup over SSH
ssh user@db-server 'pg_dump database' > local_backup.sql
# Restore database over SSH
cat local_backup.sql | ssh user@db-server 'psql database'
# Monitor with SSH
watch -n 60 'ssh user@server "df -h /; free -m; uptime"'
# Distributed processing
for host in worker{1..10}; do
ssh "user@$host" 'cd /data && process.sh' &
done
wait

SSH Wrapper Functions

#!/bin/bash
# SSH wrapper with logging
logssh() {
local logfile="/tmp/ssh-$(date +%Y%m%d).log"
echo "$(date): ssh $*" >> "$logfile"
ssh "$@"
echo "$(date): exit code $?" >> "$logfile"
}
# SSH with timeout
timeout_ssh() {
local host="$1"
local timeout="${2:-5}"
shift 2
timeout "$timeout" ssh -o ConnectTimeout="$timeout" "$host" "$@"
}
# Parallel SSH with output handling
parassh() {
local cmd="$1"
shift
local hosts=("$@")
local pids=()
for host in "${hosts[@]}"; do
(
output=$(ssh "$host" "$cmd" 2>&1)
echo "[$host] $output"
) &
pids+=($!)
done
for pid in "${pids[@]}"; do
wait "$pid"
done
}
# SSH with automatic failover
failover_ssh() {
local primary="$1"
local secondary="$2"
shift 2
if nc -z -w 2 "$primary" 22 2>/dev/null; then
ssh "$primary" "$@"
else
echo "Primary down, using secondary"
ssh "$secondary" "$@"
fi
}
# Usage
# logssh user@hostname 'uptime'
# timeout_ssh slowhost 3 'uptime'
# parassh 'uptime' server1 server2 server3
# failover_ssh primary.example.com backup.example.com 'uptime'

Conclusion

The ssh command is an essential tool for secure remote access and system administration:

Key Takeaways

  1. Secure Communication: All traffic is encrypted
  2. Multiple Authentication Methods: Keys, passwords, certificates
  3. Port Forwarding: Create secure tunnels for any protocol
  4. File Transfer: Built-in SCP and SFTP
  5. Configuration: Flexible client configuration
  6. Jump Hosts: Connect through bastion servers
  7. Automation: Scriptable for system management
  8. X11 Forwarding: Run GUI apps remotely
  9. Agent Forwarding: Forward credentials securely
  10. Integration: Works with many tools

Security Best Practices

  1. Use key-based authentication instead of passwords
  2. Disable root login remotely
  3. Use strong ciphers and MACs
  4. Limit user access with AllowUsers
  5. Set idle timeouts to close inactive sessions
  6. Use SSH certificates for large deployments
  7. Implement two-factor authentication
  8. Log and monitor SSH connections
  9. Use fail2ban to prevent brute force
  10. Keep SSH updated to latest version

Productivity Tips

  1. Use SSH config file for shortcuts
  2. Enable multiplexing for faster connections
  3. Create aliases for frequently used hosts
  4. Use jump hosts with ProxyJump
  5. Master escape sequences for session management
  6. Automate with scripts for repetitive tasks
  7. Use SSH agent for key management
  8. Create tunnels for secure service access
  9. Combine with rsync for efficient transfers
  10. Test connectivity before critical operations

SSH is the foundation of secure remote access in Unix/Linux environments, and mastering it is essential for system administrators, developers, and anyone working with remote systems.

Leave a Reply

Your email address will not be published. Required fields are marked *


Macro Nepal Helper