Thursday, October 8, 2009

[Level 2] How to run commands at remote server through telnet client.


Today, someone ask me, "How to run commands at remote server through telnet client?"
So I write a sample code for him and also share for you.

Wish this helps.

regards,
Stanley Huang

################################################

#!/usr/bin/bash

showUsage() {
  cat<<EOF
Usage:
  $0 host [user] [pwd] [sleep_sec] [cmd_file]
Ex.
  $0 localhost root root123 3 $0.cmd
  $0 localhost root root123 3
  $0 localhost root root123
  $0 localhost root
  $0 localhost
PS.
  Default values:
  user=root
  pwd=root123
  sleep_sec=3
  cmd_file=$0
EOF
}
################################## main
sGrep="^#[$] " # default grep filter

sHost=$1  && [ -z $sHost   ] && showUsage && exit 1 # sHost=b1500-16
sUsr=$2   && [ -z $sUsr    ] && sUsr=root           # whoami
sPwd=$3   && [ -z $sPwd    ] && sPwd=root123        # passwd
sSleep=$4 && [ -z $sSleep  ] && sSleep=3
sCmdF=$5  && [ -z "$sCmdF" ] && sCmdF="$0"

sCmdList="`grep "$sGrep" $sCmdF`"
sCmdList="$sUsr:$sPwd:`echo $sCmdList| sed -e 's/[ ]*#[$][ ]*/:/g'`:sleep $sSleep"
#echo $sCmdList
#exit

# IFS must put here
IFS=:
echo "Command Begin ($0) :: `date '+%Y/%m/%d %H:%M:%S'`"
for sCmd in $sCmdList
do
  sleep $sSleep
  echo $sCmd
done | telnet $sHost
echo "Command End   ($0) :: `date '+%Y/%m/%d %H:%M:%S'`"

exit 0
exit 0

######################### command line : by pattern : #$ command
######################### you can copy follow lines to a command file.
#$ uname -n
#$ #ls -ltr;
#$ id;
#$ pwd;
#$ exit;