Serveur HTTP Python en une ligne..

avril 24th, 2009
|

Un « irc friend » – fo0 en l’occurrence – m’as demandé récemment comment comment créer un petit serveur web en python, rapidement pour pouvoir partager ponctuellement des fichiers & tester du dev. Et bien c’est faisable en une courte ligne:

1
python -c 'import SimpleHTTPServer;SimpleHTTPServer.test()'

Ca lance un petit serveur http sur le port 8000, partageant les fichiers du répertoire courant. Pointez vôtre navigateur sur http://127.0.0.1:8000/ et vous servira le fichier index.html si il existe, sinon il listera le répertoire courant. Et il bavera toutes les infos sur le stdout, exemple:

1
2
3
4
5
$ python -c 'import SimpleHTTPServer;SimpleHTTPServer.test()'
Serving HTTP on 0.0.0.0 port 8000 ...
localhost - - [25/Apr/2009 00:01:27] "GET / HTTP/1.1" 200 -
localhost - - [25/Apr/2009 00:01:38] "GET /Documents/ HTTP/1.1" 200 -
localhost - - [25/Apr/2009 00:01:44] "GET /Documents/test.txt HTTP/1.1" 200 -

De plus il est « chrooté » au répertoire dans lequel vous l’aurez lancé – essayer d’accéder a http://127.0.0.1:8000/../ vous laissera dans le répertoire courant.

Voilà pour la petite astuce du soir..

Maj du 29 Avril 2009: Vu sur http://www.tux-planet.fr, une version encore plus simple:

1
python -m SimpleHTTPServer

Maj du 04 Mai 2009: Voici une version multithreadé et pas beaucoup plus compliquée:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import SocketServer
import BaseHTTPServer
import sys, os
import CGIHTTPServer
port = 8000
class ThreadingCGIServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
    pass
server = ThreadingCGIServer(('', port), CGIHTTPServer.CGIHTTPRequestHandler)
print "Serveur demarre sur le port %s." % port
try:
    while 1:
        sys.stdout.flush()
        server.handle_request()
except KeyboardInterrupt:
    print "Fini !"

3 Comments:

  1. Merci. Trés utiles, à avoir dans un coin du /home ou sur une usb-key :)

  2. Pingback: Tips: Serveur web d’urgence avec Netcat | Debian or not to be ? 2.0

  3. oui très sympa comme astuce, merci :)

Leave a comment: