blob: d1603037593216bdbb06e07c63746239adbfd732 [file] [log] [blame]
Guido van Rossum1115ab21992-11-04 15:51:30 +00001# An FTP client class. Based on RFC 959: File Transfer Protocol
2# (FTP), by J. Postel and J. Reynolds
3
Guido van Rossumae3b3a31993-11-30 13:43:54 +00004# Changes and improvements suggested by Steve Majewski
5
Guido van Rossum1115ab21992-11-04 15:51:30 +00006
Guido van Rossumc567c601992-11-05 22:22:37 +00007# Example:
8#
9# >>> from ftplib import FTP
Guido van Rossume65cce51993-11-08 15:05:21 +000010# >>> ftp = FTP('ftp.cwi.nl') # connect to host, default port
Guido van Rossumc567c601992-11-05 22:22:37 +000011# >>> ftp.login() # default, i.e.: user anonymous, passwd user@hostname
Guido van Rossumb6775db1994-08-01 11:34:53 +000012# >>> ftp.retrlines('LIST') # list directory contents
Guido van Rossumc567c601992-11-05 22:22:37 +000013# total 43
14# d--x--x--x 2 root root 512 Jul 1 16:50 bin
15# d--x--x--x 2 root root 512 Sep 16 1991 etc
16# drwxr-xr-x 2 root ftp 10752 Sep 16 1991 lost+found
17# drwxr-srwt 15 root ftp 10240 Nov 5 20:43 pub
18# >>> ftp.quit()
19#
Guido van Rossumb6775db1994-08-01 11:34:53 +000020# To download a file, use ftp.retrlines('RETR ' + filename),
Guido van Rossumc567c601992-11-05 22:22:37 +000021# or ftp.retrbinary() with slightly different arguments.
22# To upload a file, use ftp.storlines() or ftp.storbinary(), which have
23# an open file as argument.
24# The download/upload functions first issue appropriate TYPE and PORT
25# commands.
26
27
Guido van Rossum1115ab21992-11-04 15:51:30 +000028import os
29import sys
Guido van Rossum1115ab21992-11-04 15:51:30 +000030import string
31
Guido van Rossumb6775db1994-08-01 11:34:53 +000032# Import SOCKS module if it exists, else standard socket module socket
33try:
34 import SOCKS; socket = SOCKS
35except ImportError:
36 import socket
37
Guido van Rossum1115ab21992-11-04 15:51:30 +000038
Guido van Rossumd3166071993-05-24 14:16:22 +000039# Magic number from <socket.h>
40MSG_OOB = 0x1 # Process data out of band
41
42
Guido van Rossumc567c601992-11-05 22:22:37 +000043# The standard FTP server control port
Guido van Rossum1115ab21992-11-04 15:51:30 +000044FTP_PORT = 21
Guido van Rossum1115ab21992-11-04 15:51:30 +000045
46
Guido van Rossum21974791992-11-06 13:34:17 +000047# Exception raised when an error or invalid response is received
Guido van Rossumc567c601992-11-05 22:22:37 +000048error_reply = 'ftplib.error_reply' # unexpected [123]xx reply
49error_temp = 'ftplib.error_temp' # 4xx errors
50error_perm = 'ftplib.error_perm' # 5xx errors
51error_proto = 'ftplib.error_proto' # response does not begin with [1-5]
Guido van Rossum1115ab21992-11-04 15:51:30 +000052
53
Guido van Rossum21974791992-11-06 13:34:17 +000054# All exceptions (hopefully) that may be raised here and that aren't
55# (always) programming errors on our side
56all_errors = (error_reply, error_temp, error_perm, error_proto, \
57 socket.error, IOError)
58
59
Guido van Rossum1115ab21992-11-04 15:51:30 +000060# Line terminators (we always output CRLF, but accept any of CRLF, CR, LF)
61CRLF = '\r\n'
62
63
Guido van Rossum1115ab21992-11-04 15:51:30 +000064# The class itself
65class FTP:
66
Guido van Rossum52fc1f61993-06-17 12:38:10 +000067 # New initialization method (called by class instantiation)
68 # Initialize host to localhost, port to standard ftp port
Guido van Rossumae3b3a31993-11-30 13:43:54 +000069 # Optional arguments are host (for connect()),
70 # and user, passwd, acct (for login())
Guido van Rossumb6775db1994-08-01 11:34:53 +000071 def __init__(self, host = '', user = '', passwd = '', acct = ''):
Guido van Rossum52fc1f61993-06-17 12:38:10 +000072 # Initialize the instance to something mostly harmless
Guido van Rossum1115ab21992-11-04 15:51:30 +000073 self.debugging = 0
Guido van Rossum52fc1f61993-06-17 12:38:10 +000074 self.host = ''
75 self.port = FTP_PORT
76 self.sock = None
77 self.file = None
78 self.welcome = None
Guido van Rossumb6775db1994-08-01 11:34:53 +000079 if host:
80 self.connect(host)
81 if user: self.login(user, passwd, acct)
Guido van Rossum52fc1f61993-06-17 12:38:10 +000082
Guido van Rossum52fc1f61993-06-17 12:38:10 +000083 # Connect to host. Arguments:
84 # - host: hostname to connect to (default previous host)
85 # - port: port to connect to (default previous port)
Guido van Rossumb6775db1994-08-01 11:34:53 +000086 def connect(self, host = '', port = 0):
87 if host: self.host = host
88 if port: self.port = port
Guido van Rossum1115ab21992-11-04 15:51:30 +000089 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
90 self.sock.connect(self.host, self.port)
91 self.file = self.sock.makefile('r')
92 self.welcome = self.getresp()
Guido van Rossum1115ab21992-11-04 15:51:30 +000093
94 # Get the welcome message from the server
Guido van Rossum7bc817d1993-12-17 15:25:27 +000095 # (this is read and squirreled away by connect())
Guido van Rossum1115ab21992-11-04 15:51:30 +000096 def getwelcome(self):
97 if self.debugging: print '*welcome*', `self.welcome`
98 return self.welcome
99
100 # Set the debugging level. Argument level means:
101 # 0: no debugging output (default)
102 # 1: print commands and responses but not body text etc.
103 # 2: also print raw lines read and sent before stripping CR/LF
Guido van Rossume65cce51993-11-08 15:05:21 +0000104 def set_debuglevel(self, level):
Guido van Rossum1115ab21992-11-04 15:51:30 +0000105 self.debugging = level
Guido van Rossume65cce51993-11-08 15:05:21 +0000106 debug = set_debuglevel
Guido van Rossum1115ab21992-11-04 15:51:30 +0000107
108 # Internal: send one line to the server, appending CRLF
109 def putline(self, line):
110 line = line + CRLF
111 if self.debugging > 1: print '*put*', `line`
112 self.sock.send(line)
113
114 # Internal: send one command to the server (through putline())
115 def putcmd(self, line):
116 if self.debugging: print '*cmd*', `line`
117 self.putline(line)
118
119 # Internal: return one line from the server, stripping CRLF.
120 # Raise EOFError if the connection is closed
121 def getline(self):
122 line = self.file.readline()
123 if self.debugging > 1:
124 print '*get*', `line`
125 if not line: raise EOFError
126 if line[-2:] == CRLF: line = line[:-2]
127 elif line[-1:] in CRLF: line = line[:-1]
128 return line
129
130 # Internal: get a response from the server, which may possibly
131 # consist of multiple lines. Return a single string with no
132 # trailing CRLF. If the response consists of multiple lines,
133 # these are separated by '\n' characters in the string
134 def getmultiline(self):
135 line = self.getline()
136 if line[3:4] == '-':
137 code = line[:3]
138 while 1:
139 nextline = self.getline()
140 line = line + ('\n' + nextline)
141 if nextline[:3] == code and \
142 nextline[3:4] <> '-':
143 break
144 return line
145
146 # Internal: get a response from the server.
147 # Raise various errors if the response indicates an error
148 def getresp(self):
149 resp = self.getmultiline()
150 if self.debugging: print '*resp*', `resp`
151 self.lastresp = resp[:3]
152 c = resp[:1]
153 if c == '4':
Guido van Rossumc567c601992-11-05 22:22:37 +0000154 raise error_temp, resp
Guido van Rossum1115ab21992-11-04 15:51:30 +0000155 if c == '5':
Guido van Rossumc567c601992-11-05 22:22:37 +0000156 raise error_perm, resp
Guido van Rossum1115ab21992-11-04 15:51:30 +0000157 if c not in '123':
Guido van Rossumc567c601992-11-05 22:22:37 +0000158 raise error_proto, resp
Guido van Rossum1115ab21992-11-04 15:51:30 +0000159 return resp
160
Guido van Rossumc567c601992-11-05 22:22:37 +0000161 # Expect a response beginning with '2'
162 def voidresp(self):
163 resp = self.getresp()
164 if resp[0] <> '2':
165 raise error_reply, resp
166
Guido van Rossumd3166071993-05-24 14:16:22 +0000167 # Abort a file transfer. Uses out-of-band data.
168 # This does not follow the procedure from the RFC to send Telnet
169 # IP and Synch; that doesn't seem to work with the servers I've
170 # tried. Instead, just send the ABOR command as OOB data.
171 def abort(self):
172 line = 'ABOR' + CRLF
173 if self.debugging > 1: print '*put urgent*', `line`
174 self.sock.send(line, MSG_OOB)
175 resp = self.getmultiline()
176 if resp[:3] not in ('426', '226'):
177 raise error_proto, resp
178
Guido van Rossum1115ab21992-11-04 15:51:30 +0000179 # Send a command and return the response
180 def sendcmd(self, cmd):
181 self.putcmd(cmd)
182 return self.getresp()
183
Guido van Rossumc68a4011992-11-05 23:01:42 +0000184 # Send a command and expect a response beginning with '2'
Guido van Rossumc567c601992-11-05 22:22:37 +0000185 def voidcmd(self, cmd):
Guido van Rossumc68a4011992-11-05 23:01:42 +0000186 self.putcmd(cmd)
187 self.voidresp()
Guido van Rossumc567c601992-11-05 22:22:37 +0000188
Guido van Rossum1115ab21992-11-04 15:51:30 +0000189 # Send a PORT command with the current host and the given port number
190 def sendport(self, port):
191 hostname = socket.gethostname()
192 hostaddr = socket.gethostbyname(hostname)
193 hbytes = string.splitfields(hostaddr, '.')
194 pbytes = [`port/256`, `port%256`]
195 bytes = hbytes + pbytes
196 cmd = 'PORT ' + string.joinfields(bytes, ',')
Guido van Rossumc567c601992-11-05 22:22:37 +0000197 self.voidcmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000198
199 # Create a new socket and send a PORT command for it
200 def makeport(self):
201 global nextport
Guido van Rossum1115ab21992-11-04 15:51:30 +0000202 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000203 sock.listen(1)
204 host, port = sock.getsockname()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000205 resp = self.sendport(port)
206 return sock
207
Guido van Rossumc567c601992-11-05 22:22:37 +0000208 # Send a port command and a transfer command, accept the connection
209 # and return the socket for the connection
210 def transfercmd(self, cmd):
Guido van Rossum1115ab21992-11-04 15:51:30 +0000211 sock = self.makeport()
212 resp = self.sendcmd(cmd)
213 if resp[0] <> '1':
214 raise error_reply, resp
Guido van Rossumc567c601992-11-05 22:22:37 +0000215 conn, sockaddr = sock.accept()
216 return conn
217
218 # Login, default anonymous
Guido van Rossumb6775db1994-08-01 11:34:53 +0000219 def login(self, user = '', passwd = '', acct = ''):
Guido van Rossumc567c601992-11-05 22:22:37 +0000220 if not user: user = 'anonymous'
221 if user == 'anonymous' and passwd in ('', '-'):
222 thishost = socket.gethostname()
223 if os.environ.has_key('LOGNAME'):
224 realuser = os.environ['LOGNAME']
225 elif os.environ.has_key('USER'):
226 realuser = os.environ['USER']
227 else:
228 realuser = 'anonymous'
229 passwd = passwd + realuser + '@' + thishost
230 resp = self.sendcmd('USER ' + user)
231 if resp[0] == '3': resp = self.sendcmd('PASS ' + passwd)
232 if resp[0] == '3': resp = self.sendcmd('ACCT ' + acct)
233 if resp[0] <> '2':
234 raise error_reply, resp
235
236 # Retrieve data in binary mode.
237 # The argument is a RETR command.
238 # The callback function is called for each block.
239 # This creates a new port for you
240 def retrbinary(self, cmd, callback, blocksize):
241 self.voidcmd('TYPE I')
242 conn = self.transfercmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000243 while 1:
244 data = conn.recv(blocksize)
245 if not data:
246 break
247 callback(data)
248 conn.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000249 self.voidresp()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000250
Guido van Rossumc567c601992-11-05 22:22:37 +0000251 # Retrieve data in line mode.
Guido van Rossum1115ab21992-11-04 15:51:30 +0000252 # The argument is a RETR or LIST command.
253 # The callback function is called for each line, with trailing
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000254 # CRLF stripped. This creates a new port for you.
255 # print_lines is the default callback
Guido van Rossumb6775db1994-08-01 11:34:53 +0000256 def retrlines(self, cmd, callback = None):
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000257 if not callback: callback = print_line
Guido van Rossumc567c601992-11-05 22:22:37 +0000258 resp = self.sendcmd('TYPE A')
259 conn = self.transfercmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000260 fp = conn.makefile('r')
261 while 1:
262 line = fp.readline()
263 if not line:
264 break
265 if line[-2:] == CRLF:
266 line = line[:-2]
267 elif line[:-1] == '\n':
268 line = line[:-1]
269 callback(line)
270 fp.close()
271 conn.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000272 self.voidresp()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000273
Guido van Rossumc567c601992-11-05 22:22:37 +0000274 # Store a file in binary mode
275 def storbinary(self, cmd, fp, blocksize):
276 self.voidcmd('TYPE I')
277 conn = self.transfercmd(cmd)
278 while 1:
279 buf = fp.read(blocksize)
280 if not buf: break
281 conn.send(buf)
282 conn.close()
283 self.voidresp()
284
285 # Store a file in line mode
286 def storlines(self, cmd, fp):
287 self.voidcmd('TYPE A')
288 conn = self.transfercmd(cmd)
289 while 1:
290 buf = fp.readline()
291 if not buf: break
292 if buf[-2:] <> CRLF:
293 if buf[-1] in CRLF: buf = buf[:-1]
294 buf = buf + CRLF
295 conn.send(buf)
296 conn.close()
297 self.voidresp()
298
299 # Return a list of files in a given directory (default the current)
300 def nlst(self, *args):
301 cmd = 'NLST'
302 for arg in args:
303 cmd = cmd + (' ' + arg)
304 files = []
305 self.retrlines(cmd, files.append)
306 return files
307
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000308 # List a directory in long form. By default list current directory
309 # to stdout. Optional last argument is callback function;
310 # all non-empty arguments before it are concatenated to the
311 # LIST command. (This *should* only be used for a pathname.)
312 def dir(self, *args):
313 cmd = 'LIST'
314 func = None
315 if args[-1:] and type(args[-1]) != type(''):
316 args, func = args[:-1], args[-1]
317 for arg in args:
318 if arg:
319 cmd = cmd + (' ' + arg)
320 self.retrlines(cmd, func)
321
Guido van Rossumc567c601992-11-05 22:22:37 +0000322 # Rename a file
323 def rename(self, fromname, toname):
324 resp = self.sendcmd('RNFR ' + fromname)
325 if resp[0] <> '3':
Guido van Rossum1115ab21992-11-04 15:51:30 +0000326 raise error_reply, resp
Guido van Rossumc567c601992-11-05 22:22:37 +0000327 self.voidcmd('RNTO ' + toname)
328
Guido van Rossum02cf5821993-05-17 08:00:02 +0000329 # Change to a directory
330 def cwd(self, dirname):
Guido van Rossumdf563861993-07-06 15:19:36 +0000331 if dirname == '..':
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000332 try:
333 self.voidcmd('CDUP')
334 return
335 except error_perm, msg:
336 if msg[:3] != '500':
337 raise error_perm, msg
338 cmd = 'CWD ' + dirname
Guido van Rossumdf563861993-07-06 15:19:36 +0000339 self.voidcmd(cmd)
Guido van Rossum02cf5821993-05-17 08:00:02 +0000340
Guido van Rossum17ed1ae1993-06-01 13:21:04 +0000341 # Retrieve the size of a file
342 def size(self, filename):
343 resp = self.sendcmd('SIZE ' + filename)
344 if resp[:3] == '213':
345 return string.atoi(string.strip(resp[3:]))
346
Guido van Rossumc567c601992-11-05 22:22:37 +0000347 # Make a directory, return its full pathname
348 def mkd(self, dirname):
349 resp = self.sendcmd('MKD ' + dirname)
350 return parse257(resp)
351
352 # Return current wording directory
353 def pwd(self):
354 resp = self.sendcmd('PWD')
355 return parse257(resp)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000356
357 # Quit, and close the connection
358 def quit(self):
Guido van Rossumc567c601992-11-05 22:22:37 +0000359 self.voidcmd('QUIT')
Guido van Rossum17ed1ae1993-06-01 13:21:04 +0000360 self.close()
361
362 # Close the connection without assuming anything about it
363 def close(self):
Guido van Rossum1115ab21992-11-04 15:51:30 +0000364 self.file.close()
365 self.sock.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000366 del self.file, self.sock
367
368
369# Parse a response type 257
370def parse257(resp):
371 if resp[:3] <> '257':
372 raise error_reply, resp
373 if resp[3:5] <> ' "':
374 return '' # Not compliant to RFC 959, but UNIX ftpd does this
375 dirname = ''
376 i = 5
377 n = len(resp)
378 while i < n:
379 c = resp[i]
380 i = i+1
381 if c == '"':
382 if i >= n or resp[i] <> '"':
383 break
384 i = i+1
385 dirname = dirname + c
386 return dirname
Guido van Rossum1115ab21992-11-04 15:51:30 +0000387
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000388# Default retrlines callback to print a line
389def print_line(line):
390 print line
391
Guido van Rossum1115ab21992-11-04 15:51:30 +0000392
393# Test program.
394# Usage: ftp [-d] host [-l[dir]] [-d[dir]] [file] ...
395def test():
396 import marshal
Guido van Rossumb6775db1994-08-01 11:34:53 +0000397 debugging = 0
398 while sys.argv[1] == '-d':
399 debugging = debugging+1
400 del sys.argv[1]
401 host = sys.argv[1]
402 ftp = FTP(host)
403 ftp.set_debuglevel(debugging)
404 ftp.login()
405 for file in sys.argv[2:]:
406 if file[:2] == '-l':
407 ftp.dir(file[2:])
408 elif file[:2] == '-d':
409 cmd = 'CWD'
410 if file[2:]: cmd = cmd + ' ' + file[2:]
411 resp = ftp.sendcmd(cmd)
412 else:
413 ftp.retrbinary('RETR ' + file, \
414 sys.stdout.write, 1024)
415 ftp.quit()