What we want to show you in this tip article is how to run a very simple and lightweight web server using only Python as a prerequisite. Use cases can be very different, depending on your needs : you might need web server functionality in your code (e.g. a microservice), you might want to have a browser-based file manager (you will soon see what we mean by that) or you just want to test your web page and/or start learning web development and Apache is a bit much for the task.
Here we can only say "Linux" because, unless you have a very minimal setup, you already have Python installed. This is a guarantee for yum-based distributions as yum is written in Python. If you don’t have Python installed, on Debian-based distributions you can do
$ sudo apt-get install python
If you’re on RHEL-based distributions and don’t already have Python, just type
$ sudo rpm -ivh $python_rpm_package #you won't be able to run dnf/yum without Python, as stated above
3. Checking the Python version you have
The instructions for the web server depend on what Python version you have default (e.g. 2 or 3). This is how you check :
$ python -V
Notice the capitalized v, the non-capitalized option will start a Python console in verbose mode; use ‘quit()’ to exit
4. Python 2.x
The Python module we’re gonna use here is SimpleHTTPServer. By default it starts listening on port 8000, but you can add an argument to specify the port:
$ python -m SimpleHTTPServer 9000
This will start a web server on port 9000, and you can test the success of the operation by accessing localhost:$port (9000 in our case). Another use for this is the fact that you can now access the machine with the web server from anywhere in your LAN (depending on security policies though, mind you) which might prove useful if you want to download files from the desktop to the laptop, for example.
5. Python 3.x
Only the name of the module is different here, because the functionality of SimpleHTTPServer is merged into the Python 3 module, called http.server. So with Python 3, the command becomes
$ python -m http.server 9000
6. Final words
You will notice that we ran the commands as normal user. Why do we need to do something different if we want the web server to run on port 80 is left as an exercise to creative ways or interesting options to use with the concepts above, we’d like to hear them, so write a comment and let us know.
转载本站任何文章请注明：转载至神刀安全网，谢谢神刀安全网 » Running a simple HTTP web server with one terminal command and python