Automating Telnet Session Using Bash Scripts

Automating telnet session using bash scripts

Write an expect script.

Here is an example:

#!/usr/bin/expect

#If it all goes pear shaped the script will timeout after 20 seconds.
set timeout 20
#First argument is assigned to the variable name
set name [lindex $argv 0]
#Second argument is assigned to the variable user
set user [lindex $argv 1]
#Third argument is assigned to the variable password
set password [lindex $argv 2]
#This spawns the telnet program and connects it to the variable name
spawn telnet $name
#The script expects login
expect "login:"
#The script sends the user variable
send "$user "
#The script expects Password
expect "Password:"
#The script sends the password variable
send "$password "
#This hands control of the keyboard over to you (Nice expect feature!)
interact

To run:

./myscript.expect name user password

Sending Commands through Telnet via Bash Script

I solved this problem by expecting the bash again after I send my command.

When ran like this:

send "password\r"
expect "*$*"
send "ls\r"

The telnet session immediately ended. What ended up working was to expect the start of the bash script again. Because the script ends after it sends the last command, it doesn't have a chance to display the result of the command entered.

I addressed this by adding an additional expect which then allowed my command to process and get the results.

Here is my final code.

#!/usr/bin/expect
spawn telnet localhost
set timeout 10
expect "debian login"
send "test\r"
expect "Password:"
send "password\r"
expect "*$*"
send "ls\n"
expect "*$*"
send "command2"
expect "*$*"
send "command3"
expect "*$*"
send "exit\r"

Creating a script for a Telnet session?

Expect is built for this and can handle the input/output plus timeouts etc. Note that if you're not a TCL fan, there are Expect modules for Perl/Python/Java.

EDIT: The above page suggests that the Wikipedia Expect entry is a useful resource :-)

Scripting telnet mailing

Redirect to telnet a here-document:

mail_sender ()
{
echo " - FROM : "
read from
echo " - TO : "
read to
echo " - Subject : "
read subject
echo " - Message : "
read message
telnet localhost 25 << EOF
ehlo triton.itinet.fr
mail from: $from
rcpt to: $to
data
subject: $subject
$message
.
EOF
}

The content of the here-document will be redirected to telnet, effectively executing these SMTP commands in the mail server's shell.

It's important that the lines within the here-document don't have any indentation at all (no spaces or tabs at the start of the lines).
Notice that the indentation looks kind of broken in the way I wrote it above, halfway in mail_sender. It has to be this way,
because that's how here-documents work.

You can read more about here-documents and input redirection in man bash.



Related Topics



Leave a reply



Submit