blob: 8423df6d8ca7ec7954f21bfc4f87c8e058032c15 [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 Rossumc567c601992-11-05 22:22:37 +000035# The standard FTP server control port
Guido van Rossum1115ab21992-11-04 15:51:30 +000036FTP_PORT = 21
Guido van Rossum1115ab21992-11-04 15:51:30 +000037
38
Guido van Rossum21974791992-11-06 13:34:17 +000039# Exception raised when an error or invalid response is received
Guido van Rossumc567c601992-11-05 22:22:37 +000040error_reply = 'ftplib.error_reply' # unexpected [123]xx reply
41error_temp = 'ftplib.error_temp' # 4xx errors
42error_perm = 'ftplib.error_perm' # 5xx errors
43error_proto = 'ftplib.error_proto' # response does not begin with [1-5]
Guido van Rossum1115ab21992-11-04 15:51:30 +000044
45
Guido van Rossum21974791992-11-06 13:34:17 +000046# All exceptions (hopefully) that may be raised here and that aren't
47# (always) programming errors on our side
48all_errors = (error_reply, error_temp, error_perm, error_proto, \
49 socket.error, IOError)
50
51
Guido van Rossum1115ab21992-11-04 15:51:30 +000052# Line terminators (we always output CRLF, but accept any of CRLF, CR, LF)
53CRLF = '\r\n'
54
55
56# Next port to be used by makeport(), with PORT_OFFSET added
Guido van Rossumc68a4011992-11-05 23:01:42 +000057# (This is now only used when the python interpreter doesn't support
58# the getsockname() method yet)
Guido van Rossum1115ab21992-11-04 15:51:30 +000059nextport = 0
60PORT_OFFSET = 40000
61PORT_CYCLE = 1000
Guido van Rossum1115ab21992-11-04 15:51:30 +000062
63
64# The class itself
65class FTP:
66
67 # Initialize an instance. Arguments:
68 # - host: hostname to connect to
69 # - port: port to connect to (default the standard FTP port)
70 def init(self, host, *args):
71 if len(args) > 1: raise TypeError, 'too many args'
72 if args: port = args[0]
73 else: port = FTP_PORT
74 self.host = host
75 self.port = port
76 self.debugging = 0
77 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
78 self.sock.connect(self.host, self.port)
79 self.file = self.sock.makefile('r')
80 self.welcome = self.getresp()
81 return self
82
83 # Get the welcome message from the server
84 # (this is read and squirreled away by init())
85 def getwelcome(self):
86 if self.debugging: print '*welcome*', `self.welcome`
87 return self.welcome
88
89 # Set the debugging level. Argument level means:
90 # 0: no debugging output (default)
91 # 1: print commands and responses but not body text etc.
92 # 2: also print raw lines read and sent before stripping CR/LF
93 def debug(self, level):
94 self.debugging = level
95
96 # Internal: send one line to the server, appending CRLF
97 def putline(self, line):
98 line = line + CRLF
99 if self.debugging > 1: print '*put*', `line`
100 self.sock.send(line)
101
102 # Internal: send one command to the server (through putline())
103 def putcmd(self, line):
104 if self.debugging: print '*cmd*', `line`
105 self.putline(line)
106
107 # Internal: return one line from the server, stripping CRLF.
108 # Raise EOFError if the connection is closed
109 def getline(self):
110 line = self.file.readline()
111 if self.debugging > 1:
112 print '*get*', `line`
113 if not line: raise EOFError
114 if line[-2:] == CRLF: line = line[:-2]
115 elif line[-1:] in CRLF: line = line[:-1]
116 return line
117
118 # Internal: get a response from the server, which may possibly
119 # consist of multiple lines. Return a single string with no
120 # trailing CRLF. If the response consists of multiple lines,
121 # these are separated by '\n' characters in the string
122 def getmultiline(self):
123 line = self.getline()
124 if line[3:4] == '-':
125 code = line[:3]
126 while 1:
127 nextline = self.getline()
128 line = line + ('\n' + nextline)
129 if nextline[:3] == code and \
130 nextline[3:4] <> '-':
131 break
132 return line
133
134 # Internal: get a response from the server.
135 # Raise various errors if the response indicates an error
136 def getresp(self):
137 resp = self.getmultiline()
138 if self.debugging: print '*resp*', `resp`
139 self.lastresp = resp[:3]
140 c = resp[:1]
141 if c == '4':
Guido van Rossumc567c601992-11-05 22:22:37 +0000142 raise error_temp, resp
Guido van Rossum1115ab21992-11-04 15:51:30 +0000143 if c == '5':
Guido van Rossumc567c601992-11-05 22:22:37 +0000144 raise error_perm, resp
Guido van Rossum1115ab21992-11-04 15:51:30 +0000145 if c not in '123':
Guido van Rossumc567c601992-11-05 22:22:37 +0000146 raise error_proto, resp
Guido van Rossum1115ab21992-11-04 15:51:30 +0000147 return resp
148
Guido van Rossumc567c601992-11-05 22:22:37 +0000149 # Expect a response beginning with '2'
150 def voidresp(self):
151 resp = self.getresp()
152 if resp[0] <> '2':
153 raise error_reply, resp
154
Guido van Rossum1115ab21992-11-04 15:51:30 +0000155 # Send a command and return the response
156 def sendcmd(self, cmd):
157 self.putcmd(cmd)
158 return self.getresp()
159
Guido van Rossumc68a4011992-11-05 23:01:42 +0000160 # Send a command and expect a response beginning with '2'
Guido van Rossumc567c601992-11-05 22:22:37 +0000161 def voidcmd(self, cmd):
Guido van Rossumc68a4011992-11-05 23:01:42 +0000162 self.putcmd(cmd)
163 self.voidresp()
Guido van Rossumc567c601992-11-05 22:22:37 +0000164
Guido van Rossum1115ab21992-11-04 15:51:30 +0000165 # Send a PORT command with the current host and the given port number
166 def sendport(self, port):
167 hostname = socket.gethostname()
168 hostaddr = socket.gethostbyname(hostname)
169 hbytes = string.splitfields(hostaddr, '.')
170 pbytes = [`port/256`, `port%256`]
171 bytes = hbytes + pbytes
172 cmd = 'PORT ' + string.joinfields(bytes, ',')
Guido van Rossumc567c601992-11-05 22:22:37 +0000173 self.voidcmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000174
175 # Create a new socket and send a PORT command for it
176 def makeport(self):
177 global nextport
Guido van Rossum1115ab21992-11-04 15:51:30 +0000178 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Guido van Rossumc68a4011992-11-05 23:01:42 +0000179 try:
180 getsockname = sock.getsockname
181 except AttributeError:
182 if self.debugging > 1:
183 print '*** getsockname not supported',
184 print '-- using manual port assignment ***'
185 port = nextport + PORT_OFFSET
186 nextport = (nextport + 1) % PORT_CYCLE
187 sock.bind('', port)
188 getsockname = None
189 sock.listen(0) # Assigns the port if not explicitly bound
190 if getsockname:
191 host, port = getsockname()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000192 resp = self.sendport(port)
193 return sock
194
Guido van Rossumc567c601992-11-05 22:22:37 +0000195 # Send a port command and a transfer command, accept the connection
196 # and return the socket for the connection
197 def transfercmd(self, cmd):
Guido van Rossum1115ab21992-11-04 15:51:30 +0000198 sock = self.makeport()
199 resp = self.sendcmd(cmd)
200 if resp[0] <> '1':
201 raise error_reply, resp
Guido van Rossumc567c601992-11-05 22:22:37 +0000202 conn, sockaddr = sock.accept()
203 return conn
204
205 # Login, default anonymous
206 def login(self, *args):
207 user = passwd = acct = ''
208 n = len(args)
209 if n > 3: raise TypeError, 'too many arguments'
210 if n > 0: user = args[0]
211 if n > 1: passwd = args[1]
212 if n > 2: acct = args[2]
213 if not user: user = 'anonymous'
214 if user == 'anonymous' and passwd in ('', '-'):
215 thishost = socket.gethostname()
216 if os.environ.has_key('LOGNAME'):
217 realuser = os.environ['LOGNAME']
218 elif os.environ.has_key('USER'):
219 realuser = os.environ['USER']
220 else:
221 realuser = 'anonymous'
222 passwd = passwd + realuser + '@' + thishost
223 resp = self.sendcmd('USER ' + user)
224 if resp[0] == '3': resp = self.sendcmd('PASS ' + passwd)
225 if resp[0] == '3': resp = self.sendcmd('ACCT ' + acct)
226 if resp[0] <> '2':
227 raise error_reply, resp
228
229 # Retrieve data in binary mode.
230 # The argument is a RETR command.
231 # The callback function is called for each block.
232 # This creates a new port for you
233 def retrbinary(self, cmd, callback, blocksize):
234 self.voidcmd('TYPE I')
235 conn = self.transfercmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000236 while 1:
237 data = conn.recv(blocksize)
238 if not data:
239 break
240 callback(data)
241 conn.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000242 self.voidresp()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000243
Guido van Rossumc567c601992-11-05 22:22:37 +0000244 # Retrieve data in line mode.
Guido van Rossum1115ab21992-11-04 15:51:30 +0000245 # The argument is a RETR or LIST command.
246 # The callback function is called for each line, with trailing
247 # CRLF stripped. This creates a new port for you
248 def retrlines(self, cmd, callback):
Guido van Rossumc567c601992-11-05 22:22:37 +0000249 resp = self.sendcmd('TYPE A')
250 conn = self.transfercmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000251 fp = conn.makefile('r')
252 while 1:
253 line = fp.readline()
254 if not line:
255 break
256 if line[-2:] == CRLF:
257 line = line[:-2]
258 elif line[:-1] == '\n':
259 line = line[:-1]
260 callback(line)
261 fp.close()
262 conn.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000263 self.voidresp()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000264
Guido van Rossumc567c601992-11-05 22:22:37 +0000265 # Store a file in binary mode
266 def storbinary(self, cmd, fp, blocksize):
267 self.voidcmd('TYPE I')
268 conn = self.transfercmd(cmd)
269 while 1:
270 buf = fp.read(blocksize)
271 if not buf: break
272 conn.send(buf)
273 conn.close()
274 self.voidresp()
275
276 # Store a file in line mode
277 def storlines(self, cmd, fp):
278 self.voidcmd('TYPE A')
279 conn = self.transfercmd(cmd)
280 while 1:
281 buf = fp.readline()
282 if not buf: break
283 if buf[-2:] <> CRLF:
284 if buf[-1] in CRLF: buf = buf[:-1]
285 buf = buf + CRLF
286 conn.send(buf)
287 conn.close()
288 self.voidresp()
289
290 # Return a list of files in a given directory (default the current)
291 def nlst(self, *args):
292 cmd = 'NLST'
293 for arg in args:
294 cmd = cmd + (' ' + arg)
295 files = []
296 self.retrlines(cmd, files.append)
297 return files
298
299 # Rename a file
300 def rename(self, fromname, toname):
301 resp = self.sendcmd('RNFR ' + fromname)
302 if resp[0] <> '3':
Guido van Rossum1115ab21992-11-04 15:51:30 +0000303 raise error_reply, resp
Guido van Rossumc567c601992-11-05 22:22:37 +0000304 self.voidcmd('RNTO ' + toname)
305
306 # Make a directory, return its full pathname
307 def mkd(self, dirname):
308 resp = self.sendcmd('MKD ' + dirname)
309 return parse257(resp)
310
311 # Return current wording directory
312 def pwd(self):
313 resp = self.sendcmd('PWD')
314 return parse257(resp)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000315
316 # Quit, and close the connection
317 def quit(self):
Guido van Rossumc567c601992-11-05 22:22:37 +0000318 self.voidcmd('QUIT')
Guido van Rossum1115ab21992-11-04 15:51:30 +0000319 self.file.close()
320 self.sock.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000321 del self.file, self.sock
322
323
324# Parse a response type 257
325def parse257(resp):
326 if resp[:3] <> '257':
327 raise error_reply, resp
328 if resp[3:5] <> ' "':
329 return '' # Not compliant to RFC 959, but UNIX ftpd does this
330 dirname = ''
331 i = 5
332 n = len(resp)
333 while i < n:
334 c = resp[i]
335 i = i+1
336 if c == '"':
337 if i >= n or resp[i] <> '"':
338 break
339 i = i+1
340 dirname = dirname + c
341 return dirname
Guido van Rossum1115ab21992-11-04 15:51:30 +0000342
343
344# Test program.
345# Usage: ftp [-d] host [-l[dir]] [-d[dir]] [file] ...
346def test():
347 import marshal
348 global nextport
349 try:
350 nextport = marshal.load(open('.@nextport', 'r'))
351 except IOError:
352 pass
353 try:
354 debugging = 0
355 while sys.argv[1] == '-d':
356 debugging = debugging+1
357 del sys.argv[1]
358 host = sys.argv[1]
359 ftp = FTP().init(host)
360 ftp.debug(debugging)
Guido van Rossumc567c601992-11-05 22:22:37 +0000361 ftp.login()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000362 def writeln(line): print line
363 for file in sys.argv[2:]:
364 if file[:2] == '-l':
365 cmd = 'LIST'
366 if file[2:]: cmd = cmd + ' ' + file[2:]
367 ftp.retrlines(cmd, writeln)
368 elif file[:2] == '-d':
369 cmd = 'CWD'
370 if file[2:]: cmd = cmd + ' ' + file[2:]
371 resp = ftp.sendcmd(cmd)
372 else:
373 ftp.retrbinary('RETR ' + file, \
374 sys.stdout.write, 1024)
375 ftp.quit()
376 finally:
377 marshal.dump(nextport, open('.@nextport', 'w'))