Vega strike Python Modules doc  0.5.1
Documentation of the " Modules " folder of Vega strike
 All Data Structures Namespaces Files Functions Variables
FTP Class Reference

Public Member Functions

def __init__
 
def connect
 
def getwelcome
 
def set_debuglevel
 
def set_pasv
 
def sanitize
 
def putline
 
def putcmd
 
def getline
 
def getmultiline
 
def getresp
 
def voidresp
 
def abort
 
def sendcmd
 
def voidcmd
 
def sendport
 
def sendeprt
 
def makeport
 
def makepasv
 
def ntransfercmd
 
def transfercmd
 
def login
 
def retrbinary
 
def retrlines
 
def storbinary
 
def storlines
 
def acct
 
def nlst
 
def dir
 
def rename
 
def delete
 
def cwd
 
def size
 
def mkd
 
def rmd
 
def pwd
 
def quit
 
def close
 

Data Fields

 host
 
 af
 
 debugging
 
 passiveserver
 
 lastresp
 

Static Public Attributes

int debugging = 0
 
string host = ''
 
 port = FTP_PORT
 
 sock = None
 
 file = None
 
 welcome = None
 
int passiveserver = 1
 
 debug = set_debuglevel
 

Detailed Description

An FTP client class.

To create a connection, call the class using these argument:
        host, user, passwd, acct
These are all strings, and have default value ''.
Then use self.connect() with optional host and port argument.

To download a file, use ftp.retrlines('RETR ' + filename),
or ftp.retrbinary() with slightly different arguments.
To upload a file, use ftp.storlines() or ftp.storbinary(),
which have an open file as argument (see their definitions
below for details).
The download/upload functions first issue appropriate TYPE
and PORT or PASV commands.

Definition at line 76 of file ftplib.py.

Constructor & Destructor Documentation

def __init__ (   self,
  host = '',
  user = '',
  passwd = '',
  acct = '' 
)

Definition at line 106 of file ftplib.py.

References FTP.connect(), and FTP.login().

107  def __init__(self, host='', user='', passwd='', acct=''):
108  if host:
109  self.connect(host)
110  if user: self.login(user, passwd, acct)

Member Function Documentation

def abort (   self)
Abort a file transfer.  Uses out-of-band data.
This does not follow the procedure from the RFC to send Telnet
IP and Synch; that doesn't seem to work with the servers I've
tried.  Instead, just send the ABOR command as OOB data.

Definition at line 227 of file ftplib.py.

References FTP.debugging, FTP.getmultiline(), and FTP.sanitize().

228  def abort(self):
229  '''Abort a file transfer. Uses out-of-band data.
230  This does not follow the procedure from the RFC to send Telnet
231  IP and Synch; that doesn't seem to work with the servers I've
232  tried. Instead, just send the ABOR command as OOB data.'''
233  line = 'ABOR' + CRLF
234  if self.debugging > 1: print '*put urgent*', self.sanitize(line)
235  self.sock.sendall(line, MSG_OOB)
236  resp = self.getmultiline()
237  if resp[:3] not in ('426', '226'):
238  raise error_proto, resp
def acct (   self,
  password 
)
Send new account name.

Definition at line 443 of file ftplib.py.

References FTP.voidcmd().

444  def acct(self, password):
445  '''Send new account name.'''
446  cmd = 'ACCT ' + password
447  return self.voidcmd(cmd)
def close (   self)
Close the connection without assuming anything about it.

Definition at line 533 of file ftplib.py.

References Chunk.file, FTP.file, Hook.file, DumbWriter.file, MiniFieldStorage.file, Breakpoint.file, FieldStorage.file, and FTP.sock.

534  def close(self):
535  '''Close the connection without assuming anything about it.'''
536  if self.file:
537  self.file.close()
538  self.sock.close()
539  self.file = self.sock = None
540 
def connect (   self,
  host = '',
  port = 0 
)
Connect to host.  Arguments are:
- host: hostname to connect to (string, default previous host)
- port: port to connect to (integer, default previous port)

Definition at line 111 of file ftplib.py.

112  def connect(self, host = '', port = 0):
113  '''Connect to host. Arguments are:
114  - host: hostname to connect to (string, default previous host)
115  - port: port to connect to (integer, default previous port)'''
116  if host: self.host = host
117  if port: self.port = port
118  msg = "getaddrinfo returns an empty list"
119  for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM):
120  af, socktype, proto, canonname, sa = res
121  try:
122  self.sock = socket.socket(af, socktype, proto)
123  self.sock.connect(sa)
124  except socket.error, msg:
125  if self.sock:
126  self.sock.close()
127  self.sock = None
128  continue
129  break
130  if not self.sock:
131  raise socket.error, msg
132  self.af = af
133  self.file = self.sock.makefile('rb')
134  self.welcome = self.getresp()
135  return self.welcome
def cwd (   self,
  dirname 
)
Change to a directory.

Definition at line 489 of file ftplib.py.

References FTP.voidcmd().

490  def cwd(self, dirname):
491  '''Change to a directory.'''
492  if dirname == '..':
493  try:
494  return self.voidcmd('CDUP')
495  except error_perm, msg:
496  if msg.args[0][:3] != '500':
497  raise
498  elif dirname == '':
499  dirname = '.' # does nothing, but could return error
500  cmd = 'CWD ' + dirname
501  return self.voidcmd(cmd)
def delete (   self,
  filename 
)
Delete a file.

Definition at line 479 of file ftplib.py.

References FTP.sendcmd().

480  def delete(self, filename):
481  '''Delete a file.'''
482  resp = self.sendcmd('DELE ' + filename)
483  if resp[:3] in ('250', '200'):
484  return resp
485  elif resp[:1] == '5':
486  raise error_perm, resp
487  else:
488  raise error_reply, resp
def dir (   self,
  args 
)
List a directory in long form.
By default list current directory to stdout.
Optional last argument is callback function; all
non-empty arguments before it are concatenated to the
LIST command.  (This *should* only be used for a pathname.)

Definition at line 457 of file ftplib.py.

References FTP.retrlines().

458  def dir(self, *args):
459  '''List a directory in long form.
460  By default list current directory to stdout.
461  Optional last argument is callback function; all
462  non-empty arguments before it are concatenated to the
463  LIST command. (This *should* only be used for a pathname.)'''
464  cmd = 'LIST'
465  func = None
466  if args[-1:] and type(args[-1]) != type(''):
467  args, func = args[:-1], args[-1]
468  for arg in args:
469  if arg:
470  cmd = cmd + (' ' + arg)
471  self.retrlines(cmd, func)
def getline (   self)

Definition at line 180 of file ftplib.py.

References FTP.debugging, and FTP.sanitize().

181  def getline(self):
182  line = self.file.readline()
183  if self.debugging > 1:
184  print '*get*', self.sanitize(line)
185  if not line: raise EOFError
186  if line[-2:] == CRLF: line = line[:-2]
187  elif line[-1:] in CRLF: line = line[:-1]
188  return line
def getmultiline (   self)

Definition at line 193 of file ftplib.py.

References FTP.getline().

194  def getmultiline(self):
195  line = self.getline()
196  if line[3:4] == '-':
197  code = line[:3]
198  while 1:
199  nextline = self.getline()
200  line = line + ('\n' + nextline)
201  if nextline[:3] == code and \
202  nextline[3:4] != '-':
203  break
204  return line
def getresp (   self)

Definition at line 207 of file ftplib.py.

References FTP.debugging, FTP.getmultiline(), and FTP.sanitize().

208  def getresp(self):
209  resp = self.getmultiline()
210  if self.debugging: print '*resp*', self.sanitize(resp)
211  self.lastresp = resp[:3]
212  c = resp[:1]
213  if c == '4':
214  raise error_temp, resp
215  if c == '5':
216  raise error_perm, resp
217  if c not in '123':
218  raise error_proto, resp
219  return resp
def getwelcome (   self)
Get the welcome message from the server.
(this is read and squirreled away by connect())

Definition at line 136 of file ftplib.py.

References FTP.debugging, FTP.sanitize(), and FTP.welcome.

137  def getwelcome(self):
138  '''Get the welcome message from the server.
139  (this is read and squirreled away by connect())'''
140  if self.debugging:
141  print '*welcome*', self.sanitize(self.welcome)
142  return self.welcome
def login (   self,
  user = '',
  passwd = '',
  acct = '' 
)
Login, default anonymous.

Definition at line 348 of file ftplib.py.

References socket.getfqdn(), and FTP.sendcmd().

349  def login(self, user = '', passwd = '', acct = ''):
350  '''Login, default anonymous.'''
351  if not user: user = 'anonymous'
352  if not passwd: passwd = ''
353  if not acct: acct = ''
354  if user == 'anonymous' and passwd in ('', '-'):
355  # get fully qualified domain name of local host
356  thishost = socket.getfqdn()
357  try:
358  if os.environ.has_key('LOGNAME'):
359  realuser = os.environ['LOGNAME']
360  elif os.environ.has_key('USER'):
361  realuser = os.environ['USER']
362  else:
363  realuser = 'anonymous'
364  except AttributeError:
365  # Not all systems have os.environ....
366  realuser = 'anonymous'
367  passwd = passwd + realuser + '@' + thishost
368  resp = self.sendcmd('USER ' + user)
369  if resp[0] == '3': resp = self.sendcmd('PASS ' + passwd)
370  if resp[0] == '3': resp = self.sendcmd('ACCT ' + acct)
371  if resp[0] != '2':
372  raise error_reply, resp
373  return resp
def makepasv (   self)

Definition at line 298 of file ftplib.py.

References FTP.af, ftplib.parse227(), ftplib.parse229(), and FTP.sendcmd().

299  def makepasv(self):
300  if self.af == socket.AF_INET:
301  host, port = parse227(self.sendcmd('PASV'))
302  else:
303  host, port = parse229(self.sendcmd('EPSV'), self.sock.getpeername())
304  return host, port
def makeport (   self)
Create a new socket and send a PORT command for it.

Definition at line 272 of file ftplib.py.

References FTP.af, FTP.sendeprt(), FTP.sendport(), and socket.socket().

273  def makeport(self):
274  '''Create a new socket and send a PORT command for it.'''
275  msg = "getaddrinfo returns an empty list"
276  sock = None
277  for res in socket.getaddrinfo(None, 0, self.af, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
278  af, socktype, proto, canonname, sa = res
279  try:
280  sock = socket.socket(af, socktype, proto)
281  sock.bind(sa)
282  except socket.error, msg:
283  if sock:
284  sock.close()
285  sock = None
286  continue
287  break
288  if not sock:
289  raise socket.error, msg
290  sock.listen(1)
291  port = sock.getsockname()[1] # Get proper port
292  host = self.sock.getsockname()[0] # Get proper host
293  if self.af == socket.AF_INET:
294  resp = self.sendport(host, port)
295  else:
296  resp = self.sendeprt(host, port)
297  return sock
def mkd (   self,
  dirname 
)
Make a directory, return its full pathname.

Definition at line 513 of file ftplib.py.

References ftplib.parse257(), and FTP.sendcmd().

514  def mkd(self, dirname):
515  '''Make a directory, return its full pathname.'''
516  resp = self.sendcmd('MKD ' + dirname)
517  return parse257(resp)
def nlst (   self,
  args 
)
Return a list of files in a given directory (default the current).

Definition at line 448 of file ftplib.py.

References FTP.retrlines().

449  def nlst(self, *args):
450  '''Return a list of files in a given directory (default the current).'''
451  cmd = 'NLST'
452  for arg in args:
453  cmd = cmd + (' ' + arg)
454  files = []
455  self.retrlines(cmd, files.append)
456  return files
def ntransfercmd (   self,
  cmd,
  rest = None 
)
Initiate a transfer over the data connection.

If the transfer is active, send a port command and the
transfer command, and accept the connection.  If the server is
passive, send a pasv command, connect to it, and start the
transfer command.  Either way, return the socket for the
connection and the expected size of the transfer.  The
expected size may be None if it could not be determined.

Optional `rest' argument can be a string that is sent as the
argument to a RESTART command.  This is essentially a server
marker used to tell the server to skip over any data up to the
given marker.

Definition at line 305 of file ftplib.py.

References FTP.makepasv(), FTP.makeport(), ftplib.parse150(), FTP.passiveserver, FTP.sendcmd(), and socket.socket().

306  def ntransfercmd(self, cmd, rest=None):
307  """Initiate a transfer over the data connection.
308 
309  If the transfer is active, send a port command and the
310  transfer command, and accept the connection. If the server is
311  passive, send a pasv command, connect to it, and start the
312  transfer command. Either way, return the socket for the
313  connection and the expected size of the transfer. The
314  expected size may be None if it could not be determined.
315 
316  Optional `rest' argument can be a string that is sent as the
317  argument to a RESTART command. This is essentially a server
318  marker used to tell the server to skip over any data up to the
319  given marker.
320  """
321  size = None
322  if self.passiveserver:
323  host, port = self.makepasv()
324  af, socktype, proto, canon, sa = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)[0]
325  conn = socket.socket(af, socktype, proto)
326  conn.connect(sa)
327  if rest is not None:
328  self.sendcmd("REST %s" % rest)
329  resp = self.sendcmd(cmd)
330  if resp[0] != '1':
331  raise error_reply, resp
332  else:
333  sock = self.makeport()
334  if rest is not None:
335  self.sendcmd("REST %s" % rest)
336  resp = self.sendcmd(cmd)
337  if resp[0] != '1':
338  raise error_reply, resp
339  conn, sockaddr = sock.accept()
340  if resp[:3] == '150':
341  # this is conditional in case we received a 125
342  size = parse150(resp)
343  return conn, size
def putcmd (   self,
  line 
)

Definition at line 174 of file ftplib.py.

References FTP.debugging, FTP.putline(), and FTP.sanitize().

175  def putcmd(self, line):
176  if self.debugging: print '*cmd*', self.sanitize(line)
177  self.putline(line)
def putline (   self,
  line 
)

Definition at line 168 of file ftplib.py.

References FTP.debugging, and FTP.sanitize().

169  def putline(self, line):
170  line = line + CRLF
171  if self.debugging > 1: print '*put*', self.sanitize(line)
172  self.sock.sendall(line)
def pwd (   self)
Return current working directory.

Definition at line 522 of file ftplib.py.

References ftplib.parse257(), and FTP.sendcmd().

523  def pwd(self):
524  '''Return current working directory.'''
525  resp = self.sendcmd('PWD')
526  return parse257(resp)
def quit (   self)
Quit, and close the connection.

Definition at line 527 of file ftplib.py.

References Chunk.close(), openrsrc.close(), _Hqxcoderengine.close(), FileInput.close(), _Rlecoderengine.close(), BinHex.close(), _Hqxdecoderengine.close(), Aifc_read.close(), _Rledecoderengine.close(), HexBin.close(), file_wrapper.close(), FTP.close(), and FTP.voidcmd().

528  def quit(self):
529  '''Quit, and close the connection.'''
530  resp = self.voidcmd('QUIT')
531  self.close()
532  return resp
def rename (   self,
  fromname,
  toname 
)
Rename a file.

Definition at line 472 of file ftplib.py.

References FTP.sendcmd(), and FTP.voidcmd().

473  def rename(self, fromname, toname):
474  '''Rename a file.'''
475  resp = self.sendcmd('RNFR ' + fromname)
476  if resp[0] != '3':
477  raise error_reply, resp
478  return self.voidcmd('RNTO ' + toname)
def retrbinary (   self,
  cmd,
  callback,
  blocksize = 8192,
  rest = None 
)
Retrieve data in binary mode.

`cmd' is a RETR command.  `callback' is a callback function is
called for each block.  No more than `blocksize' number of
bytes will be read from the socket.  Optional `rest' is passed
to transfercmd().

A new port is created for you.  Return the response code.

Definition at line 374 of file ftplib.py.

References pydoc.callback, FTP.transfercmd(), FTP.voidcmd(), and FTP.voidresp().

375  def retrbinary(self, cmd, callback, blocksize=8192, rest=None):
376  """Retrieve data in binary mode.
377 
378  `cmd' is a RETR command. `callback' is a callback function is
379  called for each block. No more than `blocksize' number of
380  bytes will be read from the socket. Optional `rest' is passed
381  to transfercmd().
382 
383  A new port is created for you. Return the response code.
384  """
385  self.voidcmd('TYPE I')
386  conn = self.transfercmd(cmd, rest)
387  while 1:
388  data = conn.recv(blocksize)
389  if not data:
390  break
391  callback(data)
392  conn.close()
393  return self.voidresp()
def retrlines (   self,
  cmd,
  callback = None 
)
Retrieve data in line mode.
The argument is a RETR or LIST command.
The callback function (2nd argument) is called for each line,
with trailing CRLF stripped.  This creates a new port for you.
print_line() is the default callback.

Definition at line 394 of file ftplib.py.

References pydoc.callback, FTP.debugging, FTP.sendcmd(), FTP.transfercmd(), and FTP.voidresp().

395  def retrlines(self, cmd, callback = None):
396  '''Retrieve data in line mode.
397  The argument is a RETR or LIST command.
398  The callback function (2nd argument) is called for each line,
399  with trailing CRLF stripped. This creates a new port for you.
400  print_line() is the default callback.'''
401  if not callback: callback = print_line
402  resp = self.sendcmd('TYPE A')
403  conn = self.transfercmd(cmd)
404  fp = conn.makefile('rb')
405  while 1:
406  line = fp.readline()
407  if self.debugging > 2: print '*retr*', `line`
408  if not line:
409  break
410  if line[-2:] == CRLF:
411  line = line[:-2]
412  elif line[-1:] == '\n':
413  line = line[:-1]
414  callback(line)
415  fp.close()
416  conn.close()
417  return self.voidresp()
def rmd (   self,
  dirname 
)
Remove a directory.

Definition at line 518 of file ftplib.py.

References FTP.voidcmd().

519  def rmd(self, dirname):
520  '''Remove a directory.'''
521  return self.voidcmd('RMD ' + dirname)
def sanitize (   self,
  s 
)

Definition at line 159 of file ftplib.py.

160  def sanitize(self, s):
161  if s[:5] == 'pass ' or s[:5] == 'PASS ':
162  i = len(s)
163  while i > 5 and s[i-1] in '\r\n':
164  i = i-1
165  s = s[:5] + '*'*(i-5) + s[i:]
166  return `s`
def sendcmd (   self,
  cmd 
)
Send a command and return the response.

Definition at line 239 of file ftplib.py.

References FTP.getresp(), and FTP.putcmd().

240  def sendcmd(self, cmd):
241  '''Send a command and return the response.'''
242  self.putcmd(cmd)
243  return self.getresp()
def sendeprt (   self,
  host,
  port 
)
Send a EPRT command with the current host and the given port number.

Definition at line 259 of file ftplib.py.

References FTP.af, string.joinfields, and FTP.voidcmd().

260  def sendeprt(self, host, port):
261  '''Send a EPRT command with the current host and the given port number.'''
262  af = 0
263  if self.af == socket.AF_INET:
264  af = 1
265  if self.af == socket.AF_INET6:
266  af = 2
267  if af == 0:
268  raise error_proto, 'unsupported address family'
269  fields = ['', `af`, host, `port`, '']
270  cmd = 'EPRT ' + string.joinfields(fields, '|')
271  return self.voidcmd(cmd)
def sendport (   self,
  host,
  port 
)
Send a PORT command with the current host and the given
port number.

Definition at line 249 of file ftplib.py.

References dospath.join(), and FTP.voidcmd().

250  def sendport(self, host, port):
251  '''Send a PORT command with the current host and the given
252  port number.
253  '''
254  hbytes = host.split('.')
255  pbytes = [`port/256`, `port%256`]
256  bytes = hbytes + pbytes
257  cmd = 'PORT ' + ','.join(bytes)
258  return self.voidcmd(cmd)
def set_debuglevel (   self,
  level 
)
Set the debugging level.
The required argument level means:
0: no debugging output (default)
1: print commands and responses but not body text etc.
2: also print raw lines read and sent before stripping CR/LF

Definition at line 143 of file ftplib.py.

144  def set_debuglevel(self, level):
145  '''Set the debugging level.
146  The required argument level means:
147  0: no debugging output (default)
148  1: print commands and responses but not body text etc.
149  2: also print raw lines read and sent before stripping CR/LF'''
self.debugging = level
def set_pasv (   self,
  val 
)
Use passive or active mode for data transfers.
With a false argument, use the normal PORT mode,
With a true argument, use the PASV command.

Definition at line 152 of file ftplib.py.

153  def set_pasv(self, val):
154  '''Use passive or active mode for data transfers.
155  With a false argument, use the normal PORT mode,
156  With a true argument, use the PASV command.'''
157  self.passiveserver = val
def size (   self,
  filename 
)
Retrieve the size of a file.

Definition at line 502 of file ftplib.py.

References FTP.sendcmd(), and string.strip().

503  def size(self, filename):
504  '''Retrieve the size of a file.'''
505  # Note that the RFC doesn't say anything about 'SIZE'
506  resp = self.sendcmd('SIZE ' + filename)
507  if resp[:3] == '213':
508  s = resp[3:].strip()
509  try:
510  return int(s)
511  except (OverflowError, ValueError):
512  return long(s)
def storbinary (   self,
  cmd,
  fp,
  blocksize = 8192 
)
Store a file in binary mode.

Definition at line 418 of file ftplib.py.

References FTP.transfercmd(), FTP.voidcmd(), and FTP.voidresp().

419  def storbinary(self, cmd, fp, blocksize=8192):
420  '''Store a file in binary mode.'''
421  self.voidcmd('TYPE I')
422  conn = self.transfercmd(cmd)
423  while 1:
424  buf = fp.read(blocksize)
425  if not buf: break
426  conn.sendall(buf)
427  conn.close()
428  return self.voidresp()
def storlines (   self,
  cmd,
  fp 
)
Store a file in line mode.

Definition at line 429 of file ftplib.py.

References FTP.transfercmd(), FTP.voidcmd(), and FTP.voidresp().

430  def storlines(self, cmd, fp):
431  '''Store a file in line mode.'''
432  self.voidcmd('TYPE A')
433  conn = self.transfercmd(cmd)
434  while 1:
435  buf = fp.readline()
436  if not buf: break
437  if buf[-2:] != CRLF:
438  if buf[-1] in CRLF: buf = buf[:-1]
439  buf = buf + CRLF
440  conn.sendall(buf)
441  conn.close()
442  return self.voidresp()
def transfercmd (   self,
  cmd,
  rest = None 
)
Like ntransfercmd() but returns only the socket.

Definition at line 344 of file ftplib.py.

References FTP.ntransfercmd().

345  def transfercmd(self, cmd, rest=None):
346  """Like ntransfercmd() but returns only the socket."""
347  return self.ntransfercmd(cmd, rest)[0]
def voidcmd (   self,
  cmd 
)
Send a command and expect a response beginning with '2'.

Definition at line 244 of file ftplib.py.

References FTP.putcmd(), and FTP.voidresp().

245  def voidcmd(self, cmd):
246  """Send a command and expect a response beginning with '2'."""
247  self.putcmd(cmd)
248  return self.voidresp()
def voidresp (   self)
Expect a response beginning with '2'.

Definition at line 220 of file ftplib.py.

References FTP.getresp().

221  def voidresp(self):
222  """Expect a response beginning with '2'."""
223  resp = self.getresp()
224  if resp[0] != '2':
225  raise error_reply, resp
226  return resp

Field Documentation

af

Definition at line 131 of file ftplib.py.

debug = set_debuglevel
static

Definition at line 150 of file ftplib.py.

int debugging = 0
static

Definition at line 94 of file ftplib.py.

debugging

Definition at line 149 of file ftplib.py.

file = None
static

Definition at line 98 of file ftplib.py.

string host = ''
static

Definition at line 95 of file ftplib.py.

host

Definition at line 115 of file ftplib.py.

lastresp

Definition at line 210 of file ftplib.py.

int passiveserver = 1
static

Definition at line 100 of file ftplib.py.

passiveserver

Definition at line 156 of file ftplib.py.

port = FTP_PORT
static

Definition at line 96 of file ftplib.py.

sock = None
static

Definition at line 97 of file ftplib.py.

welcome = None
static

Definition at line 99 of file ftplib.py.


The documentation for this class was generated from the following file: