blob: dc662419fac31917c7948349055d6fb606f2138a [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
4
Guido van Rossumc567c601992-11-05 22:22:37 +00005# Example:
6#
7# >>> from ftplib import FTP
Guido van Rossume65cce51993-11-08 15:05:21 +00008# >>> ftp = FTP('ftp.cwi.nl') # connect to host, default port
Guido van Rossumc567c601992-11-05 22:22:37 +00009# >>> ftp.login() # default, i.e.: user anonymous, passwd user@hostname
10# >>> def handle_one_line(line): # callback for ftp.retrlines
11# ... print line
12# ...
13# >>> ftp.retrlines('LIST', handle_one_line) # list directory contents
14# 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#
21# To download a file, use ftp.retrlines('RETR ' + filename, handle_one_line),
22# 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
31import socket
32import string
33
34
Guido van Rossumd3166071993-05-24 14:16:22 +000035# Magic number from <socket.h>
36MSG_OOB = 0x1 # Process data out of band
37
38
Guido van Rossumc567c601992-11-05 22:22:37 +000039# The standard FTP server control port
Guido van Rossum1115ab21992-11-04 15:51:30 +000040FTP_PORT = 21
Guido van Rossum1115ab21992-11-04 15:51:30 +000041
42
Guido van Rossum21974791992-11-06 13:34:17 +000043# Exception raised when an error or invalid response is received
Guido van Rossumc567c601992-11-05 22:22:37 +000044error_reply = 'ftplib.error_reply' # unexpected [123]xx reply
45error_temp = 'ftplib.error_temp' # 4xx errors
46error_perm = 'ftplib.error_perm' # 5xx errors
47error_proto = 'ftplib.error_proto' # response does not begin with [1-5]
Guido van Rossum1115ab21992-11-04 15:51:30 +000048
49
Guido van Rossum21974791992-11-06 13:34:17 +000050# All exceptions (hopefully) that may be raised here and that aren't
51# (always) programming errors on our side
52all_errors = (error_reply, error_temp, error_perm, error_proto, \
53 socket.error, IOError)
54
55
Guido van Rossum1115ab21992-11-04 15:51:30 +000056# Line terminators (we always output CRLF, but accept any of CRLF, CR, LF)
57CRLF = '\r\n'
58
59
60# Next port to be used by makeport(), with PORT_OFFSET added
Guido van Rossumc68a4011992-11-05 23:01:42 +000061# (This is now only used when the python interpreter doesn't support
62# the getsockname() method yet)
Guido van Rossum1115ab21992-11-04 15:51:30 +000063nextport = 0
64PORT_OFFSET = 40000
65PORT_CYCLE = 1000
Guido van Rossum1115ab21992-11-04 15:51:30 +000066
67
68# The class itself
69class FTP:
70
Guido van Rossum52fc1f61993-06-17 12:38:10 +000071 # New initialization method (called by class instantiation)
72 # Initialize host to localhost, port to standard ftp port
73 def __init__(self, *args):
74 # Initialize the instance to something mostly harmless
Guido van Rossum1115ab21992-11-04 15:51:30 +000075 self.debugging = 0
Guido van Rossum52fc1f61993-06-17 12:38:10 +000076 self.host = ''
77 self.port = FTP_PORT
78 self.sock = None
79 self.file = None
80 self.welcome = None
81 if args:
82 apply(self.connect, args)
83
84 # Old init method (explicitly called by caller)
85 def init(self, *args):
86 if args:
87 apply(self.connect, args)
88
89 # Connect to host. Arguments:
90 # - host: hostname to connect to (default previous host)
91 # - port: port to connect to (default previous port)
92 def init(self, *args):
93 if args: self.host = args[0]
94 if args[1:]: self.port = args[1]
95 if args[2:]: raise TypeError, 'too many args'
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()
100 return self
101
102 # Get the welcome message from the server
103 # (this is read and squirreled away by init())
104 def getwelcome(self):
105 if self.debugging: print '*welcome*', `self.welcome`
106 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
116 # Internal: send one line to the server, appending CRLF
117 def putline(self, line):
118 line = line + CRLF
119 if self.debugging > 1: print '*put*', `line`
120 self.sock.send(line)
121
122 # Internal: send one command to the server (through putline())
123 def putcmd(self, line):
124 if self.debugging: print '*cmd*', `line`
125 self.putline(line)
126
127 # Internal: return one line from the server, stripping CRLF.
128 # Raise EOFError if the connection is closed
129 def getline(self):
130 line = self.file.readline()
131 if self.debugging > 1:
132 print '*get*', `line`
133 if not line: raise EOFError
134 if line[-2:] == CRLF: line = line[:-2]
135 elif line[-1:] in CRLF: line = line[:-1]
136 return line
137
138 # Internal: get a response from the server, which may possibly
139 # consist of multiple lines. Return a single string with no
140 # trailing CRLF. If the response consists of multiple lines,
141 # these are separated by '\n' characters in the string
142 def getmultiline(self):
143 line = self.getline()
144 if line[3:4] == '-':
145 code = line[:3]
146 while 1:
147 nextline = self.getline()
148 line = line + ('\n' + nextline)
149 if nextline[:3] == code and \
150 nextline[3:4] <> '-':
151 break
152 return line
153
154 # Internal: get a response from the server.
155 # Raise various errors if the response indicates an error
156 def getresp(self):
157 resp = self.getmultiline()
158 if self.debugging: print '*resp*', `resp`
159 self.lastresp = resp[:3]
160 c = resp[:1]
161 if c == '4':
Guido van Rossumc567c601992-11-05 22:22:37 +0000162 raise error_temp, resp
Guido van Rossum1115ab21992-11-04 15:51:30 +0000163 if c == '5':
Guido van Rossumc567c601992-11-05 22:22:37 +0000164 raise error_perm, resp
Guido van Rossum1115ab21992-11-04 15:51:30 +0000165 if c not in '123':
Guido van Rossumc567c601992-11-05 22:22:37 +0000166 raise error_proto, resp
Guido van Rossum1115ab21992-11-04 15:51:30 +0000167 return resp
168
Guido van Rossumc567c601992-11-05 22:22:37 +0000169 # Expect a response beginning with '2'
170 def voidresp(self):
171 resp = self.getresp()
172 if resp[0] <> '2':
173 raise error_reply, resp
174
Guido van Rossumd3166071993-05-24 14:16:22 +0000175 # Abort a file transfer. Uses out-of-band data.
176 # This does not follow the procedure from the RFC to send Telnet
177 # IP and Synch; that doesn't seem to work with the servers I've
178 # tried. Instead, just send the ABOR command as OOB data.
179 def abort(self):
180 line = 'ABOR' + CRLF
181 if self.debugging > 1: print '*put urgent*', `line`
182 self.sock.send(line, MSG_OOB)
183 resp = self.getmultiline()
184 if resp[:3] not in ('426', '226'):
185 raise error_proto, resp
186
Guido van Rossum1115ab21992-11-04 15:51:30 +0000187 # Send a command and return the response
188 def sendcmd(self, cmd):
189 self.putcmd(cmd)
190 return self.getresp()
191
Guido van Rossumc68a4011992-11-05 23:01:42 +0000192 # Send a command and expect a response beginning with '2'
Guido van Rossumc567c601992-11-05 22:22:37 +0000193 def voidcmd(self, cmd):
Guido van Rossumc68a4011992-11-05 23:01:42 +0000194 self.putcmd(cmd)
195 self.voidresp()
Guido van Rossumc567c601992-11-05 22:22:37 +0000196
Guido van Rossum1115ab21992-11-04 15:51:30 +0000197 # Send a PORT command with the current host and the given port number
198 def sendport(self, port):
199 hostname = socket.gethostname()
200 hostaddr = socket.gethostbyname(hostname)
201 hbytes = string.splitfields(hostaddr, '.')
202 pbytes = [`port/256`, `port%256`]
203 bytes = hbytes + pbytes
204 cmd = 'PORT ' + string.joinfields(bytes, ',')
Guido van Rossumc567c601992-11-05 22:22:37 +0000205 self.voidcmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000206
207 # Create a new socket and send a PORT command for it
208 def makeport(self):
209 global nextport
Guido van Rossum1115ab21992-11-04 15:51:30 +0000210 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Guido van Rossumc68a4011992-11-05 23:01:42 +0000211 try:
212 getsockname = sock.getsockname
213 except AttributeError:
214 if self.debugging > 1:
215 print '*** getsockname not supported',
216 print '-- using manual port assignment ***'
217 port = nextport + PORT_OFFSET
218 nextport = (nextport + 1) % PORT_CYCLE
219 sock.bind('', port)
220 getsockname = None
221 sock.listen(0) # Assigns the port if not explicitly bound
222 if getsockname:
223 host, port = getsockname()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000224 resp = self.sendport(port)
225 return sock
226
Guido van Rossumc567c601992-11-05 22:22:37 +0000227 # Send a port command and a transfer command, accept the connection
228 # and return the socket for the connection
229 def transfercmd(self, cmd):
Guido van Rossum1115ab21992-11-04 15:51:30 +0000230 sock = self.makeport()
231 resp = self.sendcmd(cmd)
232 if resp[0] <> '1':
233 raise error_reply, resp
Guido van Rossumc567c601992-11-05 22:22:37 +0000234 conn, sockaddr = sock.accept()
235 return conn
236
237 # Login, default anonymous
238 def login(self, *args):
239 user = passwd = acct = ''
240 n = len(args)
241 if n > 3: raise TypeError, 'too many arguments'
242 if n > 0: user = args[0]
243 if n > 1: passwd = args[1]
244 if n > 2: acct = args[2]
245 if not user: user = 'anonymous'
246 if user == 'anonymous' and passwd in ('', '-'):
247 thishost = socket.gethostname()
248 if os.environ.has_key('LOGNAME'):
249 realuser = os.environ['LOGNAME']
250 elif os.environ.has_key('USER'):
251 realuser = os.environ['USER']
252 else:
253 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
279 # CRLF stripped. This creates a new port for you
280 def retrlines(self, cmd, callback):
Guido van Rossumc567c601992-11-05 22:22:37 +0000281 resp = self.sendcmd('TYPE A')
282 conn = self.transfercmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000283 fp = conn.makefile('r')
284 while 1:
285 line = fp.readline()
286 if not line:
287 break
288 if line[-2:] == CRLF:
289 line = line[:-2]
290 elif line[:-1] == '\n':
291 line = line[:-1]
292 callback(line)
293 fp.close()
294 conn.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000295 self.voidresp()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000296
Guido van Rossumc567c601992-11-05 22:22:37 +0000297 # Store a file in binary mode
298 def storbinary(self, cmd, fp, blocksize):
299 self.voidcmd('TYPE I')
300 conn = self.transfercmd(cmd)
301 while 1:
302 buf = fp.read(blocksize)
303 if not buf: break
304 conn.send(buf)
305 conn.close()
306 self.voidresp()
307
308 # Store a file in line mode
309 def storlines(self, cmd, fp):
310 self.voidcmd('TYPE A')
311 conn = self.transfercmd(cmd)
312 while 1:
313 buf = fp.readline()
314 if not buf: break
315 if buf[-2:] <> CRLF:
316 if buf[-1] in CRLF: buf = buf[:-1]
317 buf = buf + CRLF
318 conn.send(buf)
319 conn.close()
320 self.voidresp()
321
322 # Return a list of files in a given directory (default the current)
323 def nlst(self, *args):
324 cmd = 'NLST'
325 for arg in args:
326 cmd = cmd + (' ' + arg)
327 files = []
328 self.retrlines(cmd, files.append)
329 return files
330
331 # Rename a file
332 def rename(self, fromname, toname):
333 resp = self.sendcmd('RNFR ' + fromname)
334 if resp[0] <> '3':
Guido van Rossum1115ab21992-11-04 15:51:30 +0000335 raise error_reply, resp
Guido van Rossumc567c601992-11-05 22:22:37 +0000336 self.voidcmd('RNTO ' + toname)
337
Guido van Rossum02cf5821993-05-17 08:00:02 +0000338 # Change to a directory
339 def cwd(self, dirname):
Guido van Rossumdf563861993-07-06 15:19:36 +0000340 if dirname == '..':
341 cmd = 'CDUP'
342 else:
343 cmd = 'CWD ' + dirname
344 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
393
394# Test program.
395# Usage: ftp [-d] host [-l[dir]] [-d[dir]] [file] ...
396def test():
397 import marshal
398 global nextport
399 try:
400 nextport = marshal.load(open('.@nextport', 'r'))
401 except IOError:
402 pass
403 try:
404 debugging = 0
405 while sys.argv[1] == '-d':
406 debugging = debugging+1
407 del sys.argv[1]
408 host = sys.argv[1]
Guido van Rossume65cce51993-11-08 15:05:21 +0000409 ftp = FTP(host)
410 ftp.set_debuglevel(debugging)
Guido van Rossumc567c601992-11-05 22:22:37 +0000411 ftp.login()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000412 def writeln(line): print line
413 for file in sys.argv[2:]:
414 if file[:2] == '-l':
415 cmd = 'LIST'
416 if file[2:]: cmd = cmd + ' ' + file[2:]
417 ftp.retrlines(cmd, writeln)
418 elif file[:2] == '-d':
419 cmd = 'CWD'
420 if file[2:]: cmd = cmd + ' ' + file[2:]
421 resp = ftp.sendcmd(cmd)
422 else:
423 ftp.retrbinary('RETR ' + file, \
424 sys.stdout.write, 1024)
425 ftp.quit()
426 finally:
427 marshal.dump(nextport, open('.@nextport', 'w'))