Example of expect with ftp & telnet
In the past I’ve had the need to use expect, but it wasn’t exactly easy to get going, so I went back to something I was more familiar with. Eventually I had another need and finally got it going. Here are two examples of how to use expect.
Access an FTP server to upload a file. This is a daily job that was setup as follows:
#!/bin/sh
uname= h39dj31
passwd= jd83812
ip=172.16.247.36
# Opens ftp with auto-login turned off, and take input from the program until it sees EOF.
ftp -n << EOF
# Connects to IP address specified.
open $ip
# Turns passive mode off.
passive off
# Sends the user name and password in plain text!
user $uname $passwd
# ls’ a directory (you should be logged in by now.)
ls
# cd’s to specified directory.
cd daily-reports
# Uploads daily report.
send daily-report.csv
# Terminates ftp script/session.
EOF
Here’s the same script but using expect instead:
#!/bin/sh
uname= h39dj31
passwd= jd83812
ip=172.16.247.36
# Launches expect.
expect << EOF
# Starts ftp.
spawn ftp
# Connects to ftp server.
send “open $ip\r”
# Tells the program what to expect.”
expect :
# Sends the username.
send $uname\r
expect Password:
# Sends the password.
send $passwd\r
expect ftp>
# Sends a command.
send ls\r
expect ftp>
send “cd daily-reports\r”
expect ftp>
# Uploads daily report.
send daily-report.csv
send EOF\r
Here’s another example using expect, this is to connect to all cisco devices and get some info:
#!/bin/sh
uname= h39dj31
passwd= jd83812
ip=172.16.124.37
expect << EOF
spawn telnet $ip
expect Username:
send $uname\r
expect Password:
send $passwd\r
expect #
send “show version\r”
expect #
send quit\r
Some notes:
- You need to add the return character “\r” at the end of each command you send in expect.
- You only need to use double quotes “” in expect when you have a space in what’s send. For example, if you send ls you don’t need double quotes, but if you send “rm filename” then that will need to have double quotes.
Good luck!