109

I would like to make a script to upload a file to FTP.

How would the login system work? I'm looking for something like this:

ftp.login=(mylogin)
ftp.pass=(mypass)

And any other sign in credentials.

Tonechas
  • 13,398
  • 16
  • 46
  • 80
Frustrated Python Coder
  • 1,503
  • 3
  • 15
  • 15

7 Answers7

242

Use ftplib, you can write it like this:

import ftplib
session = ftplib.FTP('server.address.com','USERNAME','PASSWORD')
file = open('kitten.jpg','rb')                  # file to send
session.storbinary('STOR kitten.jpg', file)     # send the file
file.close()                                    # close file and FTP
session.quit()

Use ftplib.FTP_TLS instead if you FTP host requires TLS.


To retrieve it, you can use urllib.retrieve:

import urllib 

urllib.urlretrieve('ftp://server/path/to/file', 'file')

EDIT:

To find out the current directory, use FTP.pwd():

FTP.pwd(): Return the pathname of the current directory on the server.

To change the directory, use FTP.cwd(pathname):

FTP.cwd(pathname): Set the current directory on the server.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
K Z
  • 29,661
  • 8
  • 73
  • 78
  • 2
    @DawsonHensel You can use `print ftp.pwd()` will show you the current path you are at. – K Z Sep 29 '12 at 05:40
  • there is some strange behavior, I can ftp to my server from command line and upload file but not with ftplib , connection is just open for some time and then socket error is thrown. what could be the reason ? – 89n3ur0n May 14 '15 at 06:30
  • Hi, I want to know if it's possible to upload a folder using ftplib – vishruti Dec 21 '20 at 11:39
40

ftplib now supports context managers so I guess it can be made even easier

from ftplib import FTP
from pathlib import Path

file_path = Path('kitten.jpg')

with FTP('server.address.com', 'USER', 'PWD') as ftp, open(file_path, 'rb') as file:
        ftp.storbinary(f'STOR {file_path.name}', file)

No need to close the file or the session

gbonetti
  • 1,334
  • 17
  • 18
  • 2
    If anyone's having issues uploading a file from Windows to an FTP server using the accepted answer, this method worked for me. – mKane848 Feb 20 '20 at 21:44
  • I did have a problem using this to overwrite/update binary files on a remote FTP Server - but it works well with text files via ftp.storlines ... – Edward Nov 22 '20 at 00:57
9

You will most likely want to use the ftplib module for python

 import ftplib
 ftp = ftplib.FTP()
 host = "ftp.site.uk"
 port = 21
 ftp.connect(host, port)
 print (ftp.getwelcome())
 try:
      print ("Logging in...")
      ftp.login("yourusername", "yourpassword")
 except:
     "failed to login"

This logs you into an FTP server. What you do from there is up to you. Your question doesnt indicate any other operations that really need doing.

Tadgh
  • 1,999
  • 10
  • 23
8

Try this:

#!/usr/bin/env python

import os
import paramiko 
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('hostname', username="username", password="password")
sftp = ssh.open_sftp()
localpath = '/home/e100075/python/ss.txt'
remotepath = '/home/developers/screenshots/ss.txt'
sftp.put(localpath, remotepath)
sftp.close()
ssh.close()
bensiu
  • 24,660
  • 56
  • 77
  • 117
Anand Rajagopal
  • 1,593
  • 6
  • 24
  • 40
4

To avoid getting the encryption error you can also try out below commands

ftp = ftplib.FTP_TLS("ftps.dummy.com")
ftp.login("username", "password")
ftp.prot_p()
file = open("filename", "rb")
ftp.storbinary("STOR filename", file)
file.close()
ftp.close()

ftp.prot_p() ensure that your connections are encrypted

Shishir
  • 327
  • 3
  • 6
1

I just answered a similar question here IMHO, if your FTP server is able to communicate with Fabric please us Fabric. It is far better than doing raw ftp.

I have an FTP account from dotgeek.com so I am not sure if this will work for other FTP accounts.

#!/usr/bin/python

from fabric.api import run, env, sudo, put

env.user = 'username'
env.hosts = ['ftp_host_name',]     # such as ftp.google.com

def copy():
    # assuming i have wong_8066.zip in the same directory as this script
    put('wong_8066.zip', '/www/public/wong_8066.zip')

save the file as fabfile.py and run fab copy locally.

yeukhon@yeukhon-P5E-VM-DO:~$ fab copy2
[1.ai] Executing task 'copy2'
[1.ai] Login password: 
[1.ai] put: wong_8066.zip -> /www/public/wong_8066.zip

Done.
Disconnecting from 1.ai... done.

Once again, if you don't want to input password all the time, just add

env.password = 'my_password'
Community
  • 1
  • 1
CppLearner
  • 16,273
  • 32
  • 108
  • 163
  • 1
    Unless I'm missing something in fabrics documentation, fabric doesn't support FTP. You're probably in the lucky circumstance that dotgeek.com supports both SSH and FTP, using the same credentials. – Epcylon Jun 12 '14 at 19:55
  • @Epcylon Fabric supports SFTP - `While the SFTP protocol (which put uses)` [link](http://docs.fabfile.org/en/latest/api/core/operations.html#fabric.operations.put) – Alex L Nov 11 '14 at 07:31
  • 2
    @AlexL Correct, but SFTP is not in any way the same as FTP. They are two different protocols for the same purpose, but if you need to connect to an FTP-server, you can not use a SFTP-client, and vice versa.From [wikipedia](http://en.wikipedia.org/wiki/SSH_File_Transfer_Protocol): "SFTP is not FTP run over SSH, but rather a new protocol designed from the ground up by the IETF SECSH working group." – Epcylon Nov 11 '14 at 19:44
  • @Epcylon Yup! Just trying to clarify what Fabric uses. Hopefully the OP (or future readers) can SFTP into their servers rather than using FTP, fabric is pretty handy. – Alex L Nov 13 '14 at 01:43
-1

You can use the below function. I haven't tested it yet, but it should work fine. Remember the destination is a directory path where as source is complete file path.

import ftplib
import os

def uploadFileFTP(sourceFilePath, destinationDirectory, server, username, password):
    myFTP = ftplib.FTP(server, username, password)
    if destinationDirectory in [name for name, data in list(remote.mlsd())]:
        print "Destination Directory does not exist. Creating it first"
        myFTP.mkd(destinationDirectory)
    # Changing Working Directory
    myFTP.cwd(destinationDirectory)
    if os.path.isfile(sourceFilePath):
        fh = open(sourceFilePath, 'rb')
        myFTP.storbinary('STOR %s' % f, fh)
        fh.close()
    else:
        print "Source File does not exist"
Debasish Mitra
  • 1,394
  • 1
  • 14
  • 17