Friday, March 21, 2014

The Unix Tip of the Day - Running Commands remotely using ssh

Today we will create a small script that will allow us to run one or more commands on multiply Unix/Linux servers ..

List of Commands / Tools :

SSH :    (SSH client) is a program for logging into a remote machine and
for executing commands on a remote machine.  It is intended to replac
rlogin and rsh, and provide secure encrypted communications between
two untrusted hosts over an insecure network.  X11 connections and  
arbitrary TCP ports can also be forwarded over the secure channel.  

CAT :    cat reads each file in sequence and writes it on the standard output.

FOR :    for will allow us to run in loop until the end of input .

ECHO :  echo writes its arguments separated by blanks and terminated by a
new-line on the standard output

VI :   it's just a text editor

CHMOD :  The chmod command changes the permissions of one or more files
according to the value of symbolic_mode_list or numeric_mode



and the script :

#!/bin/ksh
for u in `cat "$1"`; do
echo "########################################"
echo "             working on $u"
echo "########################################"
ssh $u "$2"
done


save this script in a file , and give it run permissions :

1.  vi Run_My_Commands.sh

      a. click "i" , to start input mode .
     
      b. bust the script .

2.  chmod +x Run_My_Commands.sh


3. and that is it you can run the script like the following : " ./Run_My_Commands.sh  "


the script will get 2 argoments , the first one is a file contain list of users@hosts , and the second argument will be the commands the we willing to run ..

here is an example of the run :


the file_list of users :


the command run :   and here what i run :   ./Run_My_Commands.sh users.txt "ps -efl;bdf .;ls -lrt"



running this will give you the run of the commands :

a.  ps -efl
b.  bdf .
c.  ls -lrt

on all the users in the users.txt fiel .



No comments: