Small script that will wait for a TCP connection and respond with the contents of the configured directory.

ls_echo.rb 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #!/usr/bin/ruby
  2. # Copyright (c) 2013, Lily Carpenter
  3. # All rights reserved.
  4. # Redistribution and use in source and binary forms, with or without modification,
  5. # are permitted provided that the following conditions are met:
  6. # * Redistributions of source code must retain the above copyright notice, this
  7. # list of conditions and the following disclaimer.
  8. # * Redistributions in binary form must reproduce the above copyright notice, this
  9. # list of conditions and the following disclaimer in the documentation and/or
  10. # other materials provided with the distribution.
  11. # * Neither the name of the Lily Carpenter nor the names of its
  12. # contributors may be used to endorse or promote products derived from
  13. # this software without specific prior written permission.
  14. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  15. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  16. # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  17. # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
  18. # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  19. # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  20. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  21. # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  22. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  23. # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  24. split_version = RUBY_VERSION.split(".")
  25. if split_version[0] != "1" or split_version[1] != "9"
  26. raise(RuntimeError, "Ruby 1.9.x required, but ruby #{RUBY_VERSION} used")
  27. end
  28. usage = "./ls_echo.rb <port> <directory>"
  29. if ARGV.length != 2
  30. puts(usage)
  31. exit 1
  32. end
  33. require 'socket'
  34. require 'pathname'
  35. PORT = ARGV[0]
  36. DIRECTORY = ARGV[1]
  37. # Check arguments
  38. port = Integer(PORT)
  39. directory = Pathname.new(DIRECTORY).expand_path
  40. if not directory.directory?
  41. raise ArgumentError, "Path #{DIRECTORY} does not represent a valid directory."
  42. end
  43. server = TCPServer.new port
  44. fork do
  45. Process.daemon
  46. loop do
  47. Thread.start(server.accept) do |client|
  48. dirs = directory.children.select { |c| c.directory? }\
  49. .collect { |p| p.to_s }
  50. client.puts dirs.join("\n")
  51. client.close
  52. end
  53. end
  54. end