21929 total geeks with 3247 solutions
Recent challengers:
 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
redore
o noes the webserver was acting up earlier and it was spewing out all those full path disclosures ..
DnD
Tks, I'm checking my code.
CodeX
are you thinking of level 4? I'm sure there's been plenty of people who were dismayed after calculating the answer
MaxMouse
Also... Level5 lol, when you get the answer you'll shout at your computer, guaranteed.
MaxMouse
DnD, none of the challenges have been changed in a long time, i can assure you, none of them have a bug (Except level13, and it's more of a quirk than a bug)

Donate
Donate and help us fund new challenges
Donate!
Due Date: Feb 28
February Goal: $30.00
Gross: $0.00
Net Balance: $0.00
Left to go: $30.00
Contributors


News Feeds
The Register
Ex-Intel exec
pleads guilty to
insider trading
Adobe apologizes
for festering Flash
crash bug
Conficker outbreak
infects Leeds
hospital servers
Intel
"Tukwila" born
after long and
painful labor
SourceForge
reverses ban on US
foes
Oracle issues
emergency security
patch for WebLogic
Microsoft tests
show no Win 7
battery flaw
Microsoft kills
FAST"s Linux and
Unix search biz
Linus Torvalds
doesn"t hate the
Googlephone
Sweden to prosecute
alleged Cisco, NASA
hacker
Slashdot
Virtualizing a
Supercomputer
Study Says OOXML
Unsuitable For
Norwegian
Government
Virus-Detecting
"Lab On a Chip"
Developed At BYU
Google Shooting For
Smartphone
Universal
Translator
New Material
Transforms Car
Bodies Into
Batteries
Verizon Blocking
4chan
A Reflection On Sun
Executive Payouts
For Failure
Turns Out You
Actually Can Be
Bored To Death
Cacti 0.8 Network
Monitoring
What Are the Best
Valentine"s Day
Stunts?
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 70852 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:31:46

Thank you, you answered the question I have been searching for which was whether or not to place keywords when blog commenting.. <a href="http://www.hayda.net" title="mirc, cinsel sohbet, cinsellik, chat">mirc</a> . <a href="http://www.hayda.net" title="mirc, cinsel sohbet, cinsellik, chat">chat</a> . <a href="http://www.hayda.net" title="mirc sohbet, mirc, cinsel sohbet, cinsellik, chat">mirc sohbet</a>. <a href="http://www.hayda.net" title="chat sohbet, mirc, cinsel sohbet, cinsellik, chat">chat sohbet</a> . <a href="http://www.hayda.net" title="mirc, cinsel sohbet, cinsellik, chat">cinsel sohbet</a> . <a href="http://www.hayda.net" title="cinsellik sohbet, mirc, cinsel sohbet, cinsellik, chat">cinsellik sohbet</a> . <a href="http://www.hayda.net" title="mirc indir, mirc, cinsel sohbet, cinsellik, chat">mirc indir</a> . <a href="http://www.hayda.net" title="ask sohbet, mirc indir, mirc, cinsel sohbet, cinsellik, chat">ask sohbet</a> . <a href="http://www.hayda.net" title="sicak sohbet, mirc indir, mirc, cinsel sohbet, cinsellik, chat">sicak sohbet</a> .
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-06 00:34:34
http://www.legerdress.com/ herve leger dresses
JamesPaul
2010-02-08 08:13:53

Your blog is very nice. I m really impressed .I m waiting for your next post. Hopefully I will get it soon.
Printing
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.

Related Links:
Ubuntu 5.10, Is Linux Ready for the Desktop?
So, Ive been running Ubuntu 5.10 since 2005-10-13, and I have a few thoughts on it.Thus far, my conclusion stands. Ubuntu is Debian with a lot of the sharp edges rounded off. And it just gets better with each release, really...
Software makers to send out network patrols
Symantec gets set to launch new intrusion detection software, as rival McAfee adds Linux support to its own corpo product...
Building a Linux Virtual Server
prostoalex writes NewsForge (an OSTG site) has an article that discusses the details of building a cluster for a virtual server - an environment where one can add and remove machines as needed, to account for high-traffic Web site of intensive databa..
Test Driving Linux
Michael J. Ross writes As Windows users hear more about Linux, they may be intrigued to give it a try, if only to learn what the buzz is about. But a major hurdle, possibly the most daunting, is how to obtain and install Linux on their PCs without di..
Mandriva Linux Security Update Advisory - wget (MDKSA-2005:098)
..
Windows to Have Better CLI
MickyJ writes The command line interface to the Windows Server OS will be changed to the new Monad Shell (MSH), in a phased implementation to take place over the next three to five years. It will exceed what has been delivered in Linux and Unix for m..
Linux Desktop Must Work to Head Off Straying Users
Opinion: You can talk all you want about how Mactels arent going to be that wonderful, but if you want to see many enterprise Linux desktops around in 2007, start making it happen...
Debian drops ball on security updates
The newly launched Linux distribution has been hit by a glitch--some versions were released with default security updates turned off...
Juggling Molecules with Linux
An anonymous reader writes This article at LinuxDevices.com describes an interesting project at the University of Vermont in which researchers use real-time Linux to build a laser trap that manipulates individual molecules by means of a computer-cont..
Could Apples Intel Desktop Threaten Linux?
esavard writes If Linux enthousiasts dont want Mac OSX on Intel to become a threat for the future of Linux Desktop, they must rethink the concept of Desktop has we know it today. Symphony OS did exactly that and propose some fresh concepts about how..
[?????] chmod 101
Unix 101
Configuring Tripwire
Guide to chmod


     
Your Ad Here
 
Copyright Open Source Institute, 2006