blob: 8801dfde364dd1c7a6ad408632fac3bdf564a6e2 [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
Guido van Rossum221ec0b1995-08-04 04:39:30 +0000201 def sendport(self, host, port):
202 hbytes = string.splitfields(host, '.')
Guido van Rossum1115ab21992-11-04 15:51:30 +0000203 pbytes = [`port/256`, `port%256`]
204 bytes = hbytes + pbytes
205 cmd = 'PORT ' + string.joinfields(bytes, ',')
Guido van Rossumc567c601992-11-05 22:22:37 +0000206 self.voidcmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000207
208 # Create a new socket and send a PORT command for it
209 def makeport(self):
210 global nextport
Guido van Rossum1115ab21992-11-04 15:51:30 +0000211 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Guido van Rossum303c1791995-06-20 17:21:42 +0000212 sock.bind(('', 0))
Guido van Rossumb6775db1994-08-01 11:34:53 +0000213 sock.listen(1)
Guido van Rossum221ec0b1995-08-04 04:39:30 +0000214 dummyhost, port = sock.getsockname() # Get proper port
215 host, dummyport = self.sock.getsockname() # Get proper host
216 resp = self.sendport(host, port)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000217 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)
Guido van Rossum303c1791995-06-20 17:21:42 +0000237 firstname, names, unused = \
238 socket.gethostbyaddr(thisaddr)
239 names.insert(0, firstname)
240 for name in names:
241 if '.' in name:
242 thishost = name
243 break
Jack Jansen40b98351995-01-19 12:24:45 +0000244 try:
245 if os.environ.has_key('LOGNAME'):
246 realuser = os.environ['LOGNAME']
247 elif os.environ.has_key('USER'):
248 realuser = os.environ['USER']
249 else:
250 realuser = 'anonymous'
251 except AttributeError:
252 # Not all systems have os.environ....
Guido van Rossumc567c601992-11-05 22:22:37 +0000253 realuser = 'anonymous'
254 passwd = passwd + realuser + '@' + thishost
255 resp = self.sendcmd('USER ' + user)
256 if resp[0] == '3': resp = self.sendcmd('PASS ' + passwd)
257 if resp[0] == '3': resp = self.sendcmd('ACCT ' + acct)
258 if resp[0] <> '2':
259 raise error_reply, resp
260
261 # Retrieve data in binary mode.
262 # The argument is a RETR command.
263 # The callback function is called for each block.
264 # This creates a new port for you
265 def retrbinary(self, cmd, callback, blocksize):
266 self.voidcmd('TYPE I')
267 conn = self.transfercmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000268 while 1:
269 data = conn.recv(blocksize)
270 if not data:
271 break
272 callback(data)
273 conn.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000274 self.voidresp()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000275
Guido van Rossumc567c601992-11-05 22:22:37 +0000276 # Retrieve data in line mode.
Guido van Rossum1115ab21992-11-04 15:51:30 +0000277 # The argument is a RETR or LIST command.
278 # The callback function is called for each line, with trailing
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000279 # CRLF stripped. This creates a new port for you.
280 # print_lines is the default callback
Guido van Rossumb6775db1994-08-01 11:34:53 +0000281 def retrlines(self, cmd, callback = None):
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000282 if not callback: callback = print_line
Guido van Rossumc567c601992-11-05 22:22:37 +0000283 resp = self.sendcmd('TYPE A')
284 conn = self.transfercmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000285 fp = conn.makefile('r')
286 while 1:
287 line = fp.readline()
288 if not line:
289 break
290 if line[-2:] == CRLF:
291 line = line[:-2]
292 elif line[:-1] == '\n':
293 line = line[:-1]
294 callback(line)
295 fp.close()
296 conn.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000297 self.voidresp()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000298
Guido van Rossumc567c601992-11-05 22:22:37 +0000299 # Store a file in binary mode
300 def storbinary(self, cmd, fp, blocksize):
301 self.voidcmd('TYPE I')
302 conn = self.transfercmd(cmd)
303 while 1:
304 buf = fp.read(blocksize)
305 if not buf: break
306 conn.send(buf)
307 conn.close()
308 self.voidresp()
309
310 # Store a file in line mode
311 def storlines(self, cmd, fp):
312 self.voidcmd('TYPE A')
313 conn = self.transfercmd(cmd)
314 while 1:
315 buf = fp.readline()
316 if not buf: break
317 if buf[-2:] <> CRLF:
318 if buf[-1] in CRLF: buf = buf[:-1]
319 buf = buf + CRLF
320 conn.send(buf)
321 conn.close()
322 self.voidresp()
323
324 # Return a list of files in a given directory (default the current)
325 def nlst(self, *args):
326 cmd = 'NLST'
327 for arg in args:
328 cmd = cmd + (' ' + arg)
329 files = []
330 self.retrlines(cmd, files.append)
331 return files
332
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000333 # List a directory in long form. By default list current directory
334 # to stdout. Optional last argument is callback function;
335 # all non-empty arguments before it are concatenated to the
336 # LIST command. (This *should* only be used for a pathname.)
337 def dir(self, *args):
338 cmd = 'LIST'
339 func = None
340 if args[-1:] and type(args[-1]) != type(''):
341 args, func = args[:-1], args[-1]
342 for arg in args:
343 if arg:
344 cmd = cmd + (' ' + arg)
345 self.retrlines(cmd, func)
346
Guido van Rossumc567c601992-11-05 22:22:37 +0000347 # Rename a file
348 def rename(self, fromname, toname):
349 resp = self.sendcmd('RNFR ' + fromname)
350 if resp[0] <> '3':
Guido van Rossum1115ab21992-11-04 15:51:30 +0000351 raise error_reply, resp
Guido van Rossumc567c601992-11-05 22:22:37 +0000352 self.voidcmd('RNTO ' + toname)
353
Guido van Rossum02cf5821993-05-17 08:00:02 +0000354 # Change to a directory
355 def cwd(self, dirname):
Guido van Rossumdf563861993-07-06 15:19:36 +0000356 if dirname == '..':
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000357 try:
358 self.voidcmd('CDUP')
359 return
360 except error_perm, msg:
361 if msg[:3] != '500':
362 raise error_perm, msg
363 cmd = 'CWD ' + dirname
Guido van Rossumdf563861993-07-06 15:19:36 +0000364 self.voidcmd(cmd)
Guido van Rossum02cf5821993-05-17 08:00:02 +0000365
Guido van Rossum17ed1ae1993-06-01 13:21:04 +0000366 # Retrieve the size of a file
367 def size(self, filename):
368 resp = self.sendcmd('SIZE ' + filename)
369 if resp[:3] == '213':
370 return string.atoi(string.strip(resp[3:]))
371
Guido van Rossumc567c601992-11-05 22:22:37 +0000372 # Make a directory, return its full pathname
373 def mkd(self, dirname):
374 resp = self.sendcmd('MKD ' + dirname)
375 return parse257(resp)
376
377 # Return current wording directory
378 def pwd(self):
379 resp = self.sendcmd('PWD')
380 return parse257(resp)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000381
382 # Quit, and close the connection
383 def quit(self):
Guido van Rossumc567c601992-11-05 22:22:37 +0000384 self.voidcmd('QUIT')
Guido van Rossum17ed1ae1993-06-01 13:21:04 +0000385 self.close()
386
387 # Close the connection without assuming anything about it
388 def close(self):
Guido van Rossum1115ab21992-11-04 15:51:30 +0000389 self.file.close()
390 self.sock.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000391 del self.file, self.sock
392
393
394# Parse a response type 257
395def parse257(resp):
396 if resp[:3] <> '257':
397 raise error_reply, resp
398 if resp[3:5] <> ' "':
399 return '' # Not compliant to RFC 959, but UNIX ftpd does this
400 dirname = ''
401 i = 5
402 n = len(resp)
403 while i < n:
404 c = resp[i]
405 i = i+1
406 if c == '"':
407 if i >= n or resp[i] <> '"':
408 break
409 i = i+1
410 dirname = dirname + c
411 return dirname
Guido van Rossum1115ab21992-11-04 15:51:30 +0000412
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000413# Default retrlines callback to print a line
414def print_line(line):
415 print line
416
Guido van Rossum1115ab21992-11-04 15:51:30 +0000417
418# Test program.
419# Usage: ftp [-d] host [-l[dir]] [-d[dir]] [file] ...
420def test():
421 import marshal
Guido van Rossumb6775db1994-08-01 11:34:53 +0000422 debugging = 0
423 while sys.argv[1] == '-d':
424 debugging = debugging+1
425 del sys.argv[1]
426 host = sys.argv[1]
427 ftp = FTP(host)
428 ftp.set_debuglevel(debugging)
429 ftp.login()
430 for file in sys.argv[2:]:
431 if file[:2] == '-l':
432 ftp.dir(file[2:])
433 elif file[:2] == '-d':
434 cmd = 'CWD'
435 if file[2:]: cmd = cmd + ' ' + file[2:]
436 resp = ftp.sendcmd(cmd)
437 else:
438 ftp.retrbinary('RETR ' + file, \
439 sys.stdout.write, 1024)
440 ftp.quit()
Guido van Rossum221ec0b1995-08-04 04:39:30 +0000441
442
443if __name__ == '__main__':
444 test()