In the world of Linux and Bash scripting, executing commands or scripts on remote systems is a common task. This can be achieved using Secure Shell (SSH), which provides secure encrypted communications between two untrusted hosts over an insecure network. In this tutorial, we will explore how to execute scripts on remote systems using SSH.
SSH allows you to connect to a remote server and run commands as if you were sitting in front of the server's console. This is particularly useful for automating tasks across multiple servers or managing configurations remotely.
You can execute a single command on a remote server using the following syntax:
Filesystem Size Used Avail Use% Mounted on /dev/sda1 20G 15G 4.6G 78% / tmpfs 938M 0 938M 0% /dev/shm
To execute a script on a remote server, you can use the following approach:
$ scp local_script.sh user@example.com:/path/to/remote/directory/
$ ssh user@example.com "/path/to/remote/directory/local_script.sh"
For secure and passwordless authentication, you can use SSH keys:
$ ssh-keygen -t rsa
$ ssh-copy-id user@example.com
$ ssh user@example.com "echo 'Hello, World!'"
SSH can also be used to forward ports, which is useful for accessing services running on remote servers:
$ ssh -L local_port:remote_host:remote_port user@example.com
For example, to forward port 8080 on your local machine to port 80 on a remote server:
$ ssh -L 8080:example.com:80 user@example.com
Now, you can access the service running on example.com:80 by visiting http://localhost:8080 on your local machine.
In the next section, we will explore Configuration Management tools like Ansible and Puppet, which provide more advanced capabilities for managing configurations across multiple servers.
By mastering remote execution with SSH, you'll be well-equipped to automate tasks and manage systems efficiently in a Linux environment.