Search code examples
pythonpython-3.xloggingftpftplib

Python ftplib fails during FTP


Problem: I need to open a ftp connection from a python script to an android ftp-server. I get the following error:

ConnectionResetError: [Errno 104] Connection reset by peer

The error stacktrace is given at the bottom.

Here is my Python script:

import ftplib
try:
      logger.info(ftp_ip+ftp_port)
      FTP=ftplib.FTP()
      ftp_msg=FTP.connect(host=ftp_ip, port=2221)
      logger.info("Message: "+ftp_msg)
      ftp_msg=FTP.login(user=ftp_username, passwd=ftp_pwd)
      logger.info("Message: "+ftp_msg)
      ftp_msg=FTP.pwd()
      logger.info("Current dir: "+ftp_msg)
      filename = '/....xml'
      with open(filename, 'rb') as fp:
       res = FTP.storbinary("STOR " + filename, fp)
except ftplib.all_errors as e:
      logger.error('FTP error:', e) 

I am using the "ftplib" library for python FTP.

Stacktrace and log:

2020-05-21 18:53:55,435 192.168.43.1642221
2020-05-21 18:53:55,458 Message: 220 Service ready for new user.
2020-05-21 18:53:55,473 Message: 230 User logged in, proceed.
2020-05-21 18:53:55,479 Current dir: /
Console exception (unhandled most probably):
--- Logging error ---
Traceback (most recent call last):
  File "FTP_Transfer.py", line 98, in ftp_Connect
    res = FTP.storbinary("STOR " + filename, open(filename, 'rb'))
  File "/usr/lib/python3.5/ftplib.py", line 508, in storbinary
    conn.sendall(buf)
ConnectionResetError: [Errno 104] Connection reset by peer

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3.5/logging/__init__.py", line 981, in emit
    msg = self.format(record)
  File "/usr/lib/python3.5/logging/__init__.py", line 831, in format
    return fmt.format(record)
  File "/usr/lib/python3.5/logging/__init__.py", line 568, in format
    record.message = record.getMessage()
  File "/usr/lib/python3.5/logging/__init__.py", line 331, in getMessage
    msg = msg % self.args
TypeError: not all arguments converted during string formatting
Call stack:
  File "FTP_Transfer.py", line 120, in <module>
    msg = ftp_Connect()
  File "FTP_Transfer.py", line 103, in ftp_Connect
    logger.error('FTP error:', e)
Message: 'FTP error:'
Arguments: (ConnectionResetError(104, 'Connection reset by peer'),)

So as it establishes the connection, prints the current dir but fails to upload the file. What can be the reason for this failure?


Solution

  • Prob was due to wrong local dir path. i used

     os.chdir("/home/pi/../.../.../")
    

    before FTP transfer and it worked like a charm. giving full/absolute path is not a solution.