blob: f27ab06ac5dd2998990f93134b19bf826de470e6 [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 Rossum303c1791995-06-20 17:21:42 +0000214 sock.bind(('', 0))
Guido van Rossumb6775db1994-08-01 11:34:53 +0000215 sock.listen(1)
216 host, port = sock.getsockname()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000217 resp = self.sendport(port)
218 return sock
219
Guido van Rossumc567c601992-11-05 22:22:37 +0000220 # Send a port command and a transfer command, accept the connection
221 # and return the socket for the connection
222 def transfercmd(self, cmd):
Guido van Rossum1115ab21992-11-04 15:51:30 +0000223 sock = self.makeport()
224 resp = self.sendcmd(cmd)
225 if resp[0] <> '1':
226 raise error_reply, resp
Guido van Rossumc567c601992-11-05 22:22:37 +0000227 conn, sockaddr = sock.accept()
228 return conn
229
230 # Login, default anonymous
Guido van Rossumb6775db1994-08-01 11:34:53 +0000231 def login(self, user = '', passwd = '', acct = ''):
Guido van Rossumc567c601992-11-05 22:22:37 +0000232 if not user: user = 'anonymous'
233 if user == 'anonymous' and passwd in ('', '-'):
234 thishost = socket.gethostname()
Jack Jansen2db6bfc1995-05-04 15:02:18 +0000235 # Make sure it is fully qualified
236 if not '.' in thishost:
237 thisaddr = socket.gethostbyname(thishost)
Guido van Rossum303c1791995-06-20 17:21:42 +0000238 firstname, names, unused = \
239 socket.gethostbyaddr(thisaddr)
240 names.insert(0, firstname)
241 for name in names:
242 if '.' in name:
243 thishost = name
244 break
Jack Jansen40b98351995-01-19 12:24:45 +0000245 try:
246 if os.environ.has_key('LOGNAME'):
247 realuser = os.environ['LOGNAME']
248 elif os.environ.has_key('USER'):
249 realuser = os.environ['USER']
250 else:
251 realuser = 'anonymous'
252 except AttributeError:
253 # Not all systems have os.environ....
Guido van Rossumc567c601992-11-05 22:22:37 +0000254 realuser = 'anonymous'
255 passwd = passwd + realuser + '@' + thishost
256 resp = self.sendcmd('USER ' + user)
257 if resp[0] == '3': resp = self.sendcmd('PASS ' + passwd)
258 if resp[0] == '3': resp = self.sendcmd('ACCT ' + acct)
259 if resp[0] <> '2':
260 raise error_reply, resp
261
262 # Retrieve data in binary mode.
263 # The argument is a RETR command.
264 # The callback function is called for each block.
265 # This creates a new port for you
266 def retrbinary(self, cmd, callback, blocksize):
267 self.voidcmd('TYPE I')
268 conn = self.transfercmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000269 while 1:
270 data = conn.recv(blocksize)
271 if not data:
272 break
273 callback(data)
274 conn.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000275 self.voidresp()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000276
Guido van Rossumc567c601992-11-05 22:22:37 +0000277 # Retrieve data in line mode.
Guido van Rossum1115ab21992-11-04 15:51:30 +0000278 # The argument is a RETR or LIST command.
279 # The callback function is called for each line, with trailing
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000280 # CRLF stripped. This creates a new port for you.
281 # print_lines is the default callback
Guido van Rossumb6775db1994-08-01 11:34:53 +0000282 def retrlines(self, cmd, callback = None):
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000283 if not callback: callback = print_line
Guido van Rossumc567c601992-11-05 22:22:37 +0000284 resp = self.sendcmd('TYPE A')
285 conn = self.transfercmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000286 fp = conn.makefile('r')
287 while 1:
288 line = fp.readline()
289 if not line:
290 break
291 if line[-2:] == CRLF:
292 line = line[:-2]
293 elif line[:-1] == '\n':
294 line = line[:-1]
295 callback(line)
296 fp.close()
297 conn.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000298 self.voidresp()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000299
Guido van Rossumc567c601992-11-05 22:22:37 +0000300 # Store a file in binary mode
301 def storbinary(self, cmd, fp, blocksize):
302 self.voidcmd('TYPE I')
303 conn = self.transfercmd(cmd)
304 while 1:
305 buf = fp.read(blocksize)
306 if not buf: break
307 conn.send(buf)
308 conn.close()
309 self.voidresp()
310
311 # Store a file in line mode
312 def storlines(self, cmd, fp):
313 self.voidcmd('TYPE A')
314 conn = self.transfercmd(cmd)
315 while 1:
316 buf = fp.readline()
317 if not buf: break
318 if buf[-2:] <> CRLF:
319 if buf[-1] in CRLF: buf = buf[:-1]
320 buf = buf + CRLF
321 conn.send(buf)
322 conn.close()
323 self.voidresp()
324
325 # Return a list of files in a given directory (default the current)
326 def nlst(self, *args):
327 cmd = 'NLST'
328 for arg in args:
329 cmd = cmd + (' ' + arg)
330 files = []
331 self.retrlines(cmd, files.append)
332 return files
333
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000334 # List a directory in long form. By default list current directory
335 # to stdout. Optional last argument is callback function;
336 # all non-empty arguments before it are concatenated to the
337 # LIST command. (This *should* only be used for a pathname.)
338 def dir(self, *args):
339 cmd = 'LIST'
340 func = None
341 if args[-1:] and type(args[-1]) != type(''):
342 args, func = args[:-1], args[-1]
343 for arg in args:
344 if arg:
345 cmd = cmd + (' ' + arg)
346 self.retrlines(cmd, func)
347
Guido van Rossumc567c601992-11-05 22:22:37 +0000348 # Rename a file
349 def rename(self, fromname, toname):
350 resp = self.sendcmd('RNFR ' + fromname)
351 if resp[0] <> '3':
Guido van Rossum1115ab21992-11-04 15:51:30 +0000352 raise error_reply, resp
Guido van Rossumc567c601992-11-05 22:22:37 +0000353 self.voidcmd('RNTO ' + toname)
354
Guido van Rossum02cf5821993-05-17 08:00:02 +0000355 # Change to a directory
356 def cwd(self, dirname):
Guido van Rossumdf563861993-07-06 15:19:36 +0000357 if dirname == '..':
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000358 try:
359 self.voidcmd('CDUP')
360 return
361 except error_perm, msg:
362 if msg[:3] != '500':
363 raise error_perm, msg
364 cmd = 'CWD ' + dirname
Guido van Rossumdf563861993-07-06 15:19:36 +0000365 self.voidcmd(cmd)
Guido van Rossum02cf5821993-05-17 08:00:02 +0000366
Guido van Rossum17ed1ae1993-06-01 13:21:04 +0000367 # Retrieve the size of a file
368 def size(self, filename):
369 resp = self.sendcmd('SIZE ' + filename)
370 if resp[:3] == '213':
371 return string.atoi(string.strip(resp[3:]))
372
Guido van Rossumc567c601992-11-05 22:22:37 +0000373 # Make a directory, return its full pathname
374 def mkd(self, dirname):
375 resp = self.sendcmd('MKD ' + dirname)
376 return parse257(resp)
377
378 # Return current wording directory
379 def pwd(self):
380 resp = self.sendcmd('PWD')
381 return parse257(resp)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000382
383 # Quit, and close the connection
384 def quit(self):
Guido van Rossumc567c601992-11-05 22:22:37 +0000385 self.voidcmd('QUIT')
Guido van Rossum17ed1ae1993-06-01 13:21:04 +0000386 self.close()
387
388 # Close the connection without assuming anything about it
389 def close(self):
Guido van Rossum1115ab21992-11-04 15:51:30 +0000390 self.file.close()
391 self.sock.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000392 del self.file, self.sock
393
394
395# Parse a response type 257
396def parse257(resp):
397 if resp[:3] <> '257':
398 raise error_reply, resp
399 if resp[3:5] <> ' "':
400 return '' # Not compliant to RFC 959, but UNIX ftpd does this
401 dirname = ''
402 i = 5
403 n = len(resp)
404 while i < n:
405 c = resp[i]
406 i = i+1
407 if c == '"':
408 if i >= n or resp[i] <> '"':
409 break
410 i = i+1
411 dirname = dirname + c
412 return dirname
Guido van Rossum1115ab21992-11-04 15:51:30 +0000413
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000414# Default retrlines callback to print a line
415def print_line(line):
416 print line
417
Guido van Rossum1115ab21992-11-04 15:51:30 +0000418
419# Test program.
420# Usage: ftp [-d] host [-l[dir]] [-d[dir]] [file] ...
421def test():
422 import marshal
Guido van Rossumb6775db1994-08-01 11:34:53 +0000423 debugging = 0
424 while sys.argv[1] == '-d':
425 debugging = debugging+1
426 del sys.argv[1]
427 host = sys.argv[1]
428 ftp = FTP(host)
429 ftp.set_debuglevel(debugging)
430 ftp.login()
431 for file in sys.argv[2:]:
432 if file[:2] == '-l':
433 ftp.dir(file[2:])
434 elif file[:2] == '-d':
435 cmd = 'CWD'
436 if file[2:]: cmd = cmd + ' ' + file[2:]
437 resp = ftp.sendcmd(cmd)
438 else:
439 ftp.retrbinary('RETR ' + file, \
440 sys.stdout.write, 1024)
441 ftp.quit()