Monday, 5 February 2018

A small HTTP server in Python

The Python http.server module can be run from the commandline with

python3 -m http.server

to provide a simple http server that listens on a configurable port and basically serves any file from the directory it is started from.

That is a good start but I had some additional requirements to serve up files from my raspberry Pi:

  • The server must be able to run as a demonized process, i.e, in the background
  • It must server a limited set of files
  • from a configurable directory and
  • be able to run as a less privileged user
Now of course I could have opted for a light weight http server like nginx or lighttpd, but I decided to write my own so I wouldn't have to install a boatload of additional packages.

restrictedhttpserver.py

The server is based on the daemon module a wrote about in a previous article and can be started from the commandline in much the same way as http.server:


python3 restrictedhttpserver.py


It will run as the user that started it, will listen on port 8000 and start serving any file from the current directory. It will demonize itself as well.

It takes some additional options:

python3 restrictedhttpserver.py -h

usage: restrictedhttpserver.py [-h] [-p PID_FILE] [-l LOG_FILE] [-r ROOT_DIR]
                               [-n NAME] [-u USER] [-f] [-s] [-d]
                               [--bind ADDRESS] [-x] [-e EXT]
                               [port]

Example HTTP Server

positional arguments:
  port                  Specify alternate port [default: 8000]

optional arguments:
  -h, --help            show this help message and exit
  -p PID_FILE, --pid-file PID_FILE
  -l LOG_FILE, --log-file LOG_FILE
  -r ROOT_DIR, --root-dir ROOT_DIR
  -n NAME, --name NAME  name of the server used in log lines
  -u USER, --user USER  drop privileges of running server to those of user
  -f, --force           start a server even if pid file is present already
  -s, --stop            stop a running server
  -d, --debug           Run http server in foreground mode
  --bind ADDRESS, -b ADDRESS
                        Specify alternate bind address [default: all
                        interfaces]
  -x, --nodirlist       never show a directory listing
  -e EXT, --ext EXT     allowed file extensions (without .) May occur more
                        than once
For example if you wanted to run it as user www from the directory /public/www and just server html and css files, you could run it (as root) as follows:

python3 restrictedhttpserver.py -r /public/www -u www -e html -e css

Later you could stop this process by executing
python3 retrictedhttpserver.py -s


For more information have a look at the source code, it is pretty readable I think :-)

Availability

restrictedhttpserver.py and daemon.py are both available from this GitHub repository.

57 comments:

  1. Replies
    1. I am glad that I saw this post. It is informative blog for us and we need this type of blog thanks for share this blog, Keep posting such instructional blogs and I am looking forward for your future posts. Python Projects for Students Data analytics is the study of dissecting crude data so as to make decisions about that data. Data analytics advances and procedures are generally utilized in business ventures to empower associations to settle on progressively Python Training in Chennai educated business choices. In the present worldwide commercial center, it isn't sufficient to assemble data and do the math; you should realize how to apply that data to genuine situations such that will affect conduct. In the program you will initially gain proficiency with the specialized skills, including R and Python dialects most usually utilized in data analytics programming and usage; Python Training in Chennai at that point center around the commonsense application, in view of genuine business issues in a scope of industry segments, for example, wellbeing, promoting and account. Project Center in Chennai

      Delete
  2. ExcelR Offers Business Analytics / Data Scientist Course / Data Analytics Training & Data Science Course Training In Bangalore, With 100% Placement.
    https://www.excelr.com/business-analytics-training-in-bangalore/

    ReplyDelete
  3. Nice blog..! I really loved reading through this article. Thanks for sharing such a amazing post with us and keep blogging... best angularjs training institute in chennai | angularjs training in omr | angularjs training in chennai | angularjs training in velachery |

    ReplyDelete
  4. Good blog posts information provided
    Best Play and Pre School for kids in Hyderabad,India. To give your kid a best environment and learning it is the right way to join in play and pre school were kids can build there physically, emotionally and mentally skills developed. We provide programs to kids like Play Group, Nursery, Sanjary Junior, Sanjary Senior and Teacher training Program.
    Preschool in hyderabad

    ReplyDelete
  5. Excellent explanation by the author

    Sanjary Academy is the best Piping Design institute in Hyderabad, Telangana. It is the best Piping design Course in India and we have offer professional Engineering Courses like Piping design Course, QA/QC Course, document controller course, Pressure Vessel Design Course, Welding Inspector Course, Quality Management Course and Safety Officer Course.
    Piping Design Course

    ReplyDelete
  6. Thanks for providing the updated information

    Pressure Vessel Design Course is one of the courses offered by Sanjary Academy in Hyderabad. We have offer professional Engineering Course like Piping Design Course,QA / QC Course,document Controller course,pressure Vessel Design Course,Welding Inspector Course, Quality Management Course, #Safety officer course.
    Welding Inspector Course
    Safety officer course
    Quality Management Course
    Quality Management Course in India

    ReplyDelete
  7. Great blog article informative I liked it

    Best QA / QC Course in India, Hyderabad. sanjaryacademy is a well-known institute. We have offer professional Engineering Course like Piping Design Course, QA / QC Course,document Controller course,pressure Vessel Design Course, Welding Inspector Course, Quality Management Course, #Safety officer course.
    QA / QC Course
    QA / QC Course in India
    QA / QC Course in Hyderabad

    ReplyDelete
  8. In the competitive market finding the best outsourcing services is a challenging task. This post helps me to find the best one. Thanks for sharing this post.
    Hire Magento developer India
    Hire wordpress developer India
    Hire a Programmer
    Hire PHP Developer India
    Hire Dedicated Programmers
    Mobile App Development India
    Hire Opencart Developer

    ReplyDelete
  9. I just loved your article on the beginners guide to starting a blog.If somebody take this blog article seriously in their life, he/she can earn his living by doing blogging.thank you for thizs article. pega online training , best pega online training ,
    top pega online training

    ReplyDelete
  10. Thanks for sharing such a great information. Its really nice and informative chef training videos and chef devops training

    ReplyDelete
  11. Wow. That is so elegant and logical and clearly explained. Brilliantly goes through what could be a complex process and makes it obvious Python Training.

    ReplyDelete

  12. Thank you for taking the time to provide us with your valuable information. We strive to provide our candidates with excellent care
    http://chennaitraining.in/creo-training-in-chennai/
    http://chennaitraining.in/building-estimation-and-costing-training-in-chennai/
    http://chennaitraining.in/machine-learning-training-in-chennai/
    http://chennaitraining.in/data-science-training-in-chennai/
    http://chennaitraining.in/rpa-training-in-chennai/
    http://chennaitraining.in/blueprism-training-in-chennai/

    ReplyDelete

  13. This is most informative and also this post most user friendly and super navigation to all posts. Thank you so much for giving this information to me. Python training in Chennai.

    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

    ReplyDelete
  14. Really amazing experience to visit your blog, thanks a lot for sharing with us. Visit Ogen Infosystem for creative website designing and ppc services at best price in Delhi.
    PPC Company in Delhi

    ReplyDelete
  15. Decent article, thankful for more information Activated carbon manufacturers in tamilnadu The information you gave about has been valuable while analyzing the subject.Activated carbon manufacturing companies in India

    ReplyDelete
  16. The article unambiguously indicated every one of the positive and negative sides of the issue I'm exceptionally bewildered with the nature of the substance which you have written down. This is a marvelous article! Your article has all the essential data on the individual theme branding companies in chennai

    ReplyDelete
  17. Water bodies are the main source of transportation for international freight forwarding. Due to this, sea freight company in Delhi,
    visit
    Freight Forwarder in Vietnam
    Shipping Company In India

    ReplyDelete
  18. Extraordinary Blog...The information you shared is amazingly, It is all around wrote and simple to undertand and social media marketing agency in chennai you have good thoughts to share something like this a debt of gratitude is in order for share this information.

    ReplyDelete
  19. Decent article, thankful for more information, the information you gave about has been valuable while analyzing the subject.Activated carbon manufacturing companies in India

    ReplyDelete
  20. Nice post shared! I like your content. Really it was so awesome article. Thanks for sharing nice information. Top 10 Makeup Artists in Kolkata

    ReplyDelete
  21. Due to the rising demand for Data Scientists, there are many educational platforms that are coming up with programs in Data Science, you may never find the best, but you can always find the one that is suitable for you.

    Data Science Training in Gurgaon

    ReplyDelete
  22. Compre documentos en línea, documentos originales y registrados.
    Acerca de Permisodeespana, algunos dicen que somos los solucionadores de problemas, mientras que otros se refieren a nosotros como vendedores de soluciones. Contamos con cientos de clientes satisfechos a nivel mundial. Hacemos documentos falsos autorizados y aprobados como Permiso de Residencia Español, DNI, Pasaporte Español y Licencia de Conducir Española. Somos los fabricantes y proveedores de primer nivel de estos documentos, reconocidos a nivel mundial.

    Comprar permiso de residencia,
    permiso de residenciareal y falso en línea,
    Compre licencia de conducir en línea,
    Compre una licencia de conducir española falsa en línea,
    Comprar tarjeta de identificación,
    Licencia de conducir real y falsa,
    Compre pasaporte real en línea,

    Visit Here fpr more information. :- https://permisodeespana.com/licencia-de-conducir-espanola/
    Address: 56 Guild Street, London, EC4A 3WU (UK)
    Email: contact@permisodeespana.com
    WhatsApp: +443455280186

    ReplyDelete
  23. Plumbing & HVAC Services San Diego
    Air Star Heating guarantees reliability and quality for all equipment and services
    Air Star Heating is specializing in providing top-quality heating, ventilating, air conditioning, and plumbing services to our customers and clients.
    Our company is leading the market right now. By using our seamless and huge array of services. Our customers can now have the privilege of taking benefit from our services very easily and swiftly. To cope up with the desires and needs of our clients we have built an excellent reputation. We are already having a huge list of satisfied customers that seem to be very pleased with our services.

    Plumbing & HVAC Services in San Diego. Call now (858) 900-9977 ✓Licensed & Insured ✓Certified Experts ✓Same Day Appointment ✓Original Parts Only ✓Warranty On Every Job.
    Visit:- https://airstarheating.com

    ReplyDelete
  24. I have been working in this industry for many years and have spoken to many students. In my opinion, iClass Gyansetu is the best institute for Selenium Training in Gurgaon

    ReplyDelete
  25. This site helps to clear your all query.
    This is really worth reading. nice informative article.
    vikram university ba 2nd year result
    vikram university ba 3rd year result

    ReplyDelete