blob: ec7d4791ddbf7f814315da78308d55823cdfc3b3 [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
Guido van Rossum2f3941d1997-10-07 14:49:56 +000015'230 Guest login ok, access restrictions apply.'
Guido van Rossumd2560b01996-05-28 23:41:25 +000016>>> ftp.retrlines('LIST') # list directory contents
17total 9
18drwxr-xr-x 8 root wheel 1024 Jan 3 1994 .
19drwxr-xr-x 8 root wheel 1024 Jan 3 1994 ..
20drwxr-xr-x 2 root wheel 1024 Jan 3 1994 bin
21drwxr-xr-x 2 root wheel 1024 Jan 3 1994 etc
22d-wxrwxr-x 2 ftp wheel 1024 Sep 5 13:43 incoming
23drwxr-xr-x 2 root wheel 1024 Nov 17 1993 lib
24drwxr-xr-x 6 1094 wheel 1024 Sep 13 19:07 pub
25drwxr-xr-x 3 root wheel 1024 Jan 3 1994 usr
26-rw-r--r-- 1 root root 312 Aug 1 1994 welcome.msg
Guido van Rossum2f3941d1997-10-07 14:49:56 +000027'226 Transfer complete.'
Guido van Rossumd2560b01996-05-28 23:41:25 +000028>>> ftp.quit()
Guido van Rossum2f3941d1997-10-07 14:49:56 +000029'221 Goodbye.'
Guido van Rossumd2560b01996-05-28 23:41:25 +000030>>>
31
32A nice test that reveals some of the network dialogue would be:
33python ftplib.py -d localhost -l -p -l
34'''
Guido van Rossumc567c601992-11-05 22:22:37 +000035
36
Guido van Rossum1115ab21992-11-04 15:51:30 +000037import os
38import sys
Guido van Rossum1115ab21992-11-04 15:51:30 +000039import string
40
Guido van Rossumb6775db1994-08-01 11:34:53 +000041# Import SOCKS module if it exists, else standard socket module socket
42try:
43 import SOCKS; socket = SOCKS
44except ImportError:
45 import socket
46
Guido van Rossum1115ab21992-11-04 15:51:30 +000047
Guido van Rossumd3166071993-05-24 14:16:22 +000048# Magic number from <socket.h>
49MSG_OOB = 0x1 # Process data out of band
50
51
Guido van Rossumc567c601992-11-05 22:22:37 +000052# The standard FTP server control port
Guido van Rossum1115ab21992-11-04 15:51:30 +000053FTP_PORT = 21
Guido van Rossum1115ab21992-11-04 15:51:30 +000054
55
Guido van Rossum21974791992-11-06 13:34:17 +000056# Exception raised when an error or invalid response is received
Guido van Rossumc567c601992-11-05 22:22:37 +000057error_reply = 'ftplib.error_reply' # unexpected [123]xx reply
58error_temp = 'ftplib.error_temp' # 4xx errors
59error_perm = 'ftplib.error_perm' # 5xx errors
60error_proto = 'ftplib.error_proto' # response does not begin with [1-5]
Guido van Rossum1115ab21992-11-04 15:51:30 +000061
62
Guido van Rossum21974791992-11-06 13:34:17 +000063# All exceptions (hopefully) that may be raised here and that aren't
64# (always) programming errors on our side
65all_errors = (error_reply, error_temp, error_perm, error_proto, \
Guido van Rossumc0e68d11995-09-30 16:51:50 +000066 socket.error, IOError, EOFError)
Guido van Rossum21974791992-11-06 13:34:17 +000067
68
Guido van Rossum1115ab21992-11-04 15:51:30 +000069# Line terminators (we always output CRLF, but accept any of CRLF, CR, LF)
70CRLF = '\r\n'
71
72
Guido van Rossum1115ab21992-11-04 15:51:30 +000073# The class itself
74class FTP:
75
Guido van Rossumd2560b01996-05-28 23:41:25 +000076 '''An FTP client class.
77
78 To create a connection, call the class using these argument:
79 host, user, passwd, acct
80 These are all strings, and have default value ''.
81 Then use self.connect() with optional host and port argument.
82
83 To download a file, use ftp.retrlines('RETR ' + filename),
84 or ftp.retrbinary() with slightly different arguments.
85 To upload a file, use ftp.storlines() or ftp.storbinary(),
86 which have an open file as argument (see their definitions
87 below for details).
88 The download/upload functions first issue appropriate TYPE
89 and PORT or PASV commands.
90'''
91
92 # Initialization method (called by class instantiation).
Guido van Rossum52fc1f61993-06-17 12:38:10 +000093 # Initialize host to localhost, port to standard ftp port
Guido van Rossumae3b3a31993-11-30 13:43:54 +000094 # Optional arguments are host (for connect()),
95 # and user, passwd, acct (for login())
Guido van Rossumb6775db1994-08-01 11:34:53 +000096 def __init__(self, host = '', user = '', passwd = '', acct = ''):
Guido van Rossum52fc1f61993-06-17 12:38:10 +000097 # Initialize the instance to something mostly harmless
Guido van Rossum1115ab21992-11-04 15:51:30 +000098 self.debugging = 0
Guido van Rossum52fc1f61993-06-17 12:38:10 +000099 self.host = ''
100 self.port = FTP_PORT
101 self.sock = None
102 self.file = None
103 self.welcome = None
Guido van Rossum2f3941d1997-10-07 14:49:56 +0000104 resp = None
Guido van Rossumb6775db1994-08-01 11:34:53 +0000105 if host:
Guido van Rossum2f3941d1997-10-07 14:49:56 +0000106 resp = self.connect(host)
107 if user: resp = self.login(user, passwd, acct)
Guido van Rossum52fc1f61993-06-17 12:38:10 +0000108
Guido van Rossumb6775db1994-08-01 11:34:53 +0000109 def connect(self, host = '', port = 0):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000110 '''Connect to host. Arguments are:
111 - host: hostname to connect to (string, default previous host)
112 - port: port to connect to (integer, default previous port)'''
Guido van Rossumb6775db1994-08-01 11:34:53 +0000113 if host: self.host = host
114 if port: self.port = port
Guido van Rossumd2560b01996-05-28 23:41:25 +0000115 self.passiveserver = 0
Guido van Rossum1115ab21992-11-04 15:51:30 +0000116 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
117 self.sock.connect(self.host, self.port)
Guido van Rossum24611f81996-09-30 22:02:50 +0000118 self.file = self.sock.makefile('rb')
Guido van Rossum1115ab21992-11-04 15:51:30 +0000119 self.welcome = self.getresp()
Guido van Rossum2f3941d1997-10-07 14:49:56 +0000120 return self.welcome
Guido van Rossum1115ab21992-11-04 15:51:30 +0000121
Guido van Rossum1115ab21992-11-04 15:51:30 +0000122 def getwelcome(self):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000123 '''Get the welcome message from the server.
124 (this is read and squirreled away by connect())'''
Guido van Rossumebaf1041995-05-05 15:54:14 +0000125 if self.debugging:
126 print '*welcome*', self.sanitize(self.welcome)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000127 return self.welcome
128
Guido van Rossume65cce51993-11-08 15:05:21 +0000129 def set_debuglevel(self, level):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000130 '''Set the debugging level.
131 The required argument level means:
132 0: no debugging output (default)
133 1: print commands and responses but not body text etc.
134 2: also print raw lines read and sent before stripping CR/LF'''
Guido van Rossum1115ab21992-11-04 15:51:30 +0000135 self.debugging = level
Guido van Rossume65cce51993-11-08 15:05:21 +0000136 debug = set_debuglevel
Guido van Rossum1115ab21992-11-04 15:51:30 +0000137
Guido van Rossumd2560b01996-05-28 23:41:25 +0000138 def set_pasv(self, val):
139 '''Use passive or active mode for data transfers.
140 With a false argument, use the normal PORT mode,
141 With a true argument, use the PASV command.'''
142 self.passiveserver = val
143
Guido van Rossumebaf1041995-05-05 15:54:14 +0000144 # Internal: "sanitize" a string for printing
145 def sanitize(self, s):
146 if s[:5] == 'pass ' or s[:5] == 'PASS ':
147 i = len(s)
148 while i > 5 and s[i-1] in '\r\n':
149 i = i-1
150 s = s[:5] + '*'*(i-5) + s[i:]
151 return `s`
152
Guido van Rossum1115ab21992-11-04 15:51:30 +0000153 # Internal: send one line to the server, appending CRLF
154 def putline(self, line):
155 line = line + CRLF
Guido van Rossumebaf1041995-05-05 15:54:14 +0000156 if self.debugging > 1: print '*put*', self.sanitize(line)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000157 self.sock.send(line)
158
159 # Internal: send one command to the server (through putline())
160 def putcmd(self, line):
Guido van Rossumebaf1041995-05-05 15:54:14 +0000161 if self.debugging: print '*cmd*', self.sanitize(line)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000162 self.putline(line)
163
164 # Internal: return one line from the server, stripping CRLF.
165 # Raise EOFError if the connection is closed
166 def getline(self):
167 line = self.file.readline()
168 if self.debugging > 1:
Guido van Rossumebaf1041995-05-05 15:54:14 +0000169 print '*get*', self.sanitize(line)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000170 if not line: raise EOFError
171 if line[-2:] == CRLF: line = line[:-2]
172 elif line[-1:] in CRLF: line = line[:-1]
173 return line
174
175 # Internal: get a response from the server, which may possibly
176 # consist of multiple lines. Return a single string with no
177 # trailing CRLF. If the response consists of multiple lines,
178 # these are separated by '\n' characters in the string
179 def getmultiline(self):
180 line = self.getline()
181 if line[3:4] == '-':
182 code = line[:3]
183 while 1:
184 nextline = self.getline()
185 line = line + ('\n' + nextline)
186 if nextline[:3] == code and \
187 nextline[3:4] <> '-':
188 break
189 return line
190
191 # Internal: get a response from the server.
192 # Raise various errors if the response indicates an error
193 def getresp(self):
194 resp = self.getmultiline()
Guido van Rossumebaf1041995-05-05 15:54:14 +0000195 if self.debugging: print '*resp*', self.sanitize(resp)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000196 self.lastresp = resp[:3]
197 c = resp[:1]
198 if c == '4':
Guido van Rossumc567c601992-11-05 22:22:37 +0000199 raise error_temp, resp
Guido van Rossum1115ab21992-11-04 15:51:30 +0000200 if c == '5':
Guido van Rossumc567c601992-11-05 22:22:37 +0000201 raise error_perm, resp
Guido van Rossum1115ab21992-11-04 15:51:30 +0000202 if c not in '123':
Guido van Rossumc567c601992-11-05 22:22:37 +0000203 raise error_proto, resp
Guido van Rossum1115ab21992-11-04 15:51:30 +0000204 return resp
205
Guido van Rossumc567c601992-11-05 22:22:37 +0000206 def voidresp(self):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000207 """Expect a response beginning with '2'."""
Guido van Rossumc567c601992-11-05 22:22:37 +0000208 resp = self.getresp()
209 if resp[0] <> '2':
210 raise error_reply, resp
Guido van Rossum2f3941d1997-10-07 14:49:56 +0000211 return resp
Guido van Rossumc567c601992-11-05 22:22:37 +0000212
Guido van Rossumd3166071993-05-24 14:16:22 +0000213 def abort(self):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000214 '''Abort a file transfer. Uses out-of-band data.
215 This does not follow the procedure from the RFC to send Telnet
216 IP and Synch; that doesn't seem to work with the servers I've
217 tried. Instead, just send the ABOR command as OOB data.'''
Guido van Rossumd3166071993-05-24 14:16:22 +0000218 line = 'ABOR' + CRLF
Guido van Rossumebaf1041995-05-05 15:54:14 +0000219 if self.debugging > 1: print '*put urgent*', self.sanitize(line)
Guido van Rossumd3166071993-05-24 14:16:22 +0000220 self.sock.send(line, MSG_OOB)
221 resp = self.getmultiline()
222 if resp[:3] not in ('426', '226'):
223 raise error_proto, resp
224
Guido van Rossum1115ab21992-11-04 15:51:30 +0000225 def sendcmd(self, cmd):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000226 '''Send a command and return the response.'''
Guido van Rossum1115ab21992-11-04 15:51:30 +0000227 self.putcmd(cmd)
228 return self.getresp()
229
Guido van Rossumc567c601992-11-05 22:22:37 +0000230 def voidcmd(self, cmd):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000231 """Send a command and expect a response beginning with '2'."""
Guido van Rossumc68a4011992-11-05 23:01:42 +0000232 self.putcmd(cmd)
Guido van Rossum2f3941d1997-10-07 14:49:56 +0000233 return self.voidresp()
Guido van Rossumc567c601992-11-05 22:22:37 +0000234
Guido van Rossum221ec0b1995-08-04 04:39:30 +0000235 def sendport(self, host, port):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000236 '''Send a PORT command with the current host and the given port number.'''
Guido van Rossum221ec0b1995-08-04 04:39:30 +0000237 hbytes = string.splitfields(host, '.')
Guido van Rossum1115ab21992-11-04 15:51:30 +0000238 pbytes = [`port/256`, `port%256`]
239 bytes = hbytes + pbytes
240 cmd = 'PORT ' + string.joinfields(bytes, ',')
Guido van Rossum2f3941d1997-10-07 14:49:56 +0000241 return self.voidcmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000242
Guido van Rossum1115ab21992-11-04 15:51:30 +0000243 def makeport(self):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000244 '''Create a new socket and send a PORT command for it.'''
Guido van Rossum1115ab21992-11-04 15:51:30 +0000245 global nextport
Guido van Rossum1115ab21992-11-04 15:51:30 +0000246 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Guido van Rossum303c1791995-06-20 17:21:42 +0000247 sock.bind(('', 0))
Guido van Rossumb6775db1994-08-01 11:34:53 +0000248 sock.listen(1)
Guido van Rossum221ec0b1995-08-04 04:39:30 +0000249 dummyhost, port = sock.getsockname() # Get proper port
250 host, dummyport = self.sock.getsockname() # Get proper host
251 resp = self.sendport(host, port)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000252 return sock
253
Fred Drake4de02d91997-01-10 18:26:09 +0000254 def ntransfercmd(self, cmd):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000255 '''Initiate a transfer over the data connection.
256 If the transfer is active, send a port command and
257 the transfer command, and accept the connection.
258 If the server is passive, send a pasv command, connect
259 to it, and start the transfer command.
Fred Drake4de02d91997-01-10 18:26:09 +0000260 Either way, return the socket for the connection and
261 the expected size of the transfer. The expected size
262 may be None if it could not be determined.'''
263 size = None
Guido van Rossumd2560b01996-05-28 23:41:25 +0000264 if self.passiveserver:
265 host, port = parse227(self.sendcmd('PASV'))
266 conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
267 conn.connect(host, port)
268 resp = self.sendcmd(cmd)
269 if resp[0] <> '1':
270 raise error_reply, resp
271 else:
272 sock = self.makeport()
273 resp = self.sendcmd(cmd)
274 if resp[0] <> '1':
275 raise error_reply, resp
276 conn, sockaddr = sock.accept()
Fred Drake4de02d91997-01-10 18:26:09 +0000277 if resp[:3] == '150':
278 # this is conditional in case we received a 125
279 size = parse150(resp)
280 return conn, size
281
282 def transfercmd(self, cmd):
283 '''Initiate a transfer over the data connection. Returns
284 the socket for the connection. See also ntransfercmd().'''
285 return self.ntransfercmd(cmd)[0]
Guido van Rossumc567c601992-11-05 22:22:37 +0000286
Guido van Rossumb6775db1994-08-01 11:34:53 +0000287 def login(self, user = '', passwd = '', acct = ''):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000288 '''Login, default anonymous.'''
Guido van Rossumc567c601992-11-05 22:22:37 +0000289 if not user: user = 'anonymous'
290 if user == 'anonymous' and passwd in ('', '-'):
291 thishost = socket.gethostname()
Jack Jansen2db6bfc1995-05-04 15:02:18 +0000292 # Make sure it is fully qualified
293 if not '.' in thishost:
294 thisaddr = socket.gethostbyname(thishost)
Guido van Rossum303c1791995-06-20 17:21:42 +0000295 firstname, names, unused = \
296 socket.gethostbyaddr(thisaddr)
297 names.insert(0, firstname)
298 for name in names:
299 if '.' in name:
300 thishost = name
301 break
Jack Jansen40b98351995-01-19 12:24:45 +0000302 try:
303 if os.environ.has_key('LOGNAME'):
304 realuser = os.environ['LOGNAME']
305 elif os.environ.has_key('USER'):
306 realuser = os.environ['USER']
307 else:
308 realuser = 'anonymous'
309 except AttributeError:
310 # Not all systems have os.environ....
Guido van Rossumc567c601992-11-05 22:22:37 +0000311 realuser = 'anonymous'
312 passwd = passwd + realuser + '@' + thishost
313 resp = self.sendcmd('USER ' + user)
314 if resp[0] == '3': resp = self.sendcmd('PASS ' + passwd)
315 if resp[0] == '3': resp = self.sendcmd('ACCT ' + acct)
316 if resp[0] <> '2':
317 raise error_reply, resp
Guido van Rossum2f3941d1997-10-07 14:49:56 +0000318 return resp
Guido van Rossumc567c601992-11-05 22:22:37 +0000319
Guido van Rossumc567c601992-11-05 22:22:37 +0000320 def retrbinary(self, cmd, callback, blocksize):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000321 '''Retrieve data in binary mode.
322 The argument is a RETR command.
323 The callback function is called for each block.
324 This creates a new port for you'''
Guido van Rossumc567c601992-11-05 22:22:37 +0000325 self.voidcmd('TYPE I')
326 conn = self.transfercmd(cmd)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000327 while 1:
328 data = conn.recv(blocksize)
329 if not data:
330 break
331 callback(data)
332 conn.close()
Guido van Rossum2f3941d1997-10-07 14:49:56 +0000333 return self.voidresp()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000334
Guido van Rossumb6775db1994-08-01 11:34:53 +0000335 def retrlines(self, cmd, callback = None):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000336 '''Retrieve data in line mode.
337 The argument is a RETR or LIST command.
338 The callback function (2nd argument) is called for each line,
339 with trailing CRLF stripped. This creates a new port for you.
340 print_lines is the default callback.'''
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000341 if not callback: callback = print_line
Guido van Rossumc567c601992-11-05 22:22:37 +0000342 resp = self.sendcmd('TYPE A')
343 conn = self.transfercmd(cmd)
Guido van Rossum24611f81996-09-30 22:02:50 +0000344 fp = conn.makefile('rb')
Guido van Rossum1115ab21992-11-04 15:51:30 +0000345 while 1:
346 line = fp.readline()
Guido van Rossumc0e68d11995-09-30 16:51:50 +0000347 if self.debugging > 2: print '*retr*', `line`
Guido van Rossum1115ab21992-11-04 15:51:30 +0000348 if not line:
349 break
350 if line[-2:] == CRLF:
351 line = line[:-2]
352 elif line[:-1] == '\n':
353 line = line[:-1]
354 callback(line)
355 fp.close()
356 conn.close()
Guido van Rossum2f3941d1997-10-07 14:49:56 +0000357 return self.voidresp()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000358
Guido van Rossumc567c601992-11-05 22:22:37 +0000359 def storbinary(self, cmd, fp, blocksize):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000360 '''Store a file in binary mode.'''
Guido van Rossumc567c601992-11-05 22:22:37 +0000361 self.voidcmd('TYPE I')
362 conn = self.transfercmd(cmd)
363 while 1:
364 buf = fp.read(blocksize)
365 if not buf: break
366 conn.send(buf)
367 conn.close()
Guido van Rossum2f3941d1997-10-07 14:49:56 +0000368 return self.voidresp()
Guido van Rossumc567c601992-11-05 22:22:37 +0000369
Guido van Rossumc567c601992-11-05 22:22:37 +0000370 def storlines(self, cmd, fp):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000371 '''Store a file in line mode.'''
Guido van Rossumc567c601992-11-05 22:22:37 +0000372 self.voidcmd('TYPE A')
373 conn = self.transfercmd(cmd)
374 while 1:
375 buf = fp.readline()
376 if not buf: break
377 if buf[-2:] <> CRLF:
378 if buf[-1] in CRLF: buf = buf[:-1]
379 buf = buf + CRLF
380 conn.send(buf)
381 conn.close()
Guido van Rossum2f3941d1997-10-07 14:49:56 +0000382 return self.voidresp()
Guido van Rossumc567c601992-11-05 22:22:37 +0000383
Guido van Rossum0eaa74b1996-01-25 18:37:21 +0000384 def acct(self, password):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000385 '''Send new account name.'''
Guido van Rossum0eaa74b1996-01-25 18:37:21 +0000386 cmd = 'ACCT ' + password
Guido van Rossum2f3941d1997-10-07 14:49:56 +0000387 return self.voidcmd(cmd)
Guido van Rossum0eaa74b1996-01-25 18:37:21 +0000388
Guido van Rossumc567c601992-11-05 22:22:37 +0000389 def nlst(self, *args):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000390 '''Return a list of files in a given directory (default the current).'''
Guido van Rossumc567c601992-11-05 22:22:37 +0000391 cmd = 'NLST'
392 for arg in args:
393 cmd = cmd + (' ' + arg)
394 files = []
395 self.retrlines(cmd, files.append)
396 return files
397
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000398 def dir(self, *args):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000399 '''List a directory in long form.
400 By default list current directory to stdout.
401 Optional last argument is callback function; all
402 non-empty arguments before it are concatenated to the
403 LIST command. (This *should* only be used for a pathname.)'''
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000404 cmd = 'LIST'
405 func = None
406 if args[-1:] and type(args[-1]) != type(''):
407 args, func = args[:-1], args[-1]
408 for arg in args:
409 if arg:
410 cmd = cmd + (' ' + arg)
411 self.retrlines(cmd, func)
412
Guido van Rossumc567c601992-11-05 22:22:37 +0000413 def rename(self, fromname, toname):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000414 '''Rename a file.'''
Guido van Rossumc567c601992-11-05 22:22:37 +0000415 resp = self.sendcmd('RNFR ' + fromname)
416 if resp[0] <> '3':
Guido van Rossum1115ab21992-11-04 15:51:30 +0000417 raise error_reply, resp
Guido van Rossum2f3941d1997-10-07 14:49:56 +0000418 return self.voidcmd('RNTO ' + toname)
Guido van Rossumc567c601992-11-05 22:22:37 +0000419
Guido van Rossuma61bdeb1995-10-11 17:36:31 +0000420 def delete(self, filename):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000421 '''Delete a file.'''
Guido van Rossuma61bdeb1995-10-11 17:36:31 +0000422 resp = self.sendcmd('DELE ' + filename)
423 if resp[:3] == '250':
Guido van Rossum2f3941d1997-10-07 14:49:56 +0000424 return resp
Guido van Rossuma61bdeb1995-10-11 17:36:31 +0000425 elif resp[:1] == '5':
426 raise error_perm, resp
427 else:
428 raise error_reply, resp
429
Guido van Rossum02cf5821993-05-17 08:00:02 +0000430 def cwd(self, dirname):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000431 '''Change to a directory.'''
Guido van Rossumdf563861993-07-06 15:19:36 +0000432 if dirname == '..':
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000433 try:
Guido van Rossum2f3941d1997-10-07 14:49:56 +0000434 return self.voidcmd('CDUP')
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000435 except error_perm, msg:
436 if msg[:3] != '500':
437 raise error_perm, msg
438 cmd = 'CWD ' + dirname
Guido van Rossum2f3941d1997-10-07 14:49:56 +0000439 return self.voidcmd(cmd)
Guido van Rossum02cf5821993-05-17 08:00:02 +0000440
Guido van Rossum17ed1ae1993-06-01 13:21:04 +0000441 def size(self, filename):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000442 '''Retrieve the size of a file.'''
443 # Note that the RFC doesn't say anything about 'SIZE'
Guido van Rossum17ed1ae1993-06-01 13:21:04 +0000444 resp = self.sendcmd('SIZE ' + filename)
445 if resp[:3] == '213':
446 return string.atoi(string.strip(resp[3:]))
447
Guido van Rossumc567c601992-11-05 22:22:37 +0000448 def mkd(self, dirname):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000449 '''Make a directory, return its full pathname.'''
Guido van Rossumc567c601992-11-05 22:22:37 +0000450 resp = self.sendcmd('MKD ' + dirname)
451 return parse257(resp)
452
Guido van Rossumc567c601992-11-05 22:22:37 +0000453 def pwd(self):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000454 '''Return current working directory.'''
Guido van Rossumc567c601992-11-05 22:22:37 +0000455 resp = self.sendcmd('PWD')
456 return parse257(resp)
Guido van Rossum1115ab21992-11-04 15:51:30 +0000457
Guido van Rossum1115ab21992-11-04 15:51:30 +0000458 def quit(self):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000459 '''Quit, and close the connection.'''
Guido van Rossum2f3941d1997-10-07 14:49:56 +0000460 resp = self.voidcmd('QUIT')
Guido van Rossum17ed1ae1993-06-01 13:21:04 +0000461 self.close()
Guido van Rossum2f3941d1997-10-07 14:49:56 +0000462 return resp
Guido van Rossum17ed1ae1993-06-01 13:21:04 +0000463
Guido van Rossum17ed1ae1993-06-01 13:21:04 +0000464 def close(self):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000465 '''Close the connection without assuming anything about it.'''
Guido van Rossum1115ab21992-11-04 15:51:30 +0000466 self.file.close()
467 self.sock.close()
Guido van Rossumc567c601992-11-05 22:22:37 +0000468 del self.file, self.sock
469
470
Guido van Rossumacfb82a1997-10-22 20:49:52 +0000471_150_re = None
Fred Drake4de02d91997-01-10 18:26:09 +0000472
473def parse150(resp):
474 '''Parse the '150' response for a RETR request.
475 Returns the expected transfer size or None; size is not guaranteed to
476 be present in the 150 message.
477 '''
478 if resp[:3] != '150':
479 raise error_reply, resp
Guido van Rossumacfb82a1997-10-22 20:49:52 +0000480 global _150_re
481 if _150_re is None:
482 import re
483 _150_re = re.compile("150 .* \(([0-9][0-9]*) bytes\)", re.IGNORECASE)
484 m = _150_re.match(resp)
485 if m:
486 return string.atoi(m.group(1))
Fred Drake4de02d91997-01-10 18:26:09 +0000487 return None
488
489
Guido van Rossumd2560b01996-05-28 23:41:25 +0000490def parse227(resp):
491 '''Parse the '227' response for a PASV request.
492 Raises error_proto if it does not contain '(h1,h2,h3,h4,p1,p2)'
493 Return ('host.addr.as.numbers', port#) tuple.'''
494
495 if resp[:3] <> '227':
496 raise error_reply, resp
497 left = string.find(resp, '(')
498 if left < 0: raise error_proto, resp
499 right = string.find(resp, ')', left + 1)
500 if right < 0:
501 raise error_proto, resp # should contain '(h1,h2,h3,h4,p1,p2)'
502 numbers = string.split(resp[left+1:right], ',')
503 if len(numbers) <> 6:
504 raise error_proto, resp
505 host = string.join(numbers[:4], '.')
506 port = (string.atoi(numbers[4]) << 8) + string.atoi(numbers[5])
507 return host, port
Guido van Rossumd2560b01996-05-28 23:41:25 +0000508
509
Guido van Rossumc567c601992-11-05 22:22:37 +0000510def parse257(resp):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000511 '''Parse the '257' response for a MKD or RMD request.
512 This is a response to a MKD or RMD request: a directory name.
513 Returns the directoryname in the 257 reply.'''
514
Guido van Rossumc567c601992-11-05 22:22:37 +0000515 if resp[:3] <> '257':
516 raise error_reply, resp
517 if resp[3:5] <> ' "':
518 return '' # Not compliant to RFC 959, but UNIX ftpd does this
519 dirname = ''
520 i = 5
521 n = len(resp)
522 while i < n:
523 c = resp[i]
524 i = i+1
525 if c == '"':
526 if i >= n or resp[i] <> '"':
527 break
528 i = i+1
529 dirname = dirname + c
530 return dirname
Guido van Rossum1115ab21992-11-04 15:51:30 +0000531
Guido van Rossum2f3941d1997-10-07 14:49:56 +0000532
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000533def print_line(line):
Guido van Rossumd2560b01996-05-28 23:41:25 +0000534 '''Default retrlines callback to print a line.'''
Guido van Rossumae3b3a31993-11-30 13:43:54 +0000535 print line
536
Guido van Rossum2f3941d1997-10-07 14:49:56 +0000537
Guido van Rossumd2560b01996-05-28 23:41:25 +0000538def ftpcp(source, sourcename, target, targetname = '', type = 'I'):
539 '''Copy file from one FTP-instance to another.'''
540 if not targetname: targetname = sourcename
541 type = 'TYPE ' + type
542 source.voidcmd(type)
543 target.voidcmd(type)
544 sourcehost, sourceport = parse227(source.sendcmd('PASV'))
545 target.sendport(sourcehost, sourceport)
546 # RFC 959: the user must "listen" [...] BEFORE sending the
547 # transfer request.
548 # So: STOR before RETR, because here the target is a "user".
549 treply = target.sendcmd('STOR ' + targetname)
550 if treply[:3] not in ('125', '150'): raise error_proto # RFC 959
551 sreply = source.sendcmd('RETR ' + sourcename)
552 if sreply[:3] not in ('125', '150'): raise error_proto # RFC 959
553 source.voidresp()
554 target.voidresp()
Guido van Rossum1115ab21992-11-04 15:51:30 +0000555
Guido van Rossum56d1e3a1997-03-14 04:16:54 +0000556
Guido van Rossum56d1e3a1997-03-14 04:16:54 +0000557class Netrc:
Fred Drake475d51d1997-06-24 22:02:54 +0000558 """Class to parse & provide access to 'netrc' format files.
559
560 See the netrc(4) man page for information on the file format.
561
562 """
Guido van Rossum56d1e3a1997-03-14 04:16:54 +0000563 __defuser = None
564 __defpasswd = None
565 __defacct = None
566
567 def __init__(self, filename=None):
568 if not filename:
569 if os.environ.has_key("HOME"):
570 filename = os.path.join(os.environ["HOME"], ".netrc")
571 else:
Fred Drake475d51d1997-06-24 22:02:54 +0000572 raise IOError, "specify file to load or set $HOME"
Guido van Rossum56d1e3a1997-03-14 04:16:54 +0000573 self.__hosts = {}
574 self.__macros = {}
575 fp = open(filename, "r")
576 in_macro = 0
577 while 1:
578 line = fp.readline()
579 if not line: break
580 if in_macro and string.strip(line):
581 macro_lines.append(line)
582 continue
583 elif in_macro:
584 self.__macros[macro_name] = tuple(macro_lines)
585 in_macro = 0
586 words = string.split(line)
587 host = user = passwd = acct = None
588 default = 0
589 i = 0
590 while i < len(words):
591 w1 = words[i]
592 if i+1 < len(words):
593 w2 = words[i + 1]
594 else:
595 w2 = None
596 if w1 == 'default':
597 default = 1
598 elif w1 == 'machine' and w2:
599 host = string.lower(w2)
600 i = i + 1
601 elif w1 == 'login' and w2:
602 user = w2
603 i = i + 1
604 elif w1 == 'password' and w2:
605 passwd = w2
606 i = i + 1
607 elif w1 == 'account' and w2:
608 acct = w2
609 i = i + 1
610 elif w1 == 'macdef' and w2:
611 macro_name = w2
612 macro_lines = []
613 in_macro = 1
614 break
615 i = i + 1
616 if default:
617 self.__defuser = user or self.__defuser
618 self.__defpasswd = passwd or self.__defpasswd
619 self.__defacct = acct or self.__defacct
620 if host:
621 if self.__hosts.has_key(host):
622 ouser, opasswd, oacct = self.__hosts[host]
623 user = user or ouser
624 passwd = passwd or opasswd
625 acct = acct or oacct
626 self.__hosts[host] = user, passwd, acct
627 fp.close()
628
629 def get_hosts(self):
630 """Return a list of hosts mentioned in the .netrc file."""
631 return self.__hosts.keys()
632
633 def get_account(self, host):
634 """Returns login information for the named host.
635
636 The return value is a triple containing userid, password, and the
637 accounting field.
638
639 """
640 host = string.lower(host)
Fred Drake475d51d1997-06-24 22:02:54 +0000641 user = passwd = acct = None
Guido van Rossum56d1e3a1997-03-14 04:16:54 +0000642 if self.__hosts.has_key(host):
643 user, passwd, acct = self.__hosts[host]
644 user = user or self.__defuser
645 passwd = passwd or self.__defpasswd
646 acct = acct or self.__defacct
647 return user, passwd, acct
648
649 def get_macros(self):
650 """Return a list of all defined macro names."""
651 return self.__macros.keys()
652
653 def get_macro(self, macro):
654 """Return a sequence of lines which define a named macro."""
655 return self.__macros[macro]
656
Fred Drake475d51d1997-06-24 22:02:54 +0000657
Guido van Rossum56d1e3a1997-03-14 04:16:54 +0000658
Guido van Rossum1115ab21992-11-04 15:51:30 +0000659def test():
Guido van Rossumd2560b01996-05-28 23:41:25 +0000660 '''Test program.
Fred Drake475d51d1997-06-24 22:02:54 +0000661 Usage: ftp [-d] [-r[file]] host [-l[dir]] [-d[dir]] [-p] [file] ...'''
Guido van Rossumd2560b01996-05-28 23:41:25 +0000662
Guido van Rossumb6775db1994-08-01 11:34:53 +0000663 debugging = 0
Fred Drake475d51d1997-06-24 22:02:54 +0000664 rcfile = None
Guido van Rossumb6775db1994-08-01 11:34:53 +0000665 while sys.argv[1] == '-d':
666 debugging = debugging+1
667 del sys.argv[1]
Fred Drake475d51d1997-06-24 22:02:54 +0000668 if sys.argv[1][:2] == '-r':
669 # get name of alternate ~/.netrc file:
670 rcfile = sys.argv[1][2:]
671 del sys.argv[1]
Guido van Rossumb6775db1994-08-01 11:34:53 +0000672 host = sys.argv[1]
673 ftp = FTP(host)
674 ftp.set_debuglevel(debugging)
Fred Drake475d51d1997-06-24 22:02:54 +0000675 userid = passwd = acct = ''
676 try:
677 netrc = Netrc(rcfile)
678 except IOError:
679 if rcfile is not None:
680 sys.stderr.write("Could not open account file"
681 " -- using anonymous login.")
682 else:
683 try:
684 userid, passwd, acct = netrc.get_account(host)
685 except KeyError:
686 # no account for host
687 sys.stderr.write("No account -- using anonymous login.")
688 ftp.login(userid, passwd, acct)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000689 for file in sys.argv[2:]:
690 if file[:2] == '-l':
691 ftp.dir(file[2:])
692 elif file[:2] == '-d':
693 cmd = 'CWD'
694 if file[2:]: cmd = cmd + ' ' + file[2:]
695 resp = ftp.sendcmd(cmd)
Guido van Rossumd2560b01996-05-28 23:41:25 +0000696 elif file == '-p':
697 ftp.set_pasv(not ftp.passiveserver)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000698 else:
699 ftp.retrbinary('RETR ' + file, \
700 sys.stdout.write, 1024)
701 ftp.quit()
Guido van Rossum221ec0b1995-08-04 04:39:30 +0000702
703
704if __name__ == '__main__':
705 test()