1 #!/usr/bin/env python 2 3 """This demonstrates an FTP "bookmark". This connects to an ftp site; does a 4 few ftp stuff; and then gives the user interactive control over the session. In 5 this case the "bookmark" is to a directory on the OpenBSD ftp server. It puts 6 you in the i386 packages directory. You can easily modify this for other sites. 7 """ 8 9 import pexpect 10 import sys 11 12 child = pexpect.spawn('ftp ftp.openbsd.org') 13 child.expect('(?i)name .*: ') 14 child.sendline('anonymous') 15 child.expect('(?i)password') 16 child.sendline('pexpect (at] sourceforge.net') 17 child.expect('ftp> ') 18 child.sendline('cd /pub/OpenBSD/3.7/packages/i386') 19 child.expect('ftp> ') 20 child.sendline('bin') 21 child.expect('ftp> ') 22 child.sendline('prompt') 23 child.expect('ftp> ') 24 child.sendline('pwd') 25 child.expect('ftp> ') 26 print("Escape character is '^]'.\n") 27 sys.stdout.write (child.after) 28 sys.stdout.flush() 29 child.interact() # Escape character defaults to ^] 30 # At this point this script blocks until the user presses the escape character 31 # or until the child exits. The human user and the child should be talking 32 # to each other now. 33 34 # At this point the script is running again. 35 print 'Left interactve mode.' 36 37 # The rest is not strictly necessary. This just demonstrates a few functions. 38 # This makes sure the child is dead; although it would be killed when Python exits. 39 if child.isalive(): 40 child.sendline('bye') # Try to ask ftp child to exit. 41 child.close() 42 # Print the final state of the child. Normally isalive() should be FALSE. 43 if child.isalive(): 44 print 'Child did not exit gracefully.' 45 else: 46 print 'Child exited gracefully.' 47 48