blob: e42ed8c6dfc66d400a41aa7ceda70ddd16076c18 [file] [log] [blame]
Guido van Rossumd2560b01996-05-28 23:41:25 +00001'''An FTP client class, and some helper functions.
2Based on RFC 959: File Transfer Protocol
3(FTP), by J. Postel and J. Reynolds
Guido van Rossum1115ab21992-11-04 15:51:30 +00004
Guido van Rossumd2560b01996-05-28 23:41:25 +00005Changes and improvements suggested by Steve Majewski.
6Modified by Jack to work on the mac.
7Modified by Siebren to support docstrings and PASV.
Guido van Rossumae3b3a31993-11-30 13:43:54 +00008
Guido van Rossum1115ab21992-11-04 15:51:30 +00009
Guido van Rossumd2560b01996-05-28 23:41:25 +000010Example:
11
12>>> from ftplib import FTP
13>>> ftp = FTP('ftp.python.org') # connect to host, default port
14>>> ftp.login() # default, i.e.: user anonymous, passwd user@hostname
15>>> ftp.retrlines('LIST') # list directory contents
16total 9
17drwxr-xr-x 8 root wheel 1024 Jan 3 1994 .
18drwxr-xr-x 8 root wheel 1024 Jan 3 1994 ..
19drwxr-xr-x 2 root wheel 1024 Jan 3 1994 bin
20drwxr-xr-x 2 root wheel 1024 Jan 3 1994 etc
21d-wxrwxr-x 2 ftp wheel 1024 Sep 5 13:43 incoming
22drwxr-xr-x 2 root wheel 1024 Nov 17 1993 lib
23drwxr-xr-x 6 1094 wheel 1024 Sep 13 19:07 pub
24drwxr-xr-x 3 root wheel 1024 Jan 3 1994 usr
25-rw-r--r-- 1 root root 312 Aug 1 1994 welcome.msg
26>>> ftp.quit()
27>>>
28
29A nice test that reveals some of the network dialogue would be:
30python ftplib.py -d localhost -l -p -l
31'''
Guido van Rossumc567c601992-11-05 22:22:37 +000032
33
Guido van Rossum1115ab21992-11-04 15:51:30 +000034import os
35import sys
Guido van Rossum1115ab21992-11-04 15:51:30 +000036import string
37
Guido van Rossumb6775db1994-08-01 11:34:53 +000038# Import SOCKS module if it exists, else standard socket module socket
39try:
40 import SOCKS; socket = SOCKS
41except ImportError:
42 import socket
43
Guido van Rossum1115ab21992-11-04 15:51:30 +000044
Guido van Rossumd3166071993-05-24 14:16:22 +000045# Magic number from <socket.h>
46MSG_OOB = 0x1 # Process data out of band
47
48
Guido van Rossumc567c601992-11-05 22:22:37 +000049# The standard FTP server control port
Guido van Rossum1115ab21992-11-04 15:51:30 +000050FTP_PORT = 21
Guido van Rossum1115ab21992-11-04 15:51:30 +000051
52
Guido van Rossum21974791992-11-06 13:34:17 +000053# Exception raised when an error or invalid response is received
Guido van Rossumc567c601992-11-05 22:22:37 +000054error_reply = 'ftplib.error_reply' # unexpected [123]xx reply
55error_temp = 'ftplib.error_temp' # 4xx errors
56error_perm = 'ftplib.error_perm' # 5xx errors
57error_proto = 'ftplib.error_proto' # response does not begin with [1-5]
Guido van Rossum1115ab21992-11-04 15:51:30 +000058
59
Guido van Rossum21974791992-11-06 13:34:17 +000060# All exceptions (hopefully) that may be raised here and that aren't
61# (always) programming errors on our side
62all_errors = (error_reply, error_temp, error_perm, error_proto, \
Guido van Rossumc0e68d11995-09-30 16:51:50 +000063 socket.error, IOError, EOFError)
Guido van Rossum21974791992-11-06 13:34:17 +000064
65
Guido van Rossum1115ab21992-11-04 15:51:30 +000066# Line terminators (we always output CRLF, but accept any of CRLF, CR, LF)
67CRLF = '\r\n'
68
69
Guido van Rossum1115ab21992-11-04 15:51:30 +000070# The class itself
71class FTP:
72
Guido van Rossumd2560b01996-05-28 23:41:25 +000073 '''An FTP client class.
74
75 To create a connection, call the class using these argument:
76 host, user, passwd, acct
77 These are all strings, and have default value ''.
78 Then use self.connect() with optional host and port argument.
79
80 To download a file, use ftp.retrlines('RETR ' + filename),
81 or ftp.retrbinary() with slightly different arguments.
82 To upload a file, use ftp.storlines() or ftp.storbinary(),
83 which have an open file as argument (see their definitions
84 below for details).
85 The download/upload functions first issue appropriate TYPE
86 and PORT or PASV commands.
87'''
88
89 # Initialization method (called by class instantiation).
Guido van Rossum52fc1f61993-06-17 12:38:10 +000090 # Initialize host to localhost, port to standard ftp port
Guido van Rossumae3b3a31993-11-30 13:43:54 +000091 # Optional arguments are host (for connect()),
92 # and user, passwd, acct (for login())
Guido van Rossumb6775db1994-08-01 11:34:53 +000093 def __init__(self, host = '', user = '', passwd = '', acct = ''):
Guido van Rossum52fc1f61993-06-17 12:38:10 +000094 # Initialize the instance to something mostly harmless
Guido van Rossum1115ab21992-11-04 15:51:30 +000095 self.debugging = 0
Guido van Rossum52fc1f61993-06-17 12:38:10 +000096 self.host = ''
97 self.port = FTP_PORT
98 self.sock = None
99 self.file = None
100 self.welcome = None
Guido van Rossumb6775db1994-08-01 11:34:53 +0000101 if host:
102 self.connect(host)
103 if user: self.login(user, passwd, acct)
Guido van Rossum52fc1f61993-06-17 12:38:10 +0000104
Guido van Rossumb6775db1994-08-01 11:34:53 +0000105 def connect(self, host = '', port = 0):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000106 '''Connect to host. Arguments are:
107 - host: hostname to connect to (string, default previous host)
108 - port: port to connect to (integer, default previous port)'''
Guido van Rossumb6775db1994-08-01 11:34:53 +0000109 if host: self.host = host
110 if port: self.port = port
Guido van Rossumd2560b01996-05-28 23:41:25 +0000111 self.passiveserver = 0
Guido van Rossum1115ab21992-11-04 15:51:30 +0000112 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
113 self.sock.connect(self.host, self.port)
Guido van Rossumd2560b01996-05-28 23:41:25 +0000114 self.file = self.sock.makefile('r')
Guido van Rossum1115ab21992-11-04 15:51:30 +0000115 self.welcome = self.getresp()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000116
Guido van Rossum1115ab21992-11-04 15:51:30 +0000117 def getwelcome(self):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000118 '''Get the welcome message from the server.
119 (this is read and squirreled away by connect())'''
Guido van Rossumebaf1041995-05-05 15:54:14 +0000120 if self.debugging:
121 print '*welcome*', self.sanitize(self.welcome)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000122 return self.welcome
123
Guido van Rossume65cce51993-11-08 15:05:21 +0000124 def set_debuglevel(self, level):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000125 '''Set the debugging level.
126 The required argument level means:
127 0: no debugging output (default)
128 1: print commands and responses but not body text etc.
129 2: also print raw lines read and sent before stripping CR/LF'''
Guido van Rossum1115ab21992-11-04 15:51:30 +0000130 self.debugging = level
Guido van Rossume65cce51993-11-08 15:05:21 +0000131 debug = set_debuglevel
Guido van Rossum1115ab21992-11-04 15:51:30 +0000132
Guido van Rossumd2560b01996-05-28 23:41:25 +0000133 def set_pasv(self, val):
134 '''Use passive or active mode for data transfers.
135 With a false argument, use the normal PORT mode,
136 With a true argument, use the PASV command.'''
137 self.passiveserver = val
138
Guido van Rossumebaf1041995-05-05 15:54:14 +0000139 # Internal: "sanitize" a string for printing
140 def sanitize(self, s):
141 if s[:5] == 'pass ' or s[:5] == 'PASS ':
142 i = len(s)
143 while i > 5 and s[i-1] in '\r\n':
144 i = i-1
145 s = s[:5] + '*'*(i-5) + s[i:]
146 return `s`
147
Guido van Rossum1115ab21992-11-04 15:51:30 +0000148 # Internal: send one line to the server, appending CRLF
149 def putline(self, line):
150 line = line + CRLF
Guido van Rossumebaf1041995-05-05 15:54:14 +0000151 if self.debugging > 1: print '*put*', self.sanitize(line)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000152 self.sock.send(line)
153
154 # Internal: send one command to the server (through putline())
155 def putcmd(self, line):
Guido van Rossumebaf1041995-05-05 15:54:14 +0000156 if self.debugging: print '*cmd*', self.sanitize(line)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000157 self.putline(line)
158
159 # Internal: return one line from the server, stripping CRLF.
160 # Raise EOFError if the connection is closed
161 def getline(self):
162 line = self.file.readline()
163 if self.debugging > 1:
Guido van Rossumebaf1041995-05-05 15:54:14 +0000164 print '*get*', self.sanitize(line)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000165 if not line: raise EOFError
166 if line[-2:] == CRLF: line = line[:-2]
167 elif line[-1:] in CRLF: line = line[:-1]
168 return line
169
170 # Internal: get a response from the server, which may possibly
171 # consist of multiple lines. Return a single string with no
172 # trailing CRLF. If the response consists of multiple lines,
173 # these are separated by '\n' characters in the string
174 def getmultiline(self):
175 line = self.getline()
176 if line[3:4] == '-':
177 code = line[:3]
178 while 1:
179 nextline = self.getline()
180 line = line + ('\n' + nextline)
181 if nextline[:3] == code and \
182 nextline[3:4] <> '-':
183 break
184 return line
185
186 # Internal: get a response from the server.
187 # Raise various errors if the response indicates an error
188 def getresp(self):
189 resp = self.getmultiline()
Guido van Rossumebaf1041995-05-05 15:54:14 +0000190 if self.debugging: print '*resp*', self.sanitize(resp)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000191 self.lastresp = resp[:3]
192 c = resp[:1]
193 if c == '4':
Guido van Rossumc567c601992-11-05 22:22:37 +0000194 raise error_temp, resp
Guido van Rossum1115ab21992-11-04 15:51:30 +0000195 if c == '5':
Guido van Rossumc567c601992-11-05 22:22:37 +0000196 raise error_perm, resp
Guido van Rossum1115ab21992-11-04 15:51:30 +0000197 if c not in '123':
Guido van Rossumc567c601992-11-05 22:22:37 +0000198 raise error_proto, resp
Guido van Rossum1115ab21992-11-04 15:51:30 +0000199 return resp
200
Guido van Rossumc567c601992-11-05 22:22:37 +0000201 def voidresp(self):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000202 """Expect a response beginning with '2'."""
Guido van Rossumc567c601992-11-05 22:22:37 +0000203 resp = self.getresp()
204 if resp[0] <> '2':
205 raise error_reply, resp
206
Guido van Rossumd3166071993-05-24 14:16:22 +0000207 def abort(self):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000208 '''Abort a file transfer. Uses out-of-band data.
209 This does not follow the procedure from the RFC to send Telnet
210 IP and Synch; that doesn't seem to work with the servers I've
211 tried. Instead, just send the ABOR command as OOB data.'''
Guido van Rossumd3166071993-05-24 14:16:22 +0000212 line = 'ABOR' + CRLF
Guido van Rossumebaf1041995-05-05 15:54:14 +0000213 if self.debugging > 1: print '*put urgent*', self.sanitize(line)
Guido van Rossumd3166071993-05-24 14:16:22 +0000214 self.sock.send(line, MSG_OOB)
215 resp = self.getmultiline()
216 if resp[:3] not in ('426', '226'):
217 raise error_proto, resp
218
Guido van Rossum1115ab21992-11-04 15:51:30 +0000219 def sendcmd(self, cmd):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000220 '''Send a command and return the response.'''
Guido van Rossum1115ab21992-11-04 15:51:30 +0000221 self.putcmd(cmd)
222 return self.getresp()
223
Guido van Rossumc567c601992-11-05 22:22:37 +0000224 def voidcmd(self, cmd):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000225 """Send a command and expect a response beginning with '2'."""
Guido van Rossumc68a4011992-11-05 23:01:42 +0000226 self.putcmd(cmd)
227 self.voidresp()
Guido van Rossumc567c601992-11-05 22:22:37 +0000228
Guido van Rossum221ec0b1995-08-04 04:39:30 +0000229 def sendport(self, host, port):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000230 '''Send a PORT command with the current host and the given port number.'''
Guido van Rossum221ec0b1995-08-04 04:39:30 +0000231 hbytes = string.splitfields(host, '.')
Guido van Rossum1115ab21992-11-04 15:51:30 +0000232 pbytes = [`port/256`, `port%256`]
233 bytes = hbytes + pbytes
234 cmd = 'PORT ' + string.joinfields(bytes, ',')
Guido van Rossumc567c601992-11-05 22:22:37 +0000235 self.voidcmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000236
Guido van Rossum1115ab21992-11-04 15:51:30 +0000237 def makeport(self):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000238 '''Create a new socket and send a PORT command for it.'''
Guido van Rossum1115ab21992-11-04 15:51:30 +0000239 global nextport
Guido van Rossum1115ab21992-11-04 15:51:30 +0000240 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Guido van Rossum303c1791995-06-20 17:21:42 +0000241 sock.bind(('', 0))
Guido van Rossumb6775db1994-08-01 11:34:53 +0000242 sock.listen(1)
Guido van Rossum221ec0b1995-08-04 04:39:30 +0000243 dummyhost, port = sock.getsockname() # Get proper port
244 host, dummyport = self.sock.getsockname() # Get proper host
245 resp = self.sendport(host, port)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000246 return sock
247
Guido van Rossumc567c601992-11-05 22:22:37 +0000248 def transfercmd(self, cmd):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000249 '''Initiate a transfer over the data connection.
250 If the transfer is active, send a port command and
251 the transfer command, and accept the connection.
252 If the server is passive, send a pasv command, connect
253 to it, and start the transfer command.
254 Either way, return the socket for the connection'''
255 if self.passiveserver:
256 host, port = parse227(self.sendcmd('PASV'))
257 conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
258 conn.connect(host, port)
259 resp = self.sendcmd(cmd)
260 if resp[0] <> '1':
261 raise error_reply, resp
262 else:
263 sock = self.makeport()
264 resp = self.sendcmd(cmd)
265 if resp[0] <> '1':
266 raise error_reply, resp
267 conn, sockaddr = sock.accept()
Guido van Rossumc567c601992-11-05 22:22:37 +0000268 return conn
269
Guido van Rossumb6775db1994-08-01 11:34:53 +0000270 def login(self, user = '', passwd = '', acct = ''):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000271 '''Login, default anonymous.'''
Guido van Rossumc567c601992-11-05 22:22:37 +0000272 if not user: user = 'anonymous'
273 if user == 'anonymous' and passwd in ('', '-'):
274 thishost = socket.gethostname()
Jack Jansen2db6bfc1995-05-04 15:02:18 +0000275 # Make sure it is fully qualified
276 if not '.' in thishost:
277 thisaddr = socket.gethostbyname(thishost)
Guido van Rossum303c1791995-06-20 17:21:42 +0000278 firstname, names, unused = \
279 socket.gethostbyaddr(thisaddr)
280 names.insert(0, firstname)
281 for name in names:
282 if '.' in name:
283 thishost = name
284 break
Jack Jansen40b98351995-01-19 12:24:45 +0000285 try:
286 if os.environ.has_key('LOGNAME'):
287 realuser = os.environ['LOGNAME']
288 elif os.environ.has_key('USER'):
289 realuser = os.environ['USER']
290 else:
291 realuser = 'anonymous'
292 except AttributeError:
293 # Not all systems have os.environ....
Guido van Rossumc567c601992-11-05 22:22:37 +0000294 realuser = 'anonymous'
295 passwd = passwd + realuser + '@' + thishost
296 resp = self.sendcmd('USER ' + user)
297 if resp[0] == '3': resp = self.sendcmd('PASS ' + passwd)
298 if resp[0] == '3': resp = self.sendcmd('ACCT ' + acct)
299 if resp[0] <> '2':
300 raise error_reply, resp
301
Guido van Rossumc567c601992-11-05 22:22:37 +0000302 def retrbinary(self, cmd, callback, blocksize):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000303 '''Retrieve data in binary mode.
304 The argument is a RETR command.
305 The callback function is called for each block.
306 This creates a new port for you'''
Guido van Rossumc567c601992-11-05 22:22:37 +0000307 self.voidcmd('TYPE I')
308 conn = self.transfercmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000309 while 1:
310 data = conn.recv(blocksize)
311 if not data:
312 break
313 callback(data)
314 conn.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000315 self.voidresp()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000316
Guido van Rossumb6775db1994-08-01 11:34:53 +0000317 def retrlines(self, cmd, callback = None):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000318 '''Retrieve data in line mode.
319 The argument is a RETR or LIST command.
320 The callback function (2nd argument) is called for each line,
321 with trailing CRLF stripped. This creates a new port for you.
322 print_lines is the default callback.'''
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000323 if not callback: callback = print_line
Guido van Rossumc567c601992-11-05 22:22:37 +0000324 resp = self.sendcmd('TYPE A')
325 conn = self.transfercmd(cmd)
Guido van Rossumd2560b01996-05-28 23:41:25 +0000326 fp = conn.makefile('r')
Guido van Rossum1115ab21992-11-04 15:51:30 +0000327 while 1:
328 line = fp.readline()
Guido van Rossumc0e68d11995-09-30 16:51:50 +0000329 if self.debugging > 2: print '*retr*', `line`
Guido van Rossum1115ab21992-11-04 15:51:30 +0000330 if not line:
331 break
332 if line[-2:] == CRLF:
333 line = line[:-2]
334 elif line[:-1] == '\n':
335 line = line[:-1]
336 callback(line)
337 fp.close()
338 conn.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000339 self.voidresp()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000340
Guido van Rossumc567c601992-11-05 22:22:37 +0000341 def storbinary(self, cmd, fp, blocksize):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000342 '''Store a file in binary mode.'''
Guido van Rossumc567c601992-11-05 22:22:37 +0000343 self.voidcmd('TYPE I')
344 conn = self.transfercmd(cmd)
345 while 1:
346 buf = fp.read(blocksize)
347 if not buf: break
348 conn.send(buf)
349 conn.close()
350 self.voidresp()
351
Guido van Rossumc567c601992-11-05 22:22:37 +0000352 def storlines(self, cmd, fp):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000353 '''Store a file in line mode.'''
Guido van Rossumc567c601992-11-05 22:22:37 +0000354 self.voidcmd('TYPE A')
355 conn = self.transfercmd(cmd)
356 while 1:
357 buf = fp.readline()
358 if not buf: break
359 if buf[-2:] <> CRLF:
360 if buf[-1] in CRLF: buf = buf[:-1]
361 buf = buf + CRLF
362 conn.send(buf)
363 conn.close()
364 self.voidresp()
365
Guido van Rossum0eaa74b1996-01-25 18:37:21 +0000366 def acct(self, password):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000367 '''Send new account name.'''
Guido van Rossum0eaa74b1996-01-25 18:37:21 +0000368 cmd = 'ACCT ' + password
369 self.voidcmd(cmd)
370
Guido van Rossumc567c601992-11-05 22:22:37 +0000371 def nlst(self, *args):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000372 '''Return a list of files in a given directory (default the current).'''
Guido van Rossumc567c601992-11-05 22:22:37 +0000373 cmd = 'NLST'
374 for arg in args:
375 cmd = cmd + (' ' + arg)
376 files = []
377 self.retrlines(cmd, files.append)
378 return files
379
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000380 def dir(self, *args):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000381 '''List a directory in long form.
382 By default list current directory to stdout.
383 Optional last argument is callback function; all
384 non-empty arguments before it are concatenated to the
385 LIST command. (This *should* only be used for a pathname.)'''
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000386 cmd = 'LIST'
387 func = None
388 if args[-1:] and type(args[-1]) != type(''):
389 args, func = args[:-1], args[-1]
390 for arg in args:
391 if arg:
392 cmd = cmd + (' ' + arg)
393 self.retrlines(cmd, func)
394
Guido van Rossumc567c601992-11-05 22:22:37 +0000395 def rename(self, fromname, toname):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000396 '''Rename a file.'''
Guido van Rossumc567c601992-11-05 22:22:37 +0000397 resp = self.sendcmd('RNFR ' + fromname)
398 if resp[0] <> '3':
Guido van Rossum1115ab21992-11-04 15:51:30 +0000399 raise error_reply, resp
Guido van Rossumc567c601992-11-05 22:22:37 +0000400 self.voidcmd('RNTO ' + toname)
401
Guido van Rossuma61bdeb1995-10-11 17:36:31 +0000402 def delete(self, filename):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000403 '''Delete a file.'''
Guido van Rossuma61bdeb1995-10-11 17:36:31 +0000404 resp = self.sendcmd('DELE ' + filename)
405 if resp[:3] == '250':
406 return
407 elif resp[:1] == '5':
408 raise error_perm, resp
409 else:
410 raise error_reply, resp
411
Guido van Rossum02cf5821993-05-17 08:00:02 +0000412 def cwd(self, dirname):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000413 '''Change to a directory.'''
Guido van Rossumdf563861993-07-06 15:19:36 +0000414 if dirname == '..':
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000415 try:
416 self.voidcmd('CDUP')
417 return
418 except error_perm, msg:
419 if msg[:3] != '500':
420 raise error_perm, msg
421 cmd = 'CWD ' + dirname
Guido van Rossumdf563861993-07-06 15:19:36 +0000422 self.voidcmd(cmd)
Guido van Rossum02cf5821993-05-17 08:00:02 +0000423
Guido van Rossum17ed1ae1993-06-01 13:21:04 +0000424 def size(self, filename):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000425 '''Retrieve the size of a file.'''
426 # Note that the RFC doesn't say anything about 'SIZE'
Guido van Rossum17ed1ae1993-06-01 13:21:04 +0000427 resp = self.sendcmd('SIZE ' + filename)
428 if resp[:3] == '213':
429 return string.atoi(string.strip(resp[3:]))
430
Guido van Rossumc567c601992-11-05 22:22:37 +0000431 def mkd(self, dirname):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000432 '''Make a directory, return its full pathname.'''
Guido van Rossumc567c601992-11-05 22:22:37 +0000433 resp = self.sendcmd('MKD ' + dirname)
434 return parse257(resp)
435
Guido van Rossumc567c601992-11-05 22:22:37 +0000436 def pwd(self):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000437 '''Return current working directory.'''
Guido van Rossumc567c601992-11-05 22:22:37 +0000438 resp = self.sendcmd('PWD')
439 return parse257(resp)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000440
Guido van Rossum1115ab21992-11-04 15:51:30 +0000441 def quit(self):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000442 '''Quit, and close the connection.'''
Guido van Rossumc567c601992-11-05 22:22:37 +0000443 self.voidcmd('QUIT')
Guido van Rossum17ed1ae1993-06-01 13:21:04 +0000444 self.close()
445
Guido van Rossum17ed1ae1993-06-01 13:21:04 +0000446 def close(self):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000447 '''Close the connection without assuming anything about it.'''
Guido van Rossum1115ab21992-11-04 15:51:30 +0000448 self.file.close()
449 self.sock.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000450 del self.file, self.sock
451
452
Guido van Rossumd2560b01996-05-28 23:41:25 +0000453def parse227(resp):
454 '''Parse the '227' response for a PASV request.
455 Raises error_proto if it does not contain '(h1,h2,h3,h4,p1,p2)'
456 Return ('host.addr.as.numbers', port#) tuple.'''
457
458 if resp[:3] <> '227':
459 raise error_reply, resp
460 left = string.find(resp, '(')
461 if left < 0: raise error_proto, resp
462 right = string.find(resp, ')', left + 1)
463 if right < 0:
464 raise error_proto, resp # should contain '(h1,h2,h3,h4,p1,p2)'
465 numbers = string.split(resp[left+1:right], ',')
466 if len(numbers) <> 6:
467 raise error_proto, resp
468 host = string.join(numbers[:4], '.')
469 port = (string.atoi(numbers[4]) << 8) + string.atoi(numbers[5])
470 return host, port
471# end parse227
472
473
Guido van Rossumc567c601992-11-05 22:22:37 +0000474def parse257(resp):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000475 '''Parse the '257' response for a MKD or RMD request.
476 This is a response to a MKD or RMD request: a directory name.
477 Returns the directoryname in the 257 reply.'''
478
Guido van Rossumc567c601992-11-05 22:22:37 +0000479 if resp[:3] <> '257':
480 raise error_reply, resp
481 if resp[3:5] <> ' "':
482 return '' # Not compliant to RFC 959, but UNIX ftpd does this
483 dirname = ''
484 i = 5
485 n = len(resp)
486 while i < n:
487 c = resp[i]
488 i = i+1
489 if c == '"':
490 if i >= n or resp[i] <> '"':
491 break
492 i = i+1
493 dirname = dirname + c
494 return dirname
Guido van Rossum1115ab21992-11-04 15:51:30 +0000495
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000496def print_line(line):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000497 '''Default retrlines callback to print a line.'''
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000498 print line
499
Guido van Rossumd2560b01996-05-28 23:41:25 +0000500def ftpcp(source, sourcename, target, targetname = '', type = 'I'):
501 '''Copy file from one FTP-instance to another.'''
502 if not targetname: targetname = sourcename
503 type = 'TYPE ' + type
504 source.voidcmd(type)
505 target.voidcmd(type)
506 sourcehost, sourceport = parse227(source.sendcmd('PASV'))
507 target.sendport(sourcehost, sourceport)
508 # RFC 959: the user must "listen" [...] BEFORE sending the
509 # transfer request.
510 # So: STOR before RETR, because here the target is a "user".
511 treply = target.sendcmd('STOR ' + targetname)
512 if treply[:3] not in ('125', '150'): raise error_proto # RFC 959
513 sreply = source.sendcmd('RETR ' + sourcename)
514 if sreply[:3] not in ('125', '150'): raise error_proto # RFC 959
515 source.voidresp()
516 target.voidresp()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000517
Guido van Rossum1115ab21992-11-04 15:51:30 +0000518def test():
Guido van Rossumd2560b01996-05-28 23:41:25 +0000519 '''Test program.
520 Usage: ftp [-d] host [-l[dir]] [-d[dir]] [-p] [file] ...'''
521
Guido van Rossumb6775db1994-08-01 11:34:53 +0000522 debugging = 0
523 while sys.argv[1] == '-d':
524 debugging = debugging+1
525 del sys.argv[1]
526 host = sys.argv[1]
527 ftp = FTP(host)
528 ftp.set_debuglevel(debugging)
529 ftp.login()
530 for file in sys.argv[2:]:
531 if file[:2] == '-l':
532 ftp.dir(file[2:])
533 elif file[:2] == '-d':
534 cmd = 'CWD'
535 if file[2:]: cmd = cmd + ' ' + file[2:]
536 resp = ftp.sendcmd(cmd)
Guido van Rossumd2560b01996-05-28 23:41:25 +0000537 elif file == '-p':
538 ftp.set_pasv(not ftp.passiveserver)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000539 else:
540 ftp.retrbinary('RETR ' + file, \
541 sys.stdout.write, 1024)
542 ftp.quit()
Guido van Rossum221ec0b1995-08-04 04:39:30 +0000543
544
545if __name__ == '__main__':
546 test()