Python FTP upload using Twisted

Here’s a snippet for uploading a file via FTP using the Twisted Python library available from TwistedMatrix.

from twisted.protocols.basic import FileSender
from twisted.protocols.ftp import FTPClient
from twisted.internet.protocol import ClientCreator
from twisted.internet import reactor
 
def fileTransferFail(failure):
    failure.printTraceback()
    reactor.stop()
 
def cbStore(consumer, filename):
    fs = FileSender()
    d = fs.beginFileTransfer(open(filename, 'r'), consumer)
    d.addCallback(lambda _: consumer.finish()).addErrback(fileTransferFail)
    return d
 
def connectionMade(ftpClient, filename, uploadpath = None):
    if uploadpath is None:
        uploadpath = filename
    d1, d2 = ftpClient.storeFile(uploadpath)
    d1.addCallback(cbStore, filename).addErrback(fileTransferFail)
    d2.addCallback(lambda _: reactor.stop())
    return d2
 
def sendFile(host, port, username, password, filename, uploadpath):
    creator = ClientCreator(reactor, FTPClient, username, password)
    d = creator.connectTCP(host, port)
    d.addCallback(connectionMade, filename, uploadpath).addErrback(fileTransferFail)
    return d
 
if __name__ == '__main__':
    username = 'GoogleUser'
    password = 'GoogleSuperSecretPassword'
    host = 'google.com'
    port = 21
    filename = 'index.html'
    uploadto = '/public_html/index.html'
    sendFile(host, port, username, password, filename, uploadto)
    reactor.run()
Leave a comment

1 Comments.

Leave a Reply


[ Ctrl + Enter ]