blob: c886f8226c3042576cfc3f4118a24b9d1c3d0889 [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
8# >>> ftp = FTP().init('ftp.cwi.nl') # connect to host, default port
9# >>> 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
71 # Initialize an instance. Arguments:
72 # - host: hostname to connect to
73 # - port: port to connect to (default the standard FTP port)
74 def init(self, host, *args):
75 if len(args) > 1: raise TypeError, 'too many args'
76 if args: port = args[0]
77 else: port = FTP_PORT
78 self.host = host
79 self.port = port
80 self.debugging = 0
81 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
82 self.sock.connect(self.host, self.port)
83 self.file = self.sock.makefile('r')
84 self.welcome = self.getresp()
85 return self
86
87 # Get the welcome message from the server
88 # (this is read and squirreled away by init())
89 def getwelcome(self):
90 if self.debugging: print '*welcome*', `self.welcome`
91 return self.welcome
92
93 # Set the debugging level. Argument level means:
94 # 0: no debugging output (default)
95 # 1: print commands and responses but not body text etc.
96 # 2: also print raw lines read and sent before stripping CR/LF
97 def debug(self, level):
98 self.debugging = level
99
100 # Internal: send one line to the server, appending CRLF
101 def putline(self, line):
102 line = line + CRLF
103 if self.debugging > 1: print '*put*', `line`
104 self.sock.send(line)
105
106 # Internal: send one command to the server (through putline())
107 def putcmd(self, line):
108 if self.debugging: print '*cmd*', `line`
109 self.putline(line)
110
111 # Internal: return one line from the server, stripping CRLF.
112 # Raise EOFError if the connection is closed
113 def getline(self):
114 line = self.file.readline()
115 if self.debugging > 1:
116 print '*get*', `line`
117 if not line: raise EOFError
118 if line[-2:] == CRLF: line = line[:-2]
119 elif line[-1:] in CRLF: line = line[:-1]
120 return line
121
122 # Internal: get a response from the server, which may possibly
123 # consist of multiple lines. Return a single string with no
124 # trailing CRLF. If the response consists of multiple lines,
125 # these are separated by '\n' characters in the string
126 def getmultiline(self):
127 line = self.getline()
128 if line[3:4] == '-':
129 code = line[:3]
130 while 1:
131 nextline = self.getline()
132 line = line + ('\n' + nextline)
133 if nextline[:3] == code and \
134 nextline[3:4] <> '-':
135 break
136 return line
137
138 # Internal: get a response from the server.
139 # Raise various errors if the response indicates an error
140 def getresp(self):
141 resp = self.getmultiline()
142 if self.debugging: print '*resp*', `resp`
143 self.lastresp = resp[:3]
144 c = resp[:1]
145 if c == '4':
Guido van Rossumc567c601992-11-05 22:22:37 +0000146 raise error_temp, resp
Guido van Rossum1115ab21992-11-04 15:51:30 +0000147 if c == '5':
Guido van Rossumc567c601992-11-05 22:22:37 +0000148 raise error_perm, resp
Guido van Rossum1115ab21992-11-04 15:51:30 +0000149 if c not in '123':
Guido van Rossumc567c601992-11-05 22:22:37 +0000150 raise error_proto, resp
Guido van Rossum1115ab21992-11-04 15:51:30 +0000151 return resp
152
Guido van Rossumc567c601992-11-05 22:22:37 +0000153 # Expect a response beginning with '2'
154 def voidresp(self):
155 resp = self.getresp()
156 if resp[0] <> '2':
157 raise error_reply, resp
158
Guido van Rossumd3166071993-05-24 14:16:22 +0000159 # Abort a file transfer. Uses out-of-band data.
160 # This does not follow the procedure from the RFC to send Telnet
161 # IP and Synch; that doesn't seem to work with the servers I've
162 # tried. Instead, just send the ABOR command as OOB data.
163 def abort(self):
164 line = 'ABOR' + CRLF
165 if self.debugging > 1: print '*put urgent*', `line`
166 self.sock.send(line, MSG_OOB)
167 resp = self.getmultiline()
168 if resp[:3] not in ('426', '226'):
169 raise error_proto, resp
170
Guido van Rossum1115ab21992-11-04 15:51:30 +0000171 # Send a command and return the response
172 def sendcmd(self, cmd):
173 self.putcmd(cmd)
174 return self.getresp()
175
Guido van Rossumc68a4011992-11-05 23:01:42 +0000176 # Send a command and expect a response beginning with '2'
Guido van Rossumc567c601992-11-05 22:22:37 +0000177 def voidcmd(self, cmd):
Guido van Rossumc68a4011992-11-05 23:01:42 +0000178 self.putcmd(cmd)
179 self.voidresp()
Guido van Rossumc567c601992-11-05 22:22:37 +0000180
Guido van Rossum1115ab21992-11-04 15:51:30 +0000181 # Send a PORT command with the current host and the given port number
182 def sendport(self, port):
183 hostname = socket.gethostname()
184 hostaddr = socket.gethostbyname(hostname)
185 hbytes = string.splitfields(hostaddr, '.')
186 pbytes = [`port/256`, `port%256`]
187 bytes = hbytes + pbytes
188 cmd = 'PORT ' + string.joinfields(bytes, ',')
Guido van Rossumc567c601992-11-05 22:22:37 +0000189 self.voidcmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000190
191 # Create a new socket and send a PORT command for it
192 def makeport(self):
193 global nextport
Guido van Rossum1115ab21992-11-04 15:51:30 +0000194 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Guido van Rossumc68a4011992-11-05 23:01:42 +0000195 try:
196 getsockname = sock.getsockname
197 except AttributeError:
198 if self.debugging > 1:
199 print '*** getsockname not supported',
200 print '-- using manual port assignment ***'
201 port = nextport + PORT_OFFSET
202 nextport = (nextport + 1) % PORT_CYCLE
203 sock.bind('', port)
204 getsockname = None
205 sock.listen(0) # Assigns the port if not explicitly bound
206 if getsockname:
207 host, port = getsockname()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000208 resp = self.sendport(port)
209 return sock
210
Guido van Rossumc567c601992-11-05 22:22:37 +0000211 # Send a port command and a transfer command, accept the connection
212 # and return the socket for the connection
213 def transfercmd(self, cmd):
Guido van Rossum1115ab21992-11-04 15:51:30 +0000214 sock = self.makeport()
215 resp = self.sendcmd(cmd)
216 if resp[0] <> '1':
217 raise error_reply, resp
Guido van Rossumc567c601992-11-05 22:22:37 +0000218 conn, sockaddr = sock.accept()
219 return conn
220
221 # Login, default anonymous
222 def login(self, *args):
223 user = passwd = acct = ''
224 n = len(args)
225 if n > 3: raise TypeError, 'too many arguments'
226 if n > 0: user = args[0]
227 if n > 1: passwd = args[1]
228 if n > 2: acct = args[2]
229 if not user: user = 'anonymous'
230 if user == 'anonymous' and passwd in ('', '-'):
231 thishost = socket.gethostname()
232 if os.environ.has_key('LOGNAME'):
233 realuser = os.environ['LOGNAME']
234 elif os.environ.has_key('USER'):
235 realuser = os.environ['USER']
236 else:
237 realuser = 'anonymous'
238 passwd = passwd + realuser + '@' + thishost
239 resp = self.sendcmd('USER ' + user)
240 if resp[0] == '3': resp = self.sendcmd('PASS ' + passwd)
241 if resp[0] == '3': resp = self.sendcmd('ACCT ' + acct)
242 if resp[0] <> '2':
243 raise error_reply, resp
244
245 # Retrieve data in binary mode.
246 # The argument is a RETR command.
247 # The callback function is called for each block.
248 # This creates a new port for you
249 def retrbinary(self, cmd, callback, blocksize):
250 self.voidcmd('TYPE I')
251 conn = self.transfercmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000252 while 1:
253 data = conn.recv(blocksize)
254 if not data:
255 break
256 callback(data)
257 conn.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000258 self.voidresp()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000259
Guido van Rossumc567c601992-11-05 22:22:37 +0000260 # Retrieve data in line mode.
Guido van Rossum1115ab21992-11-04 15:51:30 +0000261 # The argument is a RETR or LIST command.
262 # The callback function is called for each line, with trailing
263 # CRLF stripped. This creates a new port for you
264 def retrlines(self, cmd, callback):
Guido van Rossumc567c601992-11-05 22:22:37 +0000265 resp = self.sendcmd('TYPE A')
266 conn = self.transfercmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000267 fp = conn.makefile('r')
268 while 1:
269 line = fp.readline()
270 if not line:
271 break
272 if line[-2:] == CRLF:
273 line = line[:-2]
274 elif line[:-1] == '\n':
275 line = line[:-1]
276 callback(line)
277 fp.close()
278 conn.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000279 self.voidresp()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000280
Guido van Rossumc567c601992-11-05 22:22:37 +0000281 # Store a file in binary mode
282 def storbinary(self, cmd, fp, blocksize):
283 self.voidcmd('TYPE I')
284 conn = self.transfercmd(cmd)
285 while 1:
286 buf = fp.read(blocksize)
287 if not buf: break
288 conn.send(buf)
289 conn.close()
290 self.voidresp()
291
292 # Store a file in line mode
293 def storlines(self, cmd, fp):
294 self.voidcmd('TYPE A')
295 conn = self.transfercmd(cmd)
296 while 1:
297 buf = fp.readline()
298 if not buf: break
299 if buf[-2:] <> CRLF:
300 if buf[-1] in CRLF: buf = buf[:-1]
301 buf = buf + CRLF
302 conn.send(buf)
303 conn.close()
304 self.voidresp()
305
306 # Return a list of files in a given directory (default the current)
307 def nlst(self, *args):
308 cmd = 'NLST'
309 for arg in args:
310 cmd = cmd + (' ' + arg)
311 files = []
312 self.retrlines(cmd, files.append)
313 return files
314
315 # Rename a file
316 def rename(self, fromname, toname):
317 resp = self.sendcmd('RNFR ' + fromname)
318 if resp[0] <> '3':
Guido van Rossum1115ab21992-11-04 15:51:30 +0000319 raise error_reply, resp
Guido van Rossumc567c601992-11-05 22:22:37 +0000320 self.voidcmd('RNTO ' + toname)
321
Guido van Rossum02cf5821993-05-17 08:00:02 +0000322 # Change to a directory
323 def cwd(self, dirname):
324 self.voidcmd('CWD ' + dirname)
325
Guido van Rossum17ed1ae1993-06-01 13:21:04 +0000326 # Retrieve the size of a file
327 def size(self, filename):
328 resp = self.sendcmd('SIZE ' + filename)
329 if resp[:3] == '213':
330 return string.atoi(string.strip(resp[3:]))
331
Guido van Rossumc567c601992-11-05 22:22:37 +0000332 # Make a directory, return its full pathname
333 def mkd(self, dirname):
334 resp = self.sendcmd('MKD ' + dirname)
335 return parse257(resp)
336
337 # Return current wording directory
338 def pwd(self):
339 resp = self.sendcmd('PWD')
340 return parse257(resp)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000341
342 # Quit, and close the connection
343 def quit(self):
Guido van Rossumc567c601992-11-05 22:22:37 +0000344 self.voidcmd('QUIT')
Guido van Rossum17ed1ae1993-06-01 13:21:04 +0000345 self.close()
346
347 # Close the connection without assuming anything about it
348 def close(self):
Guido van Rossum1115ab21992-11-04 15:51:30 +0000349 self.file.close()
350 self.sock.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000351 del self.file, self.sock
352
353
354# Parse a response type 257
355def parse257(resp):
356 if resp[:3] <> '257':
357 raise error_reply, resp
358 if resp[3:5] <> ' "':
359 return '' # Not compliant to RFC 959, but UNIX ftpd does this
360 dirname = ''
361 i = 5
362 n = len(resp)
363 while i < n:
364 c = resp[i]
365 i = i+1
366 if c == '"':
367 if i >= n or resp[i] <> '"':
368 break
369 i = i+1
370 dirname = dirname + c
371 return dirname
Guido van Rossum1115ab21992-11-04 15:51:30 +0000372
373
374# Test program.
375# Usage: ftp [-d] host [-l[dir]] [-d[dir]] [file] ...
376def test():
377 import marshal
378 global nextport
379 try:
380 nextport = marshal.load(open('.@nextport', 'r'))
381 except IOError:
382 pass
383 try:
384 debugging = 0
385 while sys.argv[1] == '-d':
386 debugging = debugging+1
387 del sys.argv[1]
388 host = sys.argv[1]
389 ftp = FTP().init(host)
390 ftp.debug(debugging)
Guido van Rossumc567c601992-11-05 22:22:37 +0000391 ftp.login()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000392 def writeln(line): print line
393 for file in sys.argv[2:]:
394 if file[:2] == '-l':
395 cmd = 'LIST'
396 if file[2:]: cmd = cmd + ' ' + file[2:]
397 ftp.retrlines(cmd, writeln)
398 elif file[:2] == '-d':
399 cmd = 'CWD'
400 if file[2:]: cmd = cmd + ' ' + file[2:]
401 resp = ftp.sendcmd(cmd)
402 else:
403 ftp.retrbinary('RETR ' + file, \
404 sys.stdout.write, 1024)
405 ftp.quit()
406 finally:
407 marshal.dump(nextport, open('.@nextport', 'w'))