blob: 7a414e6882a98a0f4604d273cac5ce21be750a6b [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):
98 if self.debugging: print '*welcome*', `self.welcome`
99 return self.welcome
100
101 # Set the debugging level. Argument level means:
102 # 0: no debugging output (default)
103 # 1: print commands and responses but not body text etc.
104 # 2: also print raw lines read and sent before stripping CR/LF
Guido van Rossume65cce51993-11-08 15:05:21 +0000105 def set_debuglevel(self, level):
Guido van Rossum1115ab21992-11-04 15:51:30 +0000106 self.debugging = level
Guido van Rossume65cce51993-11-08 15:05:21 +0000107 debug = set_debuglevel
Guido van Rossum1115ab21992-11-04 15:51:30 +0000108
109 # Internal: send one line to the server, appending CRLF
110 def putline(self, line):
111 line = line + CRLF
112 if self.debugging > 1: print '*put*', `line`
113 self.sock.send(line)
114
115 # Internal: send one command to the server (through putline())
116 def putcmd(self, line):
117 if self.debugging: print '*cmd*', `line`
118 self.putline(line)
119
120 # Internal: return one line from the server, stripping CRLF.
121 # Raise EOFError if the connection is closed
122 def getline(self):
123 line = self.file.readline()
124 if self.debugging > 1:
125 print '*get*', `line`
126 if not line: raise EOFError
127 if line[-2:] == CRLF: line = line[:-2]
128 elif line[-1:] in CRLF: line = line[:-1]
129 return line
130
131 # Internal: get a response from the server, which may possibly
132 # consist of multiple lines. Return a single string with no
133 # trailing CRLF. If the response consists of multiple lines,
134 # these are separated by '\n' characters in the string
135 def getmultiline(self):
136 line = self.getline()
137 if line[3:4] == '-':
138 code = line[:3]
139 while 1:
140 nextline = self.getline()
141 line = line + ('\n' + nextline)
142 if nextline[:3] == code and \
143 nextline[3:4] <> '-':
144 break
145 return line
146
147 # Internal: get a response from the server.
148 # Raise various errors if the response indicates an error
149 def getresp(self):
150 resp = self.getmultiline()
151 if self.debugging: print '*resp*', `resp`
152 self.lastresp = resp[:3]
153 c = resp[:1]
154 if c == '4':
Guido van Rossumc567c601992-11-05 22:22:37 +0000155 raise error_temp, resp
Guido van Rossum1115ab21992-11-04 15:51:30 +0000156 if c == '5':
Guido van Rossumc567c601992-11-05 22:22:37 +0000157 raise error_perm, resp
Guido van Rossum1115ab21992-11-04 15:51:30 +0000158 if c not in '123':
Guido van Rossumc567c601992-11-05 22:22:37 +0000159 raise error_proto, resp
Guido van Rossum1115ab21992-11-04 15:51:30 +0000160 return resp
161
Guido van Rossumc567c601992-11-05 22:22:37 +0000162 # Expect a response beginning with '2'
163 def voidresp(self):
164 resp = self.getresp()
165 if resp[0] <> '2':
166 raise error_reply, resp
167
Guido van Rossumd3166071993-05-24 14:16:22 +0000168 # Abort a file transfer. Uses out-of-band data.
169 # This does not follow the procedure from the RFC to send Telnet
170 # IP and Synch; that doesn't seem to work with the servers I've
171 # tried. Instead, just send the ABOR command as OOB data.
172 def abort(self):
173 line = 'ABOR' + CRLF
174 if self.debugging > 1: print '*put urgent*', `line`
175 self.sock.send(line, MSG_OOB)
176 resp = self.getmultiline()
177 if resp[:3] not in ('426', '226'):
178 raise error_proto, resp
179
Guido van Rossum1115ab21992-11-04 15:51:30 +0000180 # Send a command and return the response
181 def sendcmd(self, cmd):
182 self.putcmd(cmd)
183 return self.getresp()
184
Guido van Rossumc68a4011992-11-05 23:01:42 +0000185 # Send a command and expect a response beginning with '2'
Guido van Rossumc567c601992-11-05 22:22:37 +0000186 def voidcmd(self, cmd):
Guido van Rossumc68a4011992-11-05 23:01:42 +0000187 self.putcmd(cmd)
188 self.voidresp()
Guido van Rossumc567c601992-11-05 22:22:37 +0000189
Guido van Rossum1115ab21992-11-04 15:51:30 +0000190 # Send a PORT command with the current host and the given port number
191 def sendport(self, port):
192 hostname = socket.gethostname()
193 hostaddr = socket.gethostbyname(hostname)
194 hbytes = string.splitfields(hostaddr, '.')
195 pbytes = [`port/256`, `port%256`]
196 bytes = hbytes + pbytes
197 cmd = 'PORT ' + string.joinfields(bytes, ',')
Guido van Rossumc567c601992-11-05 22:22:37 +0000198 self.voidcmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000199
200 # Create a new socket and send a PORT command for it
201 def makeport(self):
202 global nextport
Guido van Rossum1115ab21992-11-04 15:51:30 +0000203 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000204 sock.listen(1)
205 host, port = sock.getsockname()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000206 resp = self.sendport(port)
207 return sock
208
Guido van Rossumc567c601992-11-05 22:22:37 +0000209 # Send a port command and a transfer command, accept the connection
210 # and return the socket for the connection
211 def transfercmd(self, cmd):
Guido van Rossum1115ab21992-11-04 15:51:30 +0000212 sock = self.makeport()
213 resp = self.sendcmd(cmd)
214 if resp[0] <> '1':
215 raise error_reply, resp
Guido van Rossumc567c601992-11-05 22:22:37 +0000216 conn, sockaddr = sock.accept()
217 return conn
218
219 # Login, default anonymous
Guido van Rossumb6775db1994-08-01 11:34:53 +0000220 def login(self, user = '', passwd = '', acct = ''):
Guido van Rossumc567c601992-11-05 22:22:37 +0000221 if not user: user = 'anonymous'
222 if user == 'anonymous' and passwd in ('', '-'):
223 thishost = socket.gethostname()
Jack Jansen40b98351995-01-19 12:24:45 +0000224 try:
225 if os.environ.has_key('LOGNAME'):
226 realuser = os.environ['LOGNAME']
227 elif os.environ.has_key('USER'):
228 realuser = os.environ['USER']
229 else:
230 realuser = 'anonymous'
231 except AttributeError:
232 # Not all systems have os.environ....
Guido van Rossumc567c601992-11-05 22:22:37 +0000233 realuser = 'anonymous'
234 passwd = passwd + realuser + '@' + thishost
235 resp = self.sendcmd('USER ' + user)
236 if resp[0] == '3': resp = self.sendcmd('PASS ' + passwd)
237 if resp[0] == '3': resp = self.sendcmd('ACCT ' + acct)
238 if resp[0] <> '2':
239 raise error_reply, resp
240
241 # Retrieve data in binary mode.
242 # The argument is a RETR command.
243 # The callback function is called for each block.
244 # This creates a new port for you
245 def retrbinary(self, cmd, callback, blocksize):
246 self.voidcmd('TYPE I')
247 conn = self.transfercmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000248 while 1:
249 data = conn.recv(blocksize)
250 if not data:
251 break
252 callback(data)
253 conn.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000254 self.voidresp()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000255
Guido van Rossumc567c601992-11-05 22:22:37 +0000256 # Retrieve data in line mode.
Guido van Rossum1115ab21992-11-04 15:51:30 +0000257 # The argument is a RETR or LIST command.
258 # The callback function is called for each line, with trailing
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000259 # CRLF stripped. This creates a new port for you.
260 # print_lines is the default callback
Guido van Rossumb6775db1994-08-01 11:34:53 +0000261 def retrlines(self, cmd, callback = None):
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000262 if not callback: callback = print_line
Guido van Rossumc567c601992-11-05 22:22:37 +0000263 resp = self.sendcmd('TYPE A')
264 conn = self.transfercmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000265 fp = conn.makefile('r')
266 while 1:
267 line = fp.readline()
268 if not line:
269 break
270 if line[-2:] == CRLF:
271 line = line[:-2]
272 elif line[:-1] == '\n':
273 line = line[:-1]
274 callback(line)
275 fp.close()
276 conn.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000277 self.voidresp()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000278
Guido van Rossumc567c601992-11-05 22:22:37 +0000279 # Store a file in binary mode
280 def storbinary(self, cmd, fp, blocksize):
281 self.voidcmd('TYPE I')
282 conn = self.transfercmd(cmd)
283 while 1:
284 buf = fp.read(blocksize)
285 if not buf: break
286 conn.send(buf)
287 conn.close()
288 self.voidresp()
289
290 # Store a file in line mode
291 def storlines(self, cmd, fp):
292 self.voidcmd('TYPE A')
293 conn = self.transfercmd(cmd)
294 while 1:
295 buf = fp.readline()
296 if not buf: break
297 if buf[-2:] <> CRLF:
298 if buf[-1] in CRLF: buf = buf[:-1]
299 buf = buf + CRLF
300 conn.send(buf)
301 conn.close()
302 self.voidresp()
303
304 # Return a list of files in a given directory (default the current)
305 def nlst(self, *args):
306 cmd = 'NLST'
307 for arg in args:
308 cmd = cmd + (' ' + arg)
309 files = []
310 self.retrlines(cmd, files.append)
311 return files
312
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000313 # List a directory in long form. By default list current directory
314 # to stdout. Optional last argument is callback function;
315 # all non-empty arguments before it are concatenated to the
316 # LIST command. (This *should* only be used for a pathname.)
317 def dir(self, *args):
318 cmd = 'LIST'
319 func = None
320 if args[-1:] and type(args[-1]) != type(''):
321 args, func = args[:-1], args[-1]
322 for arg in args:
323 if arg:
324 cmd = cmd + (' ' + arg)
325 self.retrlines(cmd, func)
326
Guido van Rossumc567c601992-11-05 22:22:37 +0000327 # Rename a file
328 def rename(self, fromname, toname):
329 resp = self.sendcmd('RNFR ' + fromname)
330 if resp[0] <> '3':
Guido van Rossum1115ab21992-11-04 15:51:30 +0000331 raise error_reply, resp
Guido van Rossumc567c601992-11-05 22:22:37 +0000332 self.voidcmd('RNTO ' + toname)
333
Guido van Rossum02cf5821993-05-17 08:00:02 +0000334 # Change to a directory
335 def cwd(self, dirname):
Guido van Rossumdf563861993-07-06 15:19:36 +0000336 if dirname == '..':
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000337 try:
338 self.voidcmd('CDUP')
339 return
340 except error_perm, msg:
341 if msg[:3] != '500':
342 raise error_perm, msg
343 cmd = 'CWD ' + dirname
Guido van Rossumdf563861993-07-06 15:19:36 +0000344 self.voidcmd(cmd)
Guido van Rossum02cf5821993-05-17 08:00:02 +0000345
Guido van Rossum17ed1ae1993-06-01 13:21:04 +0000346 # Retrieve the size of a file
347 def size(self, filename):
348 resp = self.sendcmd('SIZE ' + filename)
349 if resp[:3] == '213':
350 return string.atoi(string.strip(resp[3:]))
351
Guido van Rossumc567c601992-11-05 22:22:37 +0000352 # Make a directory, return its full pathname
353 def mkd(self, dirname):
354 resp = self.sendcmd('MKD ' + dirname)
355 return parse257(resp)
356
357 # Return current wording directory
358 def pwd(self):
359 resp = self.sendcmd('PWD')
360 return parse257(resp)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000361
362 # Quit, and close the connection
363 def quit(self):
Guido van Rossumc567c601992-11-05 22:22:37 +0000364 self.voidcmd('QUIT')
Guido van Rossum17ed1ae1993-06-01 13:21:04 +0000365 self.close()
366
367 # Close the connection without assuming anything about it
368 def close(self):
Guido van Rossum1115ab21992-11-04 15:51:30 +0000369 self.file.close()
370 self.sock.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000371 del self.file, self.sock
372
373
374# Parse a response type 257
375def parse257(resp):
376 if resp[:3] <> '257':
377 raise error_reply, resp
378 if resp[3:5] <> ' "':
379 return '' # Not compliant to RFC 959, but UNIX ftpd does this
380 dirname = ''
381 i = 5
382 n = len(resp)
383 while i < n:
384 c = resp[i]
385 i = i+1
386 if c == '"':
387 if i >= n or resp[i] <> '"':
388 break
389 i = i+1
390 dirname = dirname + c
391 return dirname
Guido van Rossum1115ab21992-11-04 15:51:30 +0000392
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000393# Default retrlines callback to print a line
394def print_line(line):
395 print line
396
Guido van Rossum1115ab21992-11-04 15:51:30 +0000397
398# Test program.
399# Usage: ftp [-d] host [-l[dir]] [-d[dir]] [file] ...
400def test():
401 import marshal
Guido van Rossumb6775db1994-08-01 11:34:53 +0000402 debugging = 0
403 while sys.argv[1] == '-d':
404 debugging = debugging+1
405 del sys.argv[1]
406 host = sys.argv[1]
407 ftp = FTP(host)
408 ftp.set_debuglevel(debugging)
409 ftp.login()
410 for file in sys.argv[2:]:
411 if file[:2] == '-l':
412 ftp.dir(file[2:])
413 elif file[:2] == '-d':
414 cmd = 'CWD'
415 if file[2:]: cmd = cmd + ' ' + file[2:]
416 resp = ftp.sendcmd(cmd)
417 else:
418 ftp.retrbinary('RETR ' + file, \
419 sys.stdout.write, 1024)
420 ftp.quit()