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