在用python ftplib 上传文件的时候,遇到了一个奇怪的问题,导致上传失败,问题如下:
[*]192.168.1.238 FTP Anonymous Logon Succeeded
Traceback (most recent call last):
File "/home/pi/camnet/ftp_test.py", line 25, in <module>
uploadfile(ftp, file_name)
File "/home/pi/camnet/ftp_test.py", line 18, in uploadfile
ftp.storbinary(remotepath, fp)
File "/usr/lib/python3.11/ftplib.py", line 498, in storbinary
with self.transfercmd(cmd, rest) as conn:
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/ftplib.py", line 393, in transfercmd
return self.ntransfercmd(cmd, rest)[0]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/ftplib.py", line 359, in ntransfercmd
resp = self.sendcmd(cmd)
^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/ftplib.py", line 281, in sendcmd
return self.getresp()
^^^^^^^^^^^^^^
File "/usr/lib/python3.11/ftplib.py", line 254, in getresp
raise error_perm(resp)
ftplib.error_perm: 500 Command not understood.
ftplib.error_perm: 500 Command not understood.
问题点在这个函数的使用:
ftp.storbinary(remotepath, fp)
查询官方文档:
storbinary(cmd, fp, blocksize=8192, callback=None, rest=None)
Store a file in binary transfer mode.
Parameters:
cmd (str) – An appropriate
STOR
command:"STOR filename"
.fp (file object) – A file object (opened in binary mode) which is read until EOF, using its read() method in blocks of size blocksize to provide the data to be stored.
blocksize (int) – The read block size. Defaults to
8192
.callback (callable) – A single parameter callable that is called for each block of data sent, with its single argument being the data as bytes.
rest (int) – A
REST
command to be sent to the server. See the documentation for the rest parameter of the transfercmd() method.
发现以二进制传输模式存储文件。命令需要时恰当的STOR命令:“STOR filename”。
所以代码修改成这样就没问题了:
ftp.storbinary("STOR " + remotepath, fp)