blob: e6e1a3aafc0fc4df555fe6d70c64ab450c8073ed [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 Rossumc0e68d11995-09-30 16:51:50 +000011# >>> ftp = FTP('ftp.python.org') # 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 Rossumc0e68d11995-09-30 16:51:50 +000014# total 9
15# drwxr-xr-x 8 root wheel 1024 Jan 3 1994 .
16# drwxr-xr-x 8 root wheel 1024 Jan 3 1994 ..
17# drwxr-xr-x 2 root wheel 1024 Jan 3 1994 bin
18# drwxr-xr-x 2 root wheel 1024 Jan 3 1994 etc
19# d-wxrwxr-x 2 ftp wheel 1024 Sep 5 13:43 incoming
20# drwxr-xr-x 2 root wheel 1024 Nov 17 1993 lib
21# drwxr-xr-x 6 1094 wheel 1024 Sep 13 19:07 pub
22# drwxr-xr-x 3 root wheel 1024 Jan 3 1994 usr
23# -rw-r--r-- 1 root root 312 Aug 1 1994 welcome.msg
Guido van Rossumc567c601992-11-05 22:22:37 +000024# >>> ftp.quit()
Guido van Rossumc0e68d11995-09-30 16:51:50 +000025# >>>
Guido van Rossumc567c601992-11-05 22:22:37 +000026#
Guido van Rossumb6775db1994-08-01 11:34:53 +000027# To download a file, use ftp.retrlines('RETR ' + filename),
Guido van Rossumc567c601992-11-05 22:22:37 +000028# or ftp.retrbinary() with slightly different arguments.
29# To upload a file, use ftp.storlines() or ftp.storbinary(), which have
Guido van Rossumc0e68d11995-09-30 16:51:50 +000030# an open file as argument (see their definitions below for details).
Guido van Rossumc567c601992-11-05 22:22:37 +000031# The download/upload functions first issue appropriate TYPE and PORT
32# commands.
33
34
Guido van Rossum1115ab21992-11-04 15:51:30 +000035import os
36import sys
Guido van Rossum1115ab21992-11-04 15:51:30 +000037import string
38
Guido van Rossumb6775db1994-08-01 11:34:53 +000039# Import SOCKS module if it exists, else standard socket module socket
40try:
41 import SOCKS; socket = SOCKS
42except ImportError:
43 import socket
44
Guido van Rossum1115ab21992-11-04 15:51:30 +000045
Guido van Rossumd3166071993-05-24 14:16:22 +000046# Magic number from <socket.h>
47MSG_OOB = 0x1 # Process data out of band
48
49
Guido van Rossumc567c601992-11-05 22:22:37 +000050# The standard FTP server control port
Guido van Rossum1115ab21992-11-04 15:51:30 +000051FTP_PORT = 21
Guido van Rossum1115ab21992-11-04 15:51:30 +000052
53
Guido van Rossum21974791992-11-06 13:34:17 +000054# Exception raised when an error or invalid response is received
Guido van Rossumc567c601992-11-05 22:22:37 +000055error_reply = 'ftplib.error_reply' # unexpected [123]xx reply
56error_temp = 'ftplib.error_temp' # 4xx errors
57error_perm = 'ftplib.error_perm' # 5xx errors
58error_proto = 'ftplib.error_proto' # response does not begin with [1-5]
Guido van Rossum1115ab21992-11-04 15:51:30 +000059
60
Guido van Rossum21974791992-11-06 13:34:17 +000061# All exceptions (hopefully) that may be raised here and that aren't
62# (always) programming errors on our side
63all_errors = (error_reply, error_temp, error_perm, error_proto, \
Guido van Rossumc0e68d11995-09-30 16:51:50 +000064 socket.error, IOError, EOFError)
Guido van Rossum21974791992-11-06 13:34:17 +000065
66
Guido van Rossum1115ab21992-11-04 15:51:30 +000067# Line terminators (we always output CRLF, but accept any of CRLF, CR, LF)
68CRLF = '\r\n'
69
70
Guido van Rossum1115ab21992-11-04 15:51:30 +000071# The class itself
72class FTP:
73
Guido van Rossum52fc1f61993-06-17 12:38:10 +000074 # New initialization method (called by class instantiation)
75 # Initialize host to localhost, port to standard ftp port
Guido van Rossumae3b3a31993-11-30 13:43:54 +000076 # Optional arguments are host (for connect()),
77 # and user, passwd, acct (for login())
Guido van Rossumb6775db1994-08-01 11:34:53 +000078 def __init__(self, host = '', user = '', passwd = '', acct = ''):
Guido van Rossum52fc1f61993-06-17 12:38:10 +000079 # Initialize the instance to something mostly harmless
Guido van Rossum1115ab21992-11-04 15:51:30 +000080 self.debugging = 0
Guido van Rossum52fc1f61993-06-17 12:38:10 +000081 self.host = ''
82 self.port = FTP_PORT
83 self.sock = None
84 self.file = None
85 self.welcome = None
Guido van Rossumb6775db1994-08-01 11:34:53 +000086 if host:
87 self.connect(host)
88 if user: self.login(user, passwd, acct)
Guido van Rossum52fc1f61993-06-17 12:38:10 +000089
Guido van Rossum52fc1f61993-06-17 12:38:10 +000090 # Connect to host. Arguments:
91 # - host: hostname to connect to (default previous host)
92 # - port: port to connect to (default previous port)
Guido van Rossumb6775db1994-08-01 11:34:53 +000093 def connect(self, host = '', port = 0):
94 if host: self.host = host
95 if port: self.port = port
Guido van Rossum1115ab21992-11-04 15:51:30 +000096 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
97 self.sock.connect(self.host, self.port)
98 self.file = self.sock.makefile('r')
99 self.welcome = self.getresp()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000100
101 # Get the welcome message from the server
Guido van Rossum7bc817d1993-12-17 15:25:27 +0000102 # (this is read and squirreled away by connect())
Guido van Rossum1115ab21992-11-04 15:51:30 +0000103 def getwelcome(self):
Guido van Rossumebaf1041995-05-05 15:54:14 +0000104 if self.debugging:
105 print '*welcome*', self.sanitize(self.welcome)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000106 return self.welcome
107
108 # Set the debugging level. Argument level means:
109 # 0: no debugging output (default)
110 # 1: print commands and responses but not body text etc.
111 # 2: also print raw lines read and sent before stripping CR/LF
Guido van Rossume65cce51993-11-08 15:05:21 +0000112 def set_debuglevel(self, level):
Guido van Rossum1115ab21992-11-04 15:51:30 +0000113 self.debugging = level
Guido van Rossume65cce51993-11-08 15:05:21 +0000114 debug = set_debuglevel
Guido van Rossum1115ab21992-11-04 15:51:30 +0000115
Guido van Rossumebaf1041995-05-05 15:54:14 +0000116 # Internal: "sanitize" a string for printing
117 def sanitize(self, s):
118 if s[:5] == 'pass ' or s[:5] == 'PASS ':
119 i = len(s)
120 while i > 5 and s[i-1] in '\r\n':
121 i = i-1
122 s = s[:5] + '*'*(i-5) + s[i:]
123 return `s`
124
Guido van Rossum1115ab21992-11-04 15:51:30 +0000125 # Internal: send one line to the server, appending CRLF
126 def putline(self, line):
127 line = line + CRLF
Guido van Rossumebaf1041995-05-05 15:54:14 +0000128 if self.debugging > 1: print '*put*', self.sanitize(line)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000129 self.sock.send(line)
130
131 # Internal: send one command to the server (through putline())
132 def putcmd(self, line):
Guido van Rossumebaf1041995-05-05 15:54:14 +0000133 if self.debugging: print '*cmd*', self.sanitize(line)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000134 self.putline(line)
135
136 # Internal: return one line from the server, stripping CRLF.
137 # Raise EOFError if the connection is closed
138 def getline(self):
139 line = self.file.readline()
140 if self.debugging > 1:
Guido van Rossumebaf1041995-05-05 15:54:14 +0000141 print '*get*', self.sanitize(line)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000142 if not line: raise EOFError
143 if line[-2:] == CRLF: line = line[:-2]
144 elif line[-1:] in CRLF: line = line[:-1]
145 return line
146
147 # Internal: get a response from the server, which may possibly
148 # consist of multiple lines. Return a single string with no
149 # trailing CRLF. If the response consists of multiple lines,
150 # these are separated by '\n' characters in the string
151 def getmultiline(self):
152 line = self.getline()
153 if line[3:4] == '-':
154 code = line[:3]
155 while 1:
156 nextline = self.getline()
157 line = line + ('\n' + nextline)
158 if nextline[:3] == code and \
159 nextline[3:4] <> '-':
160 break
161 return line
162
163 # Internal: get a response from the server.
164 # Raise various errors if the response indicates an error
165 def getresp(self):
166 resp = self.getmultiline()
Guido van Rossumebaf1041995-05-05 15:54:14 +0000167 if self.debugging: print '*resp*', self.sanitize(resp)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000168 self.lastresp = resp[:3]
169 c = resp[:1]
170 if c == '4':
Guido van Rossumc567c601992-11-05 22:22:37 +0000171 raise error_temp, resp
Guido van Rossum1115ab21992-11-04 15:51:30 +0000172 if c == '5':
Guido van Rossumc567c601992-11-05 22:22:37 +0000173 raise error_perm, resp
Guido van Rossum1115ab21992-11-04 15:51:30 +0000174 if c not in '123':
Guido van Rossumc567c601992-11-05 22:22:37 +0000175 raise error_proto, resp
Guido van Rossum1115ab21992-11-04 15:51:30 +0000176 return resp
177
Guido van Rossumc567c601992-11-05 22:22:37 +0000178 # Expect a response beginning with '2'
179 def voidresp(self):
180 resp = self.getresp()
181 if resp[0] <> '2':
182 raise error_reply, resp
183
Guido van Rossumd3166071993-05-24 14:16:22 +0000184 # Abort a file transfer. Uses out-of-band data.
185 # This does not follow the procedure from the RFC to send Telnet
186 # IP and Synch; that doesn't seem to work with the servers I've
187 # tried. Instead, just send the ABOR command as OOB data.
188 def abort(self):
189 line = 'ABOR' + CRLF
Guido van Rossumebaf1041995-05-05 15:54:14 +0000190 if self.debugging > 1: print '*put urgent*', self.sanitize(line)
Guido van Rossumd3166071993-05-24 14:16:22 +0000191 self.sock.send(line, MSG_OOB)
192 resp = self.getmultiline()
193 if resp[:3] not in ('426', '226'):
194 raise error_proto, resp
195
Guido van Rossum1115ab21992-11-04 15:51:30 +0000196 # Send a command and return the response
197 def sendcmd(self, cmd):
198 self.putcmd(cmd)
199 return self.getresp()
200
Guido van Rossumc68a4011992-11-05 23:01:42 +0000201 # Send a command and expect a response beginning with '2'
Guido van Rossumc567c601992-11-05 22:22:37 +0000202 def voidcmd(self, cmd):
Guido van Rossumc68a4011992-11-05 23:01:42 +0000203 self.putcmd(cmd)
204 self.voidresp()
Guido van Rossumc567c601992-11-05 22:22:37 +0000205
Guido van Rossum1115ab21992-11-04 15:51:30 +0000206 # Send a PORT command with the current host and the given port number
Guido van Rossum221ec0b1995-08-04 04:39:30 +0000207 def sendport(self, host, port):
208 hbytes = string.splitfields(host, '.')
Guido van Rossum1115ab21992-11-04 15:51:30 +0000209 pbytes = [`port/256`, `port%256`]
210 bytes = hbytes + pbytes
211 cmd = 'PORT ' + string.joinfields(bytes, ',')
Guido van Rossumc567c601992-11-05 22:22:37 +0000212 self.voidcmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000213
214 # Create a new socket and send a PORT command for it
215 def makeport(self):
216 global nextport
Guido van Rossum1115ab21992-11-04 15:51:30 +0000217 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Guido van Rossum303c1791995-06-20 17:21:42 +0000218 sock.bind(('', 0))
Guido van Rossumb6775db1994-08-01 11:34:53 +0000219 sock.listen(1)
Guido van Rossum221ec0b1995-08-04 04:39:30 +0000220 dummyhost, port = sock.getsockname() # Get proper port
221 host, dummyport = self.sock.getsockname() # Get proper host
222 resp = self.sendport(host, port)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000223 return sock
224
Guido van Rossumc567c601992-11-05 22:22:37 +0000225 # Send a port command and a transfer command, accept the connection
226 # and return the socket for the connection
227 def transfercmd(self, cmd):
Guido van Rossum1115ab21992-11-04 15:51:30 +0000228 sock = self.makeport()
229 resp = self.sendcmd(cmd)
230 if resp[0] <> '1':
231 raise error_reply, resp
Guido van Rossumc567c601992-11-05 22:22:37 +0000232 conn, sockaddr = sock.accept()
233 return conn
234
235 # Login, default anonymous
Guido van Rossumb6775db1994-08-01 11:34:53 +0000236 def login(self, user = '', passwd = '', acct = ''):
Guido van Rossumc567c601992-11-05 22:22:37 +0000237 if not user: user = 'anonymous'
238 if user == 'anonymous' and passwd in ('', '-'):
239 thishost = socket.gethostname()
Jack Jansen2db6bfc1995-05-04 15:02:18 +0000240 # Make sure it is fully qualified
241 if not '.' in thishost:
242 thisaddr = socket.gethostbyname(thishost)
Guido van Rossum303c1791995-06-20 17:21:42 +0000243 firstname, names, unused = \
244 socket.gethostbyaddr(thisaddr)
245 names.insert(0, firstname)
246 for name in names:
247 if '.' in name:
248 thishost = name
249 break
Jack Jansen40b98351995-01-19 12:24:45 +0000250 try:
251 if os.environ.has_key('LOGNAME'):
252 realuser = os.environ['LOGNAME']
253 elif os.environ.has_key('USER'):
254 realuser = os.environ['USER']
255 else:
256 realuser = 'anonymous'
257 except AttributeError:
258 # Not all systems have os.environ....
Guido van Rossumc567c601992-11-05 22:22:37 +0000259 realuser = 'anonymous'
260 passwd = passwd + realuser + '@' + thishost
261 resp = self.sendcmd('USER ' + user)
262 if resp[0] == '3': resp = self.sendcmd('PASS ' + passwd)
263 if resp[0] == '3': resp = self.sendcmd('ACCT ' + acct)
264 if resp[0] <> '2':
265 raise error_reply, resp
266
267 # Retrieve data in binary mode.
268 # The argument is a RETR command.
269 # The callback function is called for each block.
270 # This creates a new port for you
271 def retrbinary(self, cmd, callback, blocksize):
272 self.voidcmd('TYPE I')
273 conn = self.transfercmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000274 while 1:
275 data = conn.recv(blocksize)
276 if not data:
277 break
278 callback(data)
279 conn.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000280 self.voidresp()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000281
Guido van Rossumc567c601992-11-05 22:22:37 +0000282 # Retrieve data in line mode.
Guido van Rossum1115ab21992-11-04 15:51:30 +0000283 # The argument is a RETR or LIST command.
284 # The callback function is called for each line, with trailing
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000285 # CRLF stripped. This creates a new port for you.
286 # print_lines is the default callback
Guido van Rossumb6775db1994-08-01 11:34:53 +0000287 def retrlines(self, cmd, callback = None):
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000288 if not callback: callback = print_line
Guido van Rossumc567c601992-11-05 22:22:37 +0000289 resp = self.sendcmd('TYPE A')
290 conn = self.transfercmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000291 fp = conn.makefile('r')
292 while 1:
293 line = fp.readline()
Guido van Rossumc0e68d11995-09-30 16:51:50 +0000294 if self.debugging > 2: print '*retr*', `line`
Guido van Rossum1115ab21992-11-04 15:51:30 +0000295 if not line:
296 break
297 if line[-2:] == CRLF:
298 line = line[:-2]
299 elif line[:-1] == '\n':
300 line = line[:-1]
301 callback(line)
302 fp.close()
303 conn.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000304 self.voidresp()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000305
Guido van Rossumc567c601992-11-05 22:22:37 +0000306 # Store a file in binary mode
307 def storbinary(self, cmd, fp, blocksize):
308 self.voidcmd('TYPE I')
309 conn = self.transfercmd(cmd)
310 while 1:
311 buf = fp.read(blocksize)
312 if not buf: break
313 conn.send(buf)
314 conn.close()
315 self.voidresp()
316
317 # Store a file in line mode
318 def storlines(self, cmd, fp):
319 self.voidcmd('TYPE A')
320 conn = self.transfercmd(cmd)
321 while 1:
322 buf = fp.readline()
323 if not buf: break
324 if buf[-2:] <> CRLF:
325 if buf[-1] in CRLF: buf = buf[:-1]
326 buf = buf + CRLF
327 conn.send(buf)
328 conn.close()
329 self.voidresp()
330
Guido van Rossum0eaa74b1996-01-25 18:37:21 +0000331 # Send new account name
332 def acct(self, password):
333 cmd = 'ACCT ' + password
334 self.voidcmd(cmd)
335
Guido van Rossumc567c601992-11-05 22:22:37 +0000336 # Return a list of files in a given directory (default the current)
337 def nlst(self, *args):
338 cmd = 'NLST'
339 for arg in args:
340 cmd = cmd + (' ' + arg)
341 files = []
342 self.retrlines(cmd, files.append)
343 return files
344
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000345 # List a directory in long form. By default list current directory
346 # to stdout. Optional last argument is callback function;
347 # all non-empty arguments before it are concatenated to the
348 # LIST command. (This *should* only be used for a pathname.)
349 def dir(self, *args):
350 cmd = 'LIST'
351 func = None
352 if args[-1:] and type(args[-1]) != type(''):
353 args, func = args[:-1], args[-1]
354 for arg in args:
355 if arg:
356 cmd = cmd + (' ' + arg)
357 self.retrlines(cmd, func)
358
Guido van Rossumc567c601992-11-05 22:22:37 +0000359 # Rename a file
360 def rename(self, fromname, toname):
361 resp = self.sendcmd('RNFR ' + fromname)
362 if resp[0] <> '3':
Guido van Rossum1115ab21992-11-04 15:51:30 +0000363 raise error_reply, resp
Guido van Rossumc567c601992-11-05 22:22:37 +0000364 self.voidcmd('RNTO ' + toname)
365
Guido van Rossuma61bdeb1995-10-11 17:36:31 +0000366 # Delete a file
367 def delete(self, filename):
368 resp = self.sendcmd('DELE ' + filename)
369 if resp[:3] == '250':
370 return
371 elif resp[:1] == '5':
372 raise error_perm, resp
373 else:
374 raise error_reply, resp
375
Guido van Rossum02cf5821993-05-17 08:00:02 +0000376 # Change to a directory
377 def cwd(self, dirname):
Guido van Rossumdf563861993-07-06 15:19:36 +0000378 if dirname == '..':
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000379 try:
380 self.voidcmd('CDUP')
381 return
382 except error_perm, msg:
383 if msg[:3] != '500':
384 raise error_perm, msg
385 cmd = 'CWD ' + dirname
Guido van Rossumdf563861993-07-06 15:19:36 +0000386 self.voidcmd(cmd)
Guido van Rossum02cf5821993-05-17 08:00:02 +0000387
Guido van Rossum17ed1ae1993-06-01 13:21:04 +0000388 # Retrieve the size of a file
389 def size(self, filename):
390 resp = self.sendcmd('SIZE ' + filename)
391 if resp[:3] == '213':
392 return string.atoi(string.strip(resp[3:]))
393
Guido van Rossumc567c601992-11-05 22:22:37 +0000394 # Make a directory, return its full pathname
395 def mkd(self, dirname):
396 resp = self.sendcmd('MKD ' + dirname)
397 return parse257(resp)
398
399 # Return current wording directory
400 def pwd(self):
401 resp = self.sendcmd('PWD')
402 return parse257(resp)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000403
404 # Quit, and close the connection
405 def quit(self):
Guido van Rossumc567c601992-11-05 22:22:37 +0000406 self.voidcmd('QUIT')
Guido van Rossum17ed1ae1993-06-01 13:21:04 +0000407 self.close()
408
409 # Close the connection without assuming anything about it
410 def close(self):
Guido van Rossum1115ab21992-11-04 15:51:30 +0000411 self.file.close()
412 self.sock.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000413 del self.file, self.sock
414
415
416# Parse a response type 257
417def parse257(resp):
418 if resp[:3] <> '257':
419 raise error_reply, resp
420 if resp[3:5] <> ' "':
421 return '' # Not compliant to RFC 959, but UNIX ftpd does this
422 dirname = ''
423 i = 5
424 n = len(resp)
425 while i < n:
426 c = resp[i]
427 i = i+1
428 if c == '"':
429 if i >= n or resp[i] <> '"':
430 break
431 i = i+1
432 dirname = dirname + c
433 return dirname
Guido van Rossum1115ab21992-11-04 15:51:30 +0000434
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000435# Default retrlines callback to print a line
436def print_line(line):
437 print line
438
Guido van Rossum1115ab21992-11-04 15:51:30 +0000439
440# Test program.
441# Usage: ftp [-d] host [-l[dir]] [-d[dir]] [file] ...
442def test():
443 import marshal
Guido van Rossumb6775db1994-08-01 11:34:53 +0000444 debugging = 0
445 while sys.argv[1] == '-d':
446 debugging = debugging+1
447 del sys.argv[1]
448 host = sys.argv[1]
449 ftp = FTP(host)
450 ftp.set_debuglevel(debugging)
451 ftp.login()
452 for file in sys.argv[2:]:
453 if file[:2] == '-l':
454 ftp.dir(file[2:])
455 elif file[:2] == '-d':
456 cmd = 'CWD'
457 if file[2:]: cmd = cmd + ' ' + file[2:]
458 resp = ftp.sendcmd(cmd)
459 else:
460 ftp.retrbinary('RETR ' + file, \
461 sys.stdout.write, 1024)
462 ftp.quit()
Guido van Rossum221ec0b1995-08-04 04:39:30 +0000463
464
465if __name__ == '__main__':
466 test()