blob: bfb0b5b2d52599b252bd461db2e53f3f9a939d54 [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
12# >>> def handle_one_line(line): # callback for ftp.retrlines
13# ... print line
14# ...
15# >>> ftp.retrlines('LIST', handle_one_line) # list directory contents
16# total 43
17# d--x--x--x 2 root root 512 Jul 1 16:50 bin
18# d--x--x--x 2 root root 512 Sep 16 1991 etc
19# drwxr-xr-x 2 root ftp 10752 Sep 16 1991 lost+found
20# drwxr-srwt 15 root ftp 10240 Nov 5 20:43 pub
21# >>> ftp.quit()
22#
23# To download a file, use ftp.retrlines('RETR ' + filename, handle_one_line),
24# or ftp.retrbinary() with slightly different arguments.
25# To upload a file, use ftp.storlines() or ftp.storbinary(), which have
26# an open file as argument.
27# The download/upload functions first issue appropriate TYPE and PORT
28# commands.
29
30
Guido van Rossum1115ab21992-11-04 15:51:30 +000031import os
32import sys
33import socket
34import string
35
36
Guido van Rossumd3166071993-05-24 14:16:22 +000037# Magic number from <socket.h>
38MSG_OOB = 0x1 # Process data out of band
39
40
Guido van Rossumc567c601992-11-05 22:22:37 +000041# The standard FTP server control port
Guido van Rossum1115ab21992-11-04 15:51:30 +000042FTP_PORT = 21
Guido van Rossum1115ab21992-11-04 15:51:30 +000043
44
Guido van Rossum21974791992-11-06 13:34:17 +000045# Exception raised when an error or invalid response is received
Guido van Rossumc567c601992-11-05 22:22:37 +000046error_reply = 'ftplib.error_reply' # unexpected [123]xx reply
47error_temp = 'ftplib.error_temp' # 4xx errors
48error_perm = 'ftplib.error_perm' # 5xx errors
49error_proto = 'ftplib.error_proto' # response does not begin with [1-5]
Guido van Rossum1115ab21992-11-04 15:51:30 +000050
51
Guido van Rossum21974791992-11-06 13:34:17 +000052# All exceptions (hopefully) that may be raised here and that aren't
53# (always) programming errors on our side
54all_errors = (error_reply, error_temp, error_perm, error_proto, \
55 socket.error, IOError)
56
57
Guido van Rossum1115ab21992-11-04 15:51:30 +000058# Line terminators (we always output CRLF, but accept any of CRLF, CR, LF)
59CRLF = '\r\n'
60
61
62# Next port to be used by makeport(), with PORT_OFFSET added
Guido van Rossumc68a4011992-11-05 23:01:42 +000063# (This is now only used when the python interpreter doesn't support
64# the getsockname() method yet)
Guido van Rossum1115ab21992-11-04 15:51:30 +000065nextport = 0
66PORT_OFFSET = 40000
67PORT_CYCLE = 1000
Guido van Rossum1115ab21992-11-04 15:51:30 +000068
69
70# The class itself
71class FTP:
72
Guido van Rossum52fc1f61993-06-17 12:38:10 +000073 # New initialization method (called by class instantiation)
74 # Initialize host to localhost, port to standard ftp port
Guido van Rossumae3b3a31993-11-30 13:43:54 +000075 # Optional arguments are host (for connect()),
76 # and user, passwd, acct (for login())
Guido van Rossum52fc1f61993-06-17 12:38:10 +000077 def __init__(self, *args):
78 # Initialize the instance to something mostly harmless
Guido van Rossum1115ab21992-11-04 15:51:30 +000079 self.debugging = 0
Guido van Rossum52fc1f61993-06-17 12:38:10 +000080 self.host = ''
81 self.port = FTP_PORT
82 self.sock = None
83 self.file = None
84 self.welcome = None
85 if args:
Guido van Rossumae3b3a31993-11-30 13:43:54 +000086 self.connect(args[0])
87 if args[1:]:
88 apply(self.login, args[1:])
Guido van Rossum52fc1f61993-06-17 12:38:10 +000089
90 # Old init method (explicitly called by caller)
91 def init(self, *args):
92 if args:
93 apply(self.connect, args)
94
95 # Connect to host. Arguments:
96 # - host: hostname to connect to (default previous host)
97 # - port: port to connect to (default previous port)
Guido van Rossumae3b3a31993-11-30 13:43:54 +000098 def connect(self, *args):
Guido van Rossum52fc1f61993-06-17 12:38:10 +000099 if args: self.host = args[0]
100 if args[1:]: self.port = args[1]
101 if args[2:]: raise TypeError, 'too many args'
Guido van Rossum1115ab21992-11-04 15:51:30 +0000102 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
103 self.sock.connect(self.host, self.port)
104 self.file = self.sock.makefile('r')
105 self.welcome = self.getresp()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000106
107 # Get the welcome message from the server
108 # (this is read and squirreled away by init())
109 def getwelcome(self):
110 if self.debugging: print '*welcome*', `self.welcome`
111 return self.welcome
112
113 # Set the debugging level. Argument level means:
114 # 0: no debugging output (default)
115 # 1: print commands and responses but not body text etc.
116 # 2: also print raw lines read and sent before stripping CR/LF
Guido van Rossume65cce51993-11-08 15:05:21 +0000117 def set_debuglevel(self, level):
Guido van Rossum1115ab21992-11-04 15:51:30 +0000118 self.debugging = level
Guido van Rossume65cce51993-11-08 15:05:21 +0000119 debug = set_debuglevel
Guido van Rossum1115ab21992-11-04 15:51:30 +0000120
121 # Internal: send one line to the server, appending CRLF
122 def putline(self, line):
123 line = line + CRLF
124 if self.debugging > 1: print '*put*', `line`
125 self.sock.send(line)
126
127 # Internal: send one command to the server (through putline())
128 def putcmd(self, line):
129 if self.debugging: print '*cmd*', `line`
130 self.putline(line)
131
132 # Internal: return one line from the server, stripping CRLF.
133 # Raise EOFError if the connection is closed
134 def getline(self):
135 line = self.file.readline()
136 if self.debugging > 1:
137 print '*get*', `line`
138 if not line: raise EOFError
139 if line[-2:] == CRLF: line = line[:-2]
140 elif line[-1:] in CRLF: line = line[:-1]
141 return line
142
143 # Internal: get a response from the server, which may possibly
144 # consist of multiple lines. Return a single string with no
145 # trailing CRLF. If the response consists of multiple lines,
146 # these are separated by '\n' characters in the string
147 def getmultiline(self):
148 line = self.getline()
149 if line[3:4] == '-':
150 code = line[:3]
151 while 1:
152 nextline = self.getline()
153 line = line + ('\n' + nextline)
154 if nextline[:3] == code and \
155 nextline[3:4] <> '-':
156 break
157 return line
158
159 # Internal: get a response from the server.
160 # Raise various errors if the response indicates an error
161 def getresp(self):
162 resp = self.getmultiline()
163 if self.debugging: print '*resp*', `resp`
164 self.lastresp = resp[:3]
165 c = resp[:1]
166 if c == '4':
Guido van Rossumc567c601992-11-05 22:22:37 +0000167 raise error_temp, resp
Guido van Rossum1115ab21992-11-04 15:51:30 +0000168 if c == '5':
Guido van Rossumc567c601992-11-05 22:22:37 +0000169 raise error_perm, resp
Guido van Rossum1115ab21992-11-04 15:51:30 +0000170 if c not in '123':
Guido van Rossumc567c601992-11-05 22:22:37 +0000171 raise error_proto, resp
Guido van Rossum1115ab21992-11-04 15:51:30 +0000172 return resp
173
Guido van Rossumc567c601992-11-05 22:22:37 +0000174 # Expect a response beginning with '2'
175 def voidresp(self):
176 resp = self.getresp()
177 if resp[0] <> '2':
178 raise error_reply, resp
179
Guido van Rossumd3166071993-05-24 14:16:22 +0000180 # Abort a file transfer. Uses out-of-band data.
181 # This does not follow the procedure from the RFC to send Telnet
182 # IP and Synch; that doesn't seem to work with the servers I've
183 # tried. Instead, just send the ABOR command as OOB data.
184 def abort(self):
185 line = 'ABOR' + CRLF
186 if self.debugging > 1: print '*put urgent*', `line`
187 self.sock.send(line, MSG_OOB)
188 resp = self.getmultiline()
189 if resp[:3] not in ('426', '226'):
190 raise error_proto, resp
191
Guido van Rossum1115ab21992-11-04 15:51:30 +0000192 # Send a command and return the response
193 def sendcmd(self, cmd):
194 self.putcmd(cmd)
195 return self.getresp()
196
Guido van Rossumc68a4011992-11-05 23:01:42 +0000197 # Send a command and expect a response beginning with '2'
Guido van Rossumc567c601992-11-05 22:22:37 +0000198 def voidcmd(self, cmd):
Guido van Rossumc68a4011992-11-05 23:01:42 +0000199 self.putcmd(cmd)
200 self.voidresp()
Guido van Rossumc567c601992-11-05 22:22:37 +0000201
Guido van Rossum1115ab21992-11-04 15:51:30 +0000202 # Send a PORT command with the current host and the given port number
203 def sendport(self, port):
204 hostname = socket.gethostname()
205 hostaddr = socket.gethostbyname(hostname)
206 hbytes = string.splitfields(hostaddr, '.')
207 pbytes = [`port/256`, `port%256`]
208 bytes = hbytes + pbytes
209 cmd = 'PORT ' + string.joinfields(bytes, ',')
Guido van Rossumc567c601992-11-05 22:22:37 +0000210 self.voidcmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000211
212 # Create a new socket and send a PORT command for it
213 def makeport(self):
214 global nextport
Guido van Rossum1115ab21992-11-04 15:51:30 +0000215 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Guido van Rossumc68a4011992-11-05 23:01:42 +0000216 try:
217 getsockname = sock.getsockname
218 except AttributeError:
219 if self.debugging > 1:
220 print '*** getsockname not supported',
221 print '-- using manual port assignment ***'
222 port = nextport + PORT_OFFSET
223 nextport = (nextport + 1) % PORT_CYCLE
224 sock.bind('', port)
225 getsockname = None
226 sock.listen(0) # Assigns the port if not explicitly bound
227 if getsockname:
228 host, port = getsockname()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000229 resp = self.sendport(port)
230 return sock
231
Guido van Rossumc567c601992-11-05 22:22:37 +0000232 # Send a port command and a transfer command, accept the connection
233 # and return the socket for the connection
234 def transfercmd(self, cmd):
Guido van Rossum1115ab21992-11-04 15:51:30 +0000235 sock = self.makeport()
236 resp = self.sendcmd(cmd)
237 if resp[0] <> '1':
238 raise error_reply, resp
Guido van Rossumc567c601992-11-05 22:22:37 +0000239 conn, sockaddr = sock.accept()
240 return conn
241
242 # Login, default anonymous
243 def login(self, *args):
244 user = passwd = acct = ''
245 n = len(args)
246 if n > 3: raise TypeError, 'too many arguments'
247 if n > 0: user = args[0]
248 if n > 1: passwd = args[1]
249 if n > 2: acct = args[2]
250 if not user: user = 'anonymous'
251 if user == 'anonymous' and passwd in ('', '-'):
252 thishost = socket.gethostname()
253 if os.environ.has_key('LOGNAME'):
254 realuser = os.environ['LOGNAME']
255 elif os.environ.has_key('USER'):
256 realuser = os.environ['USER']
257 else:
258 realuser = 'anonymous'
259 passwd = passwd + realuser + '@' + thishost
260 resp = self.sendcmd('USER ' + user)
261 if resp[0] == '3': resp = self.sendcmd('PASS ' + passwd)
262 if resp[0] == '3': resp = self.sendcmd('ACCT ' + acct)
263 if resp[0] <> '2':
264 raise error_reply, resp
265
266 # Retrieve data in binary mode.
267 # The argument is a RETR command.
268 # The callback function is called for each block.
269 # This creates a new port for you
270 def retrbinary(self, cmd, callback, blocksize):
271 self.voidcmd('TYPE I')
272 conn = self.transfercmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000273 while 1:
274 data = conn.recv(blocksize)
275 if not data:
276 break
277 callback(data)
278 conn.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000279 self.voidresp()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000280
Guido van Rossumc567c601992-11-05 22:22:37 +0000281 # Retrieve data in line mode.
Guido van Rossum1115ab21992-11-04 15:51:30 +0000282 # The argument is a RETR or LIST command.
283 # The callback function is called for each line, with trailing
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000284 # CRLF stripped. This creates a new port for you.
285 # print_lines is the default callback
Guido van Rossum79c85f11993-12-14 15:54:01 +0000286 def retrlines(self, cmd, *args):
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000287 callback = None
288 if args:
289 callback = args[0]
290 if args[1:]: raise TypeError, 'too many args'
291 if not callback: callback = print_line
Guido van Rossumc567c601992-11-05 22:22:37 +0000292 resp = self.sendcmd('TYPE A')
293 conn = self.transfercmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000294 fp = conn.makefile('r')
295 while 1:
296 line = fp.readline()
297 if not line:
298 break
299 if line[-2:] == CRLF:
300 line = line[:-2]
301 elif line[:-1] == '\n':
302 line = line[:-1]
303 callback(line)
304 fp.close()
305 conn.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000306 self.voidresp()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000307
Guido van Rossumc567c601992-11-05 22:22:37 +0000308 # Store a file in binary mode
309 def storbinary(self, cmd, fp, blocksize):
310 self.voidcmd('TYPE I')
311 conn = self.transfercmd(cmd)
312 while 1:
313 buf = fp.read(blocksize)
314 if not buf: break
315 conn.send(buf)
316 conn.close()
317 self.voidresp()
318
319 # Store a file in line mode
320 def storlines(self, cmd, fp):
321 self.voidcmd('TYPE A')
322 conn = self.transfercmd(cmd)
323 while 1:
324 buf = fp.readline()
325 if not buf: break
326 if buf[-2:] <> CRLF:
327 if buf[-1] in CRLF: buf = buf[:-1]
328 buf = buf + CRLF
329 conn.send(buf)
330 conn.close()
331 self.voidresp()
332
333 # Return a list of files in a given directory (default the current)
334 def nlst(self, *args):
335 cmd = 'NLST'
336 for arg in args:
337 cmd = cmd + (' ' + arg)
338 files = []
339 self.retrlines(cmd, files.append)
340 return files
341
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000342 # List a directory in long form. By default list current directory
343 # to stdout. Optional last argument is callback function;
344 # all non-empty arguments before it are concatenated to the
345 # LIST command. (This *should* only be used for a pathname.)
346 def dir(self, *args):
347 cmd = 'LIST'
348 func = None
349 if args[-1:] and type(args[-1]) != type(''):
350 args, func = args[:-1], args[-1]
351 for arg in args:
352 if arg:
353 cmd = cmd + (' ' + arg)
354 self.retrlines(cmd, func)
355
Guido van Rossumc567c601992-11-05 22:22:37 +0000356 # Rename a file
357 def rename(self, fromname, toname):
358 resp = self.sendcmd('RNFR ' + fromname)
359 if resp[0] <> '3':
Guido van Rossum1115ab21992-11-04 15:51:30 +0000360 raise error_reply, resp
Guido van Rossumc567c601992-11-05 22:22:37 +0000361 self.voidcmd('RNTO ' + toname)
362
Guido van Rossum02cf5821993-05-17 08:00:02 +0000363 # Change to a directory
364 def cwd(self, dirname):
Guido van Rossumdf563861993-07-06 15:19:36 +0000365 if dirname == '..':
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000366 try:
367 self.voidcmd('CDUP')
368 return
369 except error_perm, msg:
370 if msg[:3] != '500':
371 raise error_perm, msg
372 cmd = 'CWD ' + dirname
Guido van Rossumdf563861993-07-06 15:19:36 +0000373 self.voidcmd(cmd)
Guido van Rossum02cf5821993-05-17 08:00:02 +0000374
Guido van Rossum17ed1ae1993-06-01 13:21:04 +0000375 # Retrieve the size of a file
376 def size(self, filename):
377 resp = self.sendcmd('SIZE ' + filename)
378 if resp[:3] == '213':
379 return string.atoi(string.strip(resp[3:]))
380
Guido van Rossumc567c601992-11-05 22:22:37 +0000381 # Make a directory, return its full pathname
382 def mkd(self, dirname):
383 resp = self.sendcmd('MKD ' + dirname)
384 return parse257(resp)
385
386 # Return current wording directory
387 def pwd(self):
388 resp = self.sendcmd('PWD')
389 return parse257(resp)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000390
391 # Quit, and close the connection
392 def quit(self):
Guido van Rossumc567c601992-11-05 22:22:37 +0000393 self.voidcmd('QUIT')
Guido van Rossum17ed1ae1993-06-01 13:21:04 +0000394 self.close()
395
396 # Close the connection without assuming anything about it
397 def close(self):
Guido van Rossum1115ab21992-11-04 15:51:30 +0000398 self.file.close()
399 self.sock.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000400 del self.file, self.sock
401
402
403# Parse a response type 257
404def parse257(resp):
405 if resp[:3] <> '257':
406 raise error_reply, resp
407 if resp[3:5] <> ' "':
408 return '' # Not compliant to RFC 959, but UNIX ftpd does this
409 dirname = ''
410 i = 5
411 n = len(resp)
412 while i < n:
413 c = resp[i]
414 i = i+1
415 if c == '"':
416 if i >= n or resp[i] <> '"':
417 break
418 i = i+1
419 dirname = dirname + c
420 return dirname
Guido van Rossum1115ab21992-11-04 15:51:30 +0000421
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000422# Default retrlines callback to print a line
423def print_line(line):
424 print line
425
Guido van Rossum1115ab21992-11-04 15:51:30 +0000426
427# Test program.
428# Usage: ftp [-d] host [-l[dir]] [-d[dir]] [file] ...
429def test():
430 import marshal
431 global nextport
432 try:
433 nextport = marshal.load(open('.@nextport', 'r'))
434 except IOError:
435 pass
436 try:
437 debugging = 0
438 while sys.argv[1] == '-d':
439 debugging = debugging+1
440 del sys.argv[1]
441 host = sys.argv[1]
Guido van Rossume65cce51993-11-08 15:05:21 +0000442 ftp = FTP(host)
443 ftp.set_debuglevel(debugging)
Guido van Rossumc567c601992-11-05 22:22:37 +0000444 ftp.login()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000445 for file in sys.argv[2:]:
446 if file[:2] == '-l':
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000447 ftp.dir(file[2:])
Guido van Rossum1115ab21992-11-04 15:51:30 +0000448 elif file[:2] == '-d':
449 cmd = 'CWD'
450 if file[2:]: cmd = cmd + ' ' + file[2:]
451 resp = ftp.sendcmd(cmd)
452 else:
453 ftp.retrbinary('RETR ' + file, \
454 sys.stdout.write, 1024)
455 ftp.quit()
456 finally:
457 marshal.dump(nextport, open('.@nextport', 'w'))