2
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
3
# See LICENSE for details.
7
An example of using the FTP client
11
from twisted.protocols.ftp import FTPClient, FTPFileListProtocol
12
from twisted.internet.protocol import Protocol, ClientCreator
13
from twisted.python import usage
14
from twisted.internet import reactor
16
# Standard library imports
20
from cStringIO import StringIO
22
from StringIO import StringIO
25
class BufferingProtocol(Protocol):
26
"""Simple utility class that holds all data written to it in a buffer."""
28
self.buffer = StringIO()
30
def dataReceived(self, data):
31
self.buffer.write(data)
33
# Define some callbacks
35
def success(response):
36
print 'Success! Got response:'
41
print string.join(response, '\n')
46
print 'Failed. Error was:'
49
def showFiles(result, fileListProtocol):
50
print 'Processed file listing:'
51
for file in fileListProtocol.files:
52
print ' %s: %d bytes, %s' \
53
% (file['filename'], file['size'], file['date'])
54
print 'Total: %d files' % (len(fileListProtocol.files))
56
def showBuffer(result, bufferProtocol):
58
print bufferProtocol.buffer.getvalue()
61
class Options(usage.Options):
62
optParameters = [['host', 'h', 'localhost'],
64
['username', 'u', 'anonymous'],
65
['password', None, 'twisted@'],
74
config.opts['port'] = int(config.opts['port'])
75
config.opts['passive'] = int(config.opts['passive'])
76
config.opts['debug'] = int(config.opts['debug'])
79
FTPClient.debug = config.opts['debug']
80
creator = ClientCreator(reactor, FTPClient, config.opts['username'],
81
config.opts['password'], passive=config.opts['passive'])
82
creator.connectTCP(config.opts['host'], config.opts['port']).addCallback(connectionMade).addErrback(connectionFailed)
85
def connectionFailed(f):
86
print "Connection Failed:", f
89
def connectionMade(ftpClient):
90
# Get the current working directory
91
ftpClient.pwd().addCallbacks(success, fail)
93
# Get a detailed listing of the current directory
94
fileList = FTPFileListProtocol()
95
d = ftpClient.list('.', fileList)
96
d.addCallbacks(showFiles, fail, callbackArgs=(fileList,))
98
# Change to the parent directory
99
ftpClient.cdup().addCallbacks(success, fail)
102
proto = BufferingProtocol()
104
# Get short listing of current directory, and quit when done
105
d = ftpClient.nlst('.', proto)
106
d.addCallbacks(showBuffer, fail, callbackArgs=(proto,))
107
d.addCallback(lambda result: reactor.stop())
110
# this only runs if the module was *not* imported
111
if __name__ == '__main__':