Python : Using Pexpect: ftpTest.py

Here’s a sample Python/Pexpect script, which is called by the bash script in the previous page.

Note how the spawn function runs the command you supply as the argument, in this case “ftp ftp.ubuntu.com”.

#!/usr/bin/python

# Connects to a public ftp server, downloads a file

import pexpect
import sys
child = pexpect.spawn('ftp ftp.ubuntu.com')
child.logfile = sys.stdout
child.expect('Name')
child.sendline('anonymous')
child.expect('Password')
child.sendline('anonymous')
child.expect('ftp>')
child.sendline('cd /ubuntu/dists/xenial')
child.expect('ftp>')
child.sendline('get InRelease')
child.expect('ftp>')
child.sendline('quit')

You can insert working Python code anywhere in this chain, for instance if you need to handle multiple conditions with “if” statements.