A script a day will allow you some freedom to play and build other useful and more complicated scripts. Every day, I attempt to make my life easier—by this I mean, trying to stop doing the repetitive tasks. If a process is repeatable; it can be scripted and automated. The idea to automate everything is not new, but try automating a command on a remote host.
SSH is very flexible, and it comes with many options. My absolute favorite is
its ability to let you run a command on a remote server by passing the
flag. An example:
ssh -t firstname.lastname@example.org 'cat /etc/hosts'
ssh to webserver1.test.com, then run
/etc/hosts in your shell
and return the output.
For efficiency, you could create an ssh-key pair.
It's a simple process of creating a passwordless public and a private
keypair. To set this up, use
ssh-keygen, and accept the defaults ensuring you
leave the password blank:
ssh-keygen Generating public/private rsa key pair. Enter file in which to save the key (/home/adam/.ssh/id_rsa): y Enter passphrase (empty for no passphrase): LEAVE BLANK Enter same passphrase again: Your identification has been saved in y. Your public key has been saved in y.pub. The key fingerprint is: SHA256:jUxrQRObADE8ardXMT9UaoAcOcQPBEKGU622646P8ho ↪email@example.com The key's randomart image is: +---[RSA 2048]----+ |B*++*Bo.=o | |.+. | |=*= | +----[SHA256]-----+
Once completed, copy the public key to the target server. To do this, use
ssh-copy-id firstname.lastname@example.org /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/adam/.ssh/id_rsa.pub" /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), ↪to filter out any that are already installed /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if ↪you are prompted now it is to install the new keys email@example.com's password: ******** Number of key(s) added: 1
You will be asked for the password of the target server.
If you have set this up correctly, you won't be asked for your password
next time you
ssh to your target.
Execute the original example. It should be quicker now that you don't need to enter your password.
If you have a handful of servers and want to report
the running kernel versions, you can run
uname -r from the command line, but
to do this on multiple devices, you'll need a script.
Start with a file with a list of your servers, called server.txt, and then run your script to iterate over each server and return the required information: