0
0
Bash Scriptingscripting~5 mins

SSH automation in Bash Scripting

Choose your learning style9 modes available
Introduction
SSH automation helps you run commands on remote computers without typing passwords every time. It saves time and makes repetitive tasks easier.
You want to update software on many servers quickly.
You need to copy files to a remote machine regularly.
You want to check system status on a remote computer automatically.
You need to run backups on remote servers without manual login.
You want to automate deployment of code to remote machines.
Syntax
Bash Scripting
ssh user@remote_host 'command_to_run'

# For copying files:
scp local_file user@remote_host:/remote/path/
Replace user with your remote username and remote_host with the server address.
Commands inside single quotes run on the remote machine.
Examples
List files in Alice's home directory on the remote machine.
Bash Scripting
ssh alice@192.168.1.10 'ls -l /home/alice'
Copy the file report.txt to Bob's reports folder on the server.
Bash Scripting
scp report.txt bob@server.com:/home/bob/reports/
Run the uptime command on the remote server using a specific SSH key.
Bash Scripting
ssh -i ~/.ssh/id_rsa alice@192.168.1.10 'uptime'
Sample Program
This script logs into the remote server and runs the disk usage command to show free space on the root partition.
Bash Scripting
#!/bin/bash
# This script connects to a remote server and shows disk usage
REMOTE_USER="user"
REMOTE_HOST="192.168.1.100"

ssh ${REMOTE_USER}@${REMOTE_HOST} 'df -h /'
OutputSuccess
Important Notes
Set up SSH keys to avoid typing your password every time.
Use ssh-copy-id user@remote_host to copy your public key to the server easily.
Always test your commands manually before automating them.
Summary
SSH automation lets you run commands on remote machines without manual login.
Use SSH keys for passwordless and secure connections.
Automate tasks like file transfer, system checks, and updates easily.