Python ftplib OSError:[WinError 10013]关于STOR操作

时间:2018-02-08 14:34:32

标签: python python-3.x ftplib

我有一个使用ftplib上传大量文件的python3程序。

它工作正常但偶尔会在上传的随机点中抛出以下异常:

[WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions
Traceback (most recent call last):
  File "bulk_box_ftp.py", line 90, in push_folder_contents
    placeFiles(ftp_conn, folder)
  File "bulk_box_ftp.py", line 68, in placeFiles
    placeFiles(ftp, localpath)
  File "bulk_box_ftp.py", line 52, in placeFiles
    ftp.storbinary('STOR ' + name, upfile)
  File "...\Python\Python36-32\lib\ftplib.py", line 503, in storbinary
    self.voidcmd('TYPE I')
  File "...\Python\Python36-32\lib\ftplib.py", line 278, in voidcmd
    return self.voidresp()
  File "...\Python\Python36-32\lib\ftplib.py", line 251, in voidresp
    resp = self.getresp()
  File "...\Python\Python36-32\lib\ftplib.py", line 236, in getresp
    resp = self.getmultiline()
  File "...\Programs\Python\Python36-32\lib\ftplib.py", line 222, in getmultiline
    line = self.getline()
  File "...\Python\Python36-32\lib\ftplib.py", line 204, in getline
    line = self.file.readline(self.maxline + 1)
  File "...\Python\Python36-32\lib\socket.py", line 586, in readinto
    return self._sock.recv_into(b)
  File "...\Python\Python36-32\lib\ssl.py", line 1009, in recv_into
    return self.read(nbytes, buffer)
  File "...\Python\Python36-32\lib\ssl.py", line 871, in read
    return self._sslobj.read(len, buffer)
  File "...\Python\Python36-32\lib\ssl.py", line 631, in read
    v = self._sslobj.read(len, buffer)
OSError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions

在此OSError之后,队列中的所有其他文件将抛出ConnectionResetError

ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

可能导致此异常的原因是什么?有什么方法可以安全地捕获它并恢复以继续FTP操作吗?

1 个答案:

答案 0 :(得分:0)

经过一些试验和错误后,我发现FTP连接必须执行完全重置。我将所有FTP上传代码都包含在try:块中,并在OSError被引发时捕获:

except OSError as e:
  print("FTP Connection Error Occurred")
  attempt_conn_reset(current_pwd)

此功能将终止并重新建立FTP连接:

def attempt_conn_reset(pwd="/"):
  # resets the FTP connection in case of a socket disconnect
  print("Attempting FTP reconnect")
  try:
      ftp_conn.quit()
  except ConnectionResetError:
    print("Connection was already closed")
  # allow OS to release port
  time.sleep(2)
  ftp_conn.connect(FTP_URL)
  ftp_conn.login(FTP_USER, FTP_PASSWORD)
  ftp_conn.prot_p()
  ftp_conn.cwd(pwd)
  print("FTP connection has been reset")