22858 total geeks with 3297 solutions
Recent challengers:
best bread maker
 Welcome, you are an anonymous user! [register] [login] Get a yourname@osix.net email address 

Articles

GEEK

User's box
Username:
Password:

Forgot password?
New account

Shoutbox
sefo
anilg, new comments are deleted automaticall y because of some abuse recently
anilg
this is plain wierd. I submitted comments twice to article 950, and they dont seem to be there. Something wrong with the comment code?
CodeX
shout-boxes in general are old + the staff thing happened to everyone after an issue 2 months ago
anilg
/me is no longer staff :(
anilg
Also, osix's shoutbox predated twitter. Heh.

Donate
Donate and help us fund new challenges
Donate!
Due Date: Jul 31
July Goal: $40.00
Gross: $0.00
Net Balance: $0.00
Left to go: $40.00
Contributors


News Feeds
The Register
UK.gov sticks to IE
6 cos it"s more
"cost effective",
innit
T-Mobile UK pumps
out the iPhone 4
Polaroid 300
instant print
camera
NatWest dumps O2
Money
YouTube ups video
time limit
Alleged expenses
fiddlers to face
justice
Nude trampolinist
bounces free from
court
Nexus One phone
rockets to 28,000ft
UK.gov drops £6m on
Google
Fake Firefox update
used to sling
scareware
Slashdot
British ISPs Favour
Well-Connected
Customers
"Bizarre"
Nanobubbles Found
In Strained
Graphene
1-in-1,000 Chance
of Asteroid Impact
In
...
2182?
2 Chinese ISPs
Serve 20% of World
Broadband Users
World"s Fastest
Hybrid OK"d For
Production
Sometimes It"s OK
To Steal My Games
Thermoelectrics
Could Let You Feel
the Heat In Games
KDE SC 4.7 May Use
OpenGL 3 For
Compositing
Perl 6, Early, With
Rakudo Star
Internal Costs Per
Gigabyte —
What Do You Pay?
Article viewer

Simple Telnet Automation Using Expect



Written by:dimport
Published by:thinkt4nk
Published on:2003-06-21 07:19:46
Topic:Linux
Search OSI about Linux.More articles by dimport.
 viewed 80515 times send this article printer friendly

Digg this!
    Rate this article :
This is a nice simple bash shell script to automate and test telnet servers, it's a nice script and well commented. Hope you enjoy, all comments welcome.



Think your a GEEK? Prove it on the Geek Challenges




Explanation of Code (Bash Shell)

The code works by the user entering an argument, this argument could be either
-a, -h, or a server nickname. The -a argument would cause the bash shell to
log in and out of every server located in the autotelrc file, using the usernames
and passwords provided. The -h argument would bring up a small help message.
The code written is heavily commented but some parts deserve some explanation
as to their rationale.

 if [ "z$1" == "z" ]; then
   echo "You didn't type a valid argument."


The z in front of the $1 argument is to tell if the user entered an argument
or not. If something isn't entered it returns just the z by itself and the error
echo occurs.
If this condition is not true then the script then proceeds to the else statement.
Under this statement is another if statement. This takes account for the -a,
-h and server nickname argument. The counter I has been initialised at 2, this
saves us a line of code, if I = 2 then we would have to use another cut to trim
off the hashes in the rc file. So just incrementing the counter by 1 helps us
here. If the -h argument is used then the if statement give echoes us the help
message, which explains the usage to the user. If the -a argument is used, then
the statement then proceeds to work it's way through the rc file and telnet
into each using the expect script (explained later) and then log out, this is
useful to a network administrator to test various telnet machines. If the user
specifies an argument with a server nickname then the script searches through
the rc file for the relevant line and telnets into it using the expect script.
The code used here was as follows.

 If [ $1 == $Nickname ]; then
   ./telExpect.exp $Machine $Username $Password
   Fi #finish if statement


This was chosen instead of using the getops because it is much shorter code,
and in searching a small file there is not much performance difference.

Code Explained (Expect Script's)

There are two expect scripts, one to telnet in and out of every server and
the other to telnet in and give control to the user.
Firstly we set the timeout in the script to 20 seconds, this means that if everything
else goes wrong the program will exit after 20 seconds. We then set the variables
used in the script, which would be passed in as arguments from the bash script.
These arguments are the name of the server the user (username) and the password
of the server. What the script then does is spawn the telnet program then connect
to the server which is the name variable and then wait or expect the response
"login:" it would then send the user (username) variable. It then
waits for the "Password:" prompt and then sends the password variable.
Once this has occurred, the expect script then uses the interact feature, which
hands keyboard control over to the user.

The second script is identical to the first but it sends "exit" once
the machine has accepted the login, this is to test each computer.

Note Remember to create the autotelrc file.

The Code (Bash Script)

#!/bin/sh #Where the script is run from
 
Chmod 600 #only owner can read/write
 
 if [ "z$1" == "z" ]; then #if the argument is null
 
 echo "You didn't type a valid argument." #echo an error msg
 
 else #otherwise perform the next set of if statements
 
 if [ $1 == "-h" ]; then #if the argument is -h
 
 
echo " Usage ./autotel [-a] [-h] Nickname" #echo the usage msg.
   echo "-a - Attempts to log on to each telnet server in file autotelrc and
  then exits."
   echo "-h - Displays this help message."
   echo "nickname - Telnets server using the username and password provided
  in the telnetrc file"
 
 elif [ $1 == "-a" ]; then #if the argument is -a
 
 n=`wc -l autotelrc | cut -b 0-7` #counts the number of lines in autotelrc
   i=2 #Makes the counter start at 2, this stops it from reading the first comment
  line
   
   while [ $i -le $n ] #while we still have lines to go through in the file
   
   do #do the following
   
   line=`head -$i autotelrc | tail -1` #The line used in the following loop
 
 Machine=`echo $line | cut -d' ' -f1` #initialising the Machine variable
 
 Username=`echo $line | cut -d' ' -f2` #initialising the Machine variable
 
 Password=`echo $line | cut -d' ' -f3` #initialising the Machine variable
 
 ./telExpect.exp $Machine $Username $Password #run the expect script with the
  arguments provided
   
   sleep 21 #sleep for 21 seconds to allow script to logout or timeout.
 
 i=`expr $i + 1` #increment counter
   
   done #end while loop
 
 else #wildcard else
 
 n=`wc -l autotelrc | cut -b 0-7` #counts the number of lines in autotelrc
   i=2 #Makes the counter start at 2, this stops it from reading the first comment
  line
   
   while [ $i -le $n ] #while we still have lines to go through in the file
   
   do #do the following
   
   line=`head -$i autotelrc | tail -1` #The line used in the following loop
 
 Machine=`echo $line | cut -d' ' -f 1` #initialising the Machine variable
 
 Username=`echo $line | cut -d' ' -f 2` #initialising the Machine variable
 
 Password=`echo $line | cut -d' ' -f 3` #initialising the Machine variable
 
 Nickname=`echo $line | cut -d' ' -f 4` #initialising the Machine variable
 
 if [ $1 == $Nickname ] #if the argument matched the nickname
   
   then #then do the following
   
   ./telExpect1.exp $Machine $Username $Password #run second expect script
 
 
 fi #finish if statement
 
 
   
   i=`expr $i + 1` #increment counter
   
   done #end while loop
   fi #finish if statement
   fi #finish if statement
   
   exit 0 #exit


Expect Script 1

#!/usr/bin/expect #Where the script should be run from.
   Chmod 600 #only owner can read/write
   set timeout 20 #If it all goes pear shaped the script will timeout after 20
  seconds.
   set Machine [lindex $argv 0] #First argument is assigned to the variable name
   set Username [lindex $argv 1] #Second argument is assigned to the variable user
   set Password [lindex $argv 2] #Third argument is assigned to the variable password
   spawn telnet $Machine #This spawns the telnet program and connects it to the
  variable name
   expect "login:" #The script expects login
   send "$Username " #The script sends the user variable
   expect "Password:" #The script expects Password
   send "$Password " #The script sends the password variable
   interact #This hands control of the keyboard over two you
 


Expect Script 2

  #!/usr/bin/expect #Where the script should be run from.
   set timeout 20 #If it all goes pear shaped the script will timeout after 20
  seconds.
   set Machine [lindex $argv 0] #First argument is assigned to the variable name
   set Username [lindex $argv 1] #Second argument is assigned to the variable user
   set Password [lindex $argv 2] #Third argument is assigned to the variable password
   spawn telnet $name #This spawns the telnet program and connects it to the variable
  name
   expect "login:" #The script expects login
   send "$Username" #The script sends the user variable
   expect
"Password:" #The script expects Password
   send "$Password" #The script sends the password variable
   send "quit" #log out of server.
 
 



This article was originally written by Sliptop

Did you like this article? There are hundreds more.

Comments:
biffta
2005-05-06 10:45:43
I couldn't get the expect scripts to work. Errors trying to set the variables at the start. I notice this is quite an old post, maybe doesnt work with new version.
Anonymous
2007-07-20 16:32:08
try lrange instead of lindex:
set password [lrange $argv 0 0]
set ipaddr [lrange $argv 1 1]
Anonymous
2008-01-09 14:04:44
I'm trying to use this to login to approx 600 routers, give the same command on each one, get the results and store the results for each one in a unique file based on its ip/hostname. But each router will have a different prompt (of their hostname). Any idea how to do this?
Anonymous
2008-05-07 19:52:45
in the sample above, expect "Password:" could have also been coded as expect "word:"

Hopefully there is something consistent about the last prompt character that you could key on...

another thought... use the uname command to add a consistent character to the prompt?

Anonymous
2009-03-27 15:44:11
You need a "\r" in the send command. i.e.:
send "$Password\r"
Anonymous
2009-04-22 14:29:48
I'm trying to use this to login to approx 600 routers, give the same command on each one, get the results and store the results for each one in a unique file based on its ip/hostname. But each router will have a different prompt (of their hostname). online games
Anonymous
2009-06-10 02:06:51
Everything here ties in strongly to the current state of the anti-spyware economy. It's clear that norton 360 3.0 2 year subscription coupon codes and voucher codes are the best way to save money these days on the internet. It's becoming increasingly clear that free downloading of pc tools is a major element when assessing the money saving value of PC Tools Anti Spyware. The same concerns come into play with the coupon codes and symantec norton 360 antivirus voucher codes seen in Norton 360 3.0 Voucher which is why saving money with coupon codes and voucher codes is so important these days for pc tools promotional discounts with norton 360. Make sure to consider resource discount voucher before going.
Anonymous
2010-01-02 23:32:35

Thank you, you answered the question I have been searching for which was whether or not to place keywords when blog commenting.. http://www.hayda.net/
Anonymous
2010-02-10 10:00:28
I must say that this is a great post. I loved reading it. You have done a great job.
Laser Hair Removal New York City
Anonymous
2010-02-27 16:40:19
All the world's latest and most authoritative website with all kinds of uniforms. We are recognized worldwide network of sales jersey website. Here you can choose a variety of uniforms such as MLB jerseys, NFL jerseys, NHL jerseys and NBA jerseys. Professional security identification products with credit guarantee, first-class quality and reasonable prices!
--Lin Guowang
Anonymously add a comment: (or register here)
(registration is really fast and we send you no spam)
BB Code is enabled.
Captcha Number:


Blogs: (People who have posted blogs on this subject..)
bb
start svn on system boot in debian on Tue 21st Jul 10am
http://linux.justinhartman.com/Startup_S cript_for_Subversion I found this a really simple explanation of how to start svn when the server boots
bb
SSHFS: Super Easy File Access over SSH on Wed 18th Feb 1pm
This was really useful, and worked great to communicate between servers. http://www.linuxjournal.com/article/8904 Thanks to gabbs
bb
hellanzb nzb news downloader for NSLU2 on Tue 22nd May 7pm
Someone introduced me to the joyful NZB file recently. Its truly a wonderful invention, and allows my to explore usenet binary grabbing using my NSLU2. as previous nntp readers id tried made the process too painful. So simply .... 1) apt-get inst
bb
edna mp3 streaming for nslu2 on Wed 9th May 11am
I've been streaming music from my home NSLU2 server for a while now using mt-daapd (firefly) which is an ITunes server for linux. I can connect to my home network from work using ITunes and a little daap proxy app called rendevous. My friend was doing
Adnurak
How to choose the right Linux Distro on Thu 9th Nov 7pm
This is mainly for new users who want to try out Linux for the first time, but try it out if you're experienced in Linux anyway, it's kinda fun. What with all these different distributions of Linux that you hear about all the time, it's hard to choose
ketan404
my blog on Thu 9th Nov 6am
http://ketan404.blogspot.com
bb
Tweaking Apache and Mysql for Low Memory on Fri 20th Oct 11am
i implemented this to tweak my apache/mysql for better performance on my NSLU2. Hard to tell if its helping much though ;-) Mysql really doesnt run too well with apache on NSLU2 so I dont use it for much. http://www.unixshell.com/wiki/index.php/ Optimiz
Adnurak
Fate - A Linux Security Simulation Written in C++ on Fri 20th Oct 6am
Fate is a simulation of a Linux system written in C++ and meant for DOS (runs fine in winxp and winme by just doubleclicking) that according to the creator, m101, shows you the basics of security in different Linux systems, including but not limited to, M
bb
Article on building rtorrent for arm5vtel NSLU2 with debianslug on Thu 19th Oct 7am
I wrote an article today on my efforts at compiling rtorrent for debianslug. its here ... Article on building rtorrent/libtorrent for arm5vtel NSLU2 with littleendian debianslug
bb
How to mount .iso file on NSLU2 running debianslug on Tue 19th Sep 12pm
If like me your running debianslug on an NSLU2 and you'd like to mount an iso file so it can be directly streamed to Xbox Media Centre (its a beautiful solution isnt it!) then simply do the following. Ensure you have loop support in your debianslug k

Test Yourself: (why not try testing your skill on this subject? Clicking the link will start the test.)
Linux Test Simple by a13x4nd7u

This is a simple Linux commands test.
Linux Quiz by abhijangda

Trivia about your favorite OS
Linux Administration by typedeaF

Testing your knowledge of Linux administration tools, very light shell scripting, and good high level understanding of how the OS works at the user level. Anyone who has worked with Linux for 1-3 years should do good.
Linux Commands (Part 1) by nirus

If you think you know the linux command-line then this test is for you. For reference purposes, it is based on Debian/GNU Linux with a BASH Shell.


     
Your Ad Here
 
Copyright Open Source Institute, 2006