blob: a78f06b05df34e3911a9a6487b6303d81d8e6890 [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
Jack Jansen40b98351995-01-19 12:24:45 +00005# Modified by Jack to work on the mac.
Guido van Rossumae3b3a31993-11-30 13:43:54 +00006
Guido van Rossum1115ab21992-11-04 15:51:30 +00007
Guido van Rossumc567c601992-11-05 22:22:37 +00008# Example:
9#
10# >>> from ftplib import FTP
Guido van Rossume65cce51993-11-08 15:05:21 +000011# >>> ftp = FTP('ftp.cwi.nl') # connect to host, default port
Guido van Rossumc567c601992-11-05 22:22:37 +000012# >>> ftp.login() # default, i.e.: user anonymous, passwd user@hostname
Guido van Rossumb6775db1994-08-01 11:34:53 +000013# >>> ftp.retrlines('LIST') # list directory contents
Guido van Rossumc567c601992-11-05 22:22:37 +000014# total 43
15# d--x--x--x 2 root root 512 Jul 1 16:50 bin
16# d--x--x--x 2 root root 512 Sep 16 1991 etc
17# drwxr-xr-x 2 root ftp 10752 Sep 16 1991 lost+found
18# drwxr-srwt 15 root ftp 10240 Nov 5 20:43 pub
19# >>> ftp.quit()
20#
Guido van Rossumb6775db1994-08-01 11:34:53 +000021# To download a file, use ftp.retrlines('RETR ' + filename),
Guido van Rossumc567c601992-11-05 22:22:37 +000022# or ftp.retrbinary() with slightly different arguments.
23# To upload a file, use ftp.storlines() or ftp.storbinary(), which have
24# an open file as argument.
25# The download/upload functions first issue appropriate TYPE and PORT
26# commands.
27
28
Guido van Rossum1115ab21992-11-04 15:51:30 +000029import os
30import sys
Guido van Rossum1115ab21992-11-04 15:51:30 +000031import string
32
Guido van Rossumb6775db1994-08-01 11:34:53 +000033# Import SOCKS module if it exists, else standard socket module socket
34try:
35 import SOCKS; socket = SOCKS
36except ImportError:
37 import socket
38
Guido van Rossum1115ab21992-11-04 15:51:30 +000039
Guido van Rossumd3166071993-05-24 14:16:22 +000040# Magic number from <socket.h>
41MSG_OOB = 0x1 # Process data out of band
42
43
Guido van Rossumc567c601992-11-05 22:22:37 +000044# The standard FTP server control port
Guido van Rossum1115ab21992-11-04 15:51:30 +000045FTP_PORT = 21
Guido van Rossum1115ab21992-11-04 15:51:30 +000046
47
Guido van Rossum21974791992-11-06 13:34:17 +000048# Exception raised when an error or invalid response is received
Guido van Rossumc567c601992-11-05 22:22:37 +000049error_reply = 'ftplib.error_reply' # unexpected [123]xx reply
50error_temp = 'ftplib.error_temp' # 4xx errors
51error_perm = 'ftplib.error_perm' # 5xx errors
52error_proto = 'ftplib.error_proto' # response does not begin with [1-5]
Guido van Rossum1115ab21992-11-04 15:51:30 +000053
54
Guido van Rossum21974791992-11-06 13:34:17 +000055# All exceptions (hopefully) that may be raised here and that aren't
56# (always) programming errors on our side
57all_errors = (error_reply, error_temp, error_perm, error_proto, \
58 socket.error, IOError)
59
60
Guido van Rossum1115ab21992-11-04 15:51:30 +000061# Line terminators (we always output CRLF, but accept any of CRLF, CR, LF)
62CRLF = '\r\n'
63
64
Guido van Rossum1115ab21992-11-04 15:51:30 +000065# The class itself
66class FTP:
67
Guido van Rossum52fc1f61993-06-17 12:38:10 +000068 # New initialization method (called by class instantiation)
69 # Initialize host to localhost, port to standard ftp port
Guido van Rossumae3b3a31993-11-30 13:43:54 +000070 # Optional arguments are host (for connect()),
71 # and user, passwd, acct (for login())
Guido van Rossumb6775db1994-08-01 11:34:53 +000072 def __init__(self, host = '', user = '', passwd = '', acct = ''):
Guido van Rossum52fc1f61993-06-17 12:38:10 +000073 # Initialize the instance to something mostly harmless
Guido van Rossum1115ab21992-11-04 15:51:30 +000074 self.debugging = 0
Guido van Rossum52fc1f61993-06-17 12:38:10 +000075 self.host = ''
76 self.port = FTP_PORT
77 self.sock = None
78 self.file = None
79 self.welcome = None
Guido van Rossumb6775db1994-08-01 11:34:53 +000080 if host:
81 self.connect(host)
82 if user: self.login(user, passwd, acct)
Guido van Rossum52fc1f61993-06-17 12:38:10 +000083
Guido van Rossum52fc1f61993-06-17 12:38:10 +000084 # Connect to host. Arguments:
85 # - host: hostname to connect to (default previous host)
86 # - port: port to connect to (default previous port)
Guido van Rossumb6775db1994-08-01 11:34:53 +000087 def connect(self, host = '', port = 0):
88 if host: self.host = host
89 if port: self.port = port
Guido van Rossum1115ab21992-11-04 15:51:30 +000090 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
91 self.sock.connect(self.host, self.port)
92 self.file = self.sock.makefile('r')
93 self.welcome = self.getresp()
Guido van Rossum1115ab21992-11-04 15:51:30 +000094
95 # Get the welcome message from the server
Guido van Rossum7bc817d1993-12-17 15:25:27 +000096 # (this is read and squirreled away by connect())
Guido van Rossum1115ab21992-11-04 15:51:30 +000097 def getwelcome(self):
Guido van Rossumebaf1041995-05-05 15:54:14 +000098 if self.debugging:
99 print '*welcome*', self.sanitize(self.welcome)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000100 return self.welcome
101
102 # Set the debugging level. Argument level means:
103 # 0: no debugging output (default)
104 # 1: print commands and responses but not body text etc.
105 # 2: also print raw lines read and sent before stripping CR/LF
Guido van Rossume65cce51993-11-08 15:05:21 +0000106 def set_debuglevel(self, level):
Guido van Rossum1115ab21992-11-04 15:51:30 +0000107 self.debugging = level
Guido van Rossume65cce51993-11-08 15:05:21 +0000108 debug = set_debuglevel
Guido van Rossum1115ab21992-11-04 15:51:30 +0000109
Guido van Rossumebaf1041995-05-05 15:54:14 +0000110 # Internal: "sanitize" a string for printing
111 def sanitize(self, s):
112 if s[:5] == 'pass ' or s[:5] == 'PASS ':
113 i = len(s)
114 while i > 5 and s[i-1] in '\r\n':
115 i = i-1
116 s = s[:5] + '*'*(i-5) + s[i:]
117 return `s`
118
Guido van Rossum1115ab21992-11-04 15:51:30 +0000119 # Internal: send one line to the server, appending CRLF
120 def putline(self, line):
121 line = line + CRLF
Guido van Rossumebaf1041995-05-05 15:54:14 +0000122 if self.debugging > 1: print '*put*', self.sanitize(line)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000123 self.sock.send(line)
124
125 # Internal: send one command to the server (through putline())
126 def putcmd(self, line):
Guido van Rossumebaf1041995-05-05 15:54:14 +0000127 if self.debugging: print '*cmd*', self.sanitize(line)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000128 self.putline(line)
129
130 # Internal: return one line from the server, stripping CRLF.
131 # Raise EOFError if the connection is closed
132 def getline(self):
133 line = self.file.readline()
134 if self.debugging > 1:
Guido van Rossumebaf1041995-05-05 15:54:14 +0000135 print '*get*', self.sanitize(line)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000136 if not line: raise EOFError
137 if line[-2:] == CRLF: line = line[:-2]
138 elif line[-1:] in CRLF: line = line[:-1]
139 return line
140
141 # Internal: get a response from the server, which may possibly
142 # consist of multiple lines. Return a single string with no
143 # trailing CRLF. If the response consists of multiple lines,
144 # these are separated by '\n' characters in the string
145 def getmultiline(self):
146 line = self.getline()
147 if line[3:4] == '-':
148 code = line[:3]
149 while 1:
150 nextline = self.getline()
151 line = line + ('\n' + nextline)
152 if nextline[:3] == code and \
153 nextline[3:4] <> '-':
154 break
155 return line
156
157 # Internal: get a response from the server.
158 # Raise various errors if the response indicates an error
159 def getresp(self):
160 resp = self.getmultiline()
Guido van Rossumebaf1041995-05-05 15:54:14 +0000161 if self.debugging: print '*resp*', self.sanitize(resp)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000162 self.lastresp = resp[:3]
163 c = resp[:1]
164 if c == '4':
Guido van Rossumc567c601992-11-05 22:22:37 +0000165 raise error_temp, resp
Guido van Rossum1115ab21992-11-04 15:51:30 +0000166 if c == '5':
Guido van Rossumc567c601992-11-05 22:22:37 +0000167 raise error_perm, resp
Guido van Rossum1115ab21992-11-04 15:51:30 +0000168 if c not in '123':
Guido van Rossumc567c601992-11-05 22:22:37 +0000169 raise error_proto, resp
Guido van Rossum1115ab21992-11-04 15:51:30 +0000170 return resp
171
Guido van Rossumc567c601992-11-05 22:22:37 +0000172 # Expect a response beginning with '2'
173 def voidresp(self):
174 resp = self.getresp()
175 if resp[0] <> '2':
176 raise error_reply, resp
177
Guido van Rossumd3166071993-05-24 14:16:22 +0000178 # Abort a file transfer. Uses out-of-band data.
179 # This does not follow the procedure from the RFC to send Telnet
180 # IP and Synch; that doesn't seem to work with the servers I've
181 # tried. Instead, just send the ABOR command as OOB data.
182 def abort(self):
183 line = 'ABOR' + CRLF
Guido van Rossumebaf1041995-05-05 15:54:14 +0000184 if self.debugging > 1: print '*put urgent*', self.sanitize(line)
Guido van Rossumd3166071993-05-24 14:16:22 +0000185 self.sock.send(line, MSG_OOB)
186 resp = self.getmultiline()
187 if resp[:3] not in ('426', '226'):
188 raise error_proto, resp
189
Guido van Rossum1115ab21992-11-04 15:51:30 +0000190 # Send a command and return the response
191 def sendcmd(self, cmd):
192 self.putcmd(cmd)
193 return self.getresp()
194
Guido van Rossumc68a4011992-11-05 23:01:42 +0000195 # Send a command and expect a response beginning with '2'
Guido van Rossumc567c601992-11-05 22:22:37 +0000196 def voidcmd(self, cmd):
Guido van Rossumc68a4011992-11-05 23:01:42 +0000197 self.putcmd(cmd)
198 self.voidresp()
Guido van Rossumc567c601992-11-05 22:22:37 +0000199
Guido van Rossum1115ab21992-11-04 15:51:30 +0000200 # Send a PORT command with the current host and the given port number
201 def sendport(self, port):
202 hostname = socket.gethostname()
203 hostaddr = socket.gethostbyname(hostname)
204 hbytes = string.splitfields(hostaddr, '.')
205 pbytes = [`port/256`, `port%256`]
206 bytes = hbytes + pbytes
207 cmd = 'PORT ' + string.joinfields(bytes, ',')
Guido van Rossumc567c601992-11-05 22:22:37 +0000208 self.voidcmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000209
210 # Create a new socket and send a PORT command for it
211 def makeport(self):
212 global nextport
Guido van Rossum1115ab21992-11-04 15:51:30 +0000213 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000214 sock.listen(1)
215 host, port = sock.getsockname()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000216 resp = self.sendport(port)
217 return sock
218
Guido van Rossumc567c601992-11-05 22:22:37 +0000219 # Send a port command and a transfer command, accept the connection
220 # and return the socket for the connection
221 def transfercmd(self, cmd):
Guido van Rossum1115ab21992-11-04 15:51:30 +0000222 sock = self.makeport()
223 resp = self.sendcmd(cmd)
224 if resp[0] <> '1':
225 raise error_reply, resp
Guido van Rossumc567c601992-11-05 22:22:37 +0000226 conn, sockaddr = sock.accept()
227 return conn
228
229 # Login, default anonymous
Guido van Rossumb6775db1994-08-01 11:34:53 +0000230 def login(self, user = '', passwd = '', acct = ''):
Guido van Rossumc567c601992-11-05 22:22:37 +0000231 if not user: user = 'anonymous'
232 if user == 'anonymous' and passwd in ('', '-'):
233 thishost = socket.gethostname()
Jack Jansen2db6bfc1995-05-04 15:02:18 +0000234 # Make sure it is fully qualified
235 if not '.' in thishost:
236 thisaddr = socket.gethostbyname(thishost)
237 thishost = socket.gethostbyaddr(thisaddr)[0]
Jack Jansen40b98351995-01-19 12:24:45 +0000238 try:
239 if os.environ.has_key('LOGNAME'):
240 realuser = os.environ['LOGNAME']
241 elif os.environ.has_key('USER'):
242 realuser = os.environ['USER']
243 else:
244 realuser = 'anonymous'
245 except AttributeError:
246 # Not all systems have os.environ....
Guido van Rossumc567c601992-11-05 22:22:37 +0000247 realuser = 'anonymous'
248 passwd = passwd + realuser + '@' + thishost
249 resp = self.sendcmd('USER ' + user)
250 if resp[0] == '3': resp = self.sendcmd('PASS ' + passwd)
251 if resp[0] == '3': resp = self.sendcmd('ACCT ' + acct)
252 if resp[0] <> '2':
253 raise error_reply, resp
254
255 # Retrieve data in binary mode.
256 # The argument is a RETR command.
257 # The callback function is called for each block.
258 # This creates a new port for you
259 def retrbinary(self, cmd, callback, blocksize):
260 self.voidcmd('TYPE I')
261 conn = self.transfercmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000262 while 1:
263 data = conn.recv(blocksize)
264 if not data:
265 break
266 callback(data)
267 conn.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000268 self.voidresp()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000269
Guido van Rossumc567c601992-11-05 22:22:37 +0000270 # Retrieve data in line mode.
Guido van Rossum1115ab21992-11-04 15:51:30 +0000271 # The argument is a RETR or LIST command.
272 # The callback function is called for each line, with trailing
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000273 # CRLF stripped. This creates a new port for you.
274 # print_lines is the default callback
Guido van Rossumb6775db1994-08-01 11:34:53 +0000275 def retrlines(self, cmd, callback = None):
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000276 if not callback: callback = print_line
Guido van Rossumc567c601992-11-05 22:22:37 +0000277 resp = self.sendcmd('TYPE A')
278 conn = self.transfercmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000279 fp = conn.makefile('r')
280 while 1:
281 line = fp.readline()
282 if not line:
283 break
284 if line[-2:] == CRLF:
285 line = line[:-2]
286 elif line[:-1] == '\n':
287 line = line[:-1]
288 callback(line)
289 fp.close()
290 conn.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000291 self.voidresp()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000292
Guido van Rossumc567c601992-11-05 22:22:37 +0000293 # Store a file in binary mode
294 def storbinary(self, cmd, fp, blocksize):
295 self.voidcmd('TYPE I')
296 conn = self.transfercmd(cmd)
297 while 1:
298 buf = fp.read(blocksize)
299 if not buf: break
300 conn.send(buf)
301 conn.close()
302 self.voidresp()
303
304 # Store a file in line mode
305 def storlines(self, cmd, fp):
306 self.voidcmd('TYPE A')
307 conn = self.transfercmd(cmd)
308 while 1:
309 buf = fp.readline()
310 if not buf: break
311 if buf[-2:] <> CRLF:
312 if buf[-1] in CRLF: buf = buf[:-1]
313 buf = buf + CRLF
314 conn.send(buf)
315 conn.close()
316 self.voidresp()
317
318 # Return a list of files in a given directory (default the current)
319 def nlst(self, *args):
320 cmd = 'NLST'
321 for arg in args:
322 cmd = cmd + (' ' + arg)
323 files = []
324 self.retrlines(cmd, files.append)
325 return files
326
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000327 # List a directory in long form. By default list current directory
328 # to stdout. Optional last argument is callback function;
329 # all non-empty arguments before it are concatenated to the
330 # LIST command. (This *should* only be used for a pathname.)
331 def dir(self, *args):
332 cmd = 'LIST'
333 func = None
334 if args[-1:] and type(args[-1]) != type(''):
335 args, func = args[:-1], args[-1]
336 for arg in args:
337 if arg:
338 cmd = cmd + (' ' + arg)
339 self.retrlines(cmd, func)
340
Guido van Rossumc567c601992-11-05 22:22:37 +0000341 # Rename a file
342 def rename(self, fromname, toname):
343 resp = self.sendcmd('RNFR ' + fromname)
344 if resp[0] <> '3':
Guido van Rossum1115ab21992-11-04 15:51:30 +0000345 raise error_reply, resp
Guido van Rossumc567c601992-11-05 22:22:37 +0000346 self.voidcmd('RNTO ' + toname)
347
Guido van Rossum02cf5821993-05-17 08:00:02 +0000348 # Change to a directory
349 def cwd(self, dirname):
Guido van Rossumdf563861993-07-06 15:19:36 +0000350 if dirname == '..':
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000351 try:
352 self.voidcmd('CDUP')
353 return
354 except error_perm, msg:
355 if msg[:3] != '500':
356 raise error_perm, msg
357 cmd = 'CWD ' + dirname
Guido van Rossumdf563861993-07-06 15:19:36 +0000358 self.voidcmd(cmd)
Guido van Rossum02cf5821993-05-17 08:00:02 +0000359
Guido van Rossum17ed1ae1993-06-01 13:21:04 +0000360 # Retrieve the size of a file
361 def size(self, filename):
362 resp = self.sendcmd('SIZE ' + filename)
363 if resp[:3] == '213':
364 return string.atoi(string.strip(resp[3:]))
365
Guido van Rossumc567c601992-11-05 22:22:37 +0000366 # Make a directory, return its full pathname
367 def mkd(self, dirname):
368 resp = self.sendcmd('MKD ' + dirname)
369 return parse257(resp)
370
371 # Return current wording directory
372 def pwd(self):
373 resp = self.sendcmd('PWD')
374 return parse257(resp)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000375
376 # Quit, and close the connection
377 def quit(self):
Guido van Rossumc567c601992-11-05 22:22:37 +0000378 self.voidcmd('QUIT')
Guido van Rossum17ed1ae1993-06-01 13:21:04 +0000379 self.close()
380
381 # Close the connection without assuming anything about it
382 def close(self):
Guido van Rossum1115ab21992-11-04 15:51:30 +0000383 self.file.close()
384 self.sock.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000385 del self.file, self.sock
386
387
388# Parse a response type 257
389def parse257(resp):
390 if resp[:3] <> '257':
391 raise error_reply, resp
392 if resp[3:5] <> ' "':
393 return '' # Not compliant to RFC 959, but UNIX ftpd does this
394 dirname = ''
395 i = 5
396 n = len(resp)
397 while i < n:
398 c = resp[i]
399 i = i+1
400 if c == '"':
401 if i >= n or resp[i] <> '"':
402 break
403 i = i+1
404 dirname = dirname + c
405 return dirname
Guido van Rossum1115ab21992-11-04 15:51:30 +0000406
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000407# Default retrlines callback to print a line
408def print_line(line):
409 print line
410
Guido van Rossum1115ab21992-11-04 15:51:30 +0000411
412# Test program.
413# Usage: ftp [-d] host [-l[dir]] [-d[dir]] [file] ...
414def test():
415 import marshal
Guido van Rossumb6775db1994-08-01 11:34:53 +0000416 debugging = 0
417 while sys.argv[1] == '-d':
418 debugging = debugging+1
419 del sys.argv[1]
420 host = sys.argv[1]
421 ftp = FTP(host)
422 ftp.set_debuglevel(debugging)
423 ftp.login()
424 for file in sys.argv[2:]:
425 if file[:2] == '-l':
426 ftp.dir(file[2:])
427 elif file[:2] == '-d':
428 cmd = 'CWD'
429 if file[2:]: cmd = cmd + ' ' + file[2:]
430 resp = ftp.sendcmd(cmd)
431 else:
432 ftp.retrbinary('RETR ' + file, \
433 sys.stdout.write, 1024)
434 ftp.quit()