/Demo/sockets/ftp.py

http://unladen-swallow.googlecode.com/ · Python · 146 lines · 74 code · 21 blank · 51 comment · 17 complexity · 58f63c7c419acb37e3e81347e3647a32 MD5 · raw file

  1. # A simple FTP client.
  2. #
  3. # The information to write this program was gathered from RFC 959,
  4. # but this is not a complete implementation! Yet it shows how a simple
  5. # FTP client can be built, and you are welcome to extend it to suit
  6. # it to your needs...
  7. #
  8. # How it works (assuming you've read the RFC):
  9. #
  10. # User commands are passed uninterpreted to the server. However, the
  11. # user never needs to send a PORT command. Rather, the client opens a
  12. # port right away and sends the appropriate PORT command to the server.
  13. # When a response code 150 is received, this port is used to receive
  14. # the data (which is written to stdout in this version), and when the
  15. # data is exhausted, a new port is opened and a corresponding PORT
  16. # command sent. In order to avoid errors when reusing ports quickly
  17. # (and because there is no s.getsockname() method in Python yet) we
  18. # cycle through a number of ports in the 50000 range.
  19. import sys, posix, string
  20. from socket import *
  21. BUFSIZE = 1024
  22. # Default port numbers used by the FTP protocol.
  23. #
  24. FTP_PORT = 21
  25. FTP_DATA_PORT = FTP_PORT - 1
  26. # Change the data port to something not needing root permissions.
  27. #
  28. FTP_DATA_PORT = FTP_DATA_PORT + 50000
  29. # Main program (called at the end of this file).
  30. #
  31. def main():
  32. hostname = sys.argv[1]
  33. control(hostname)
  34. # Control process (user interface and user protocol interpreter).
  35. #
  36. def control(hostname):
  37. #
  38. # Create control connection
  39. #
  40. s = socket(AF_INET, SOCK_STREAM)
  41. s.connect((hostname, FTP_PORT))
  42. f = s.makefile('r') # Reading the replies is easier from a file...
  43. #
  44. # Control loop
  45. #
  46. r = None
  47. while 1:
  48. code = getreply(f)
  49. if code in ('221', 'EOF'): break
  50. if code == '150':
  51. getdata(r)
  52. code = getreply(f)
  53. r = None
  54. if not r:
  55. r = newdataport(s, f)
  56. cmd = getcommand()
  57. if not cmd: break
  58. s.send(cmd + '\r\n')
  59. # Create a new data port and send a PORT command to the server for it.
  60. # (Cycle through a number of ports to avoid problems with reusing
  61. # a port within a short time.)
  62. #
  63. nextport = 0
  64. #
  65. def newdataport(s, f):
  66. global nextport
  67. port = nextport + FTP_DATA_PORT
  68. nextport = (nextport+1) % 16
  69. r = socket(AF_INET, SOCK_STREAM)
  70. r.bind((gethostbyname(gethostname()), port))
  71. r.listen(1)
  72. sendportcmd(s, f, port)
  73. return r
  74. # Send an appropriate port command.
  75. #
  76. def sendportcmd(s, f, port):
  77. hostname = gethostname()
  78. hostaddr = gethostbyname(hostname)
  79. hbytes = string.splitfields(hostaddr, '.')
  80. pbytes = [repr(port//256), repr(port%256)]
  81. bytes = hbytes + pbytes
  82. cmd = 'PORT ' + string.joinfields(bytes, ',')
  83. s.send(cmd + '\r\n')
  84. code = getreply(f)
  85. # Process an ftp reply and return the 3-digit reply code (as a string).
  86. # The reply should be a line of text starting with a 3-digit number.
  87. # If the 4th char is '-', it is a multi-line reply and is
  88. # terminate by a line starting with the same 3-digit number.
  89. # Any text while receiving the reply is echoed to the file.
  90. #
  91. def getreply(f):
  92. line = f.readline()
  93. if not line: return 'EOF'
  94. print line,
  95. code = line[:3]
  96. if line[3:4] == '-':
  97. while 1:
  98. line = f.readline()
  99. if not line: break # Really an error
  100. print line,
  101. if line[:3] == code and line[3:4] != '-': break
  102. return code
  103. # Get the data from the data connection.
  104. #
  105. def getdata(r):
  106. print '(accepting data connection)'
  107. conn, host = r.accept()
  108. print '(data connection accepted)'
  109. while 1:
  110. data = conn.recv(BUFSIZE)
  111. if not data: break
  112. sys.stdout.write(data)
  113. print '(end of data connection)'
  114. # Get a command from the user.
  115. #
  116. def getcommand():
  117. try:
  118. while 1:
  119. line = raw_input('ftp.py> ')
  120. if line: return line
  121. except EOFError:
  122. return ''
  123. # Call the main program.
  124. #
  125. main()