Junio 20, 2018, 07:10:04 am

Autor Tema: Subir y bajar archivos desde un browser  (Leído 2140 veces)

0 Usuarios y 1 Visitante están viendo este tema.

Desconectado Avoidance25

  • Colaborador
  • ****
  • Mensajes: 1248
  • Sexo: Masculino
  • Da gehört eiskrem aber nicht hin xD
    • Ver Perfil
    • sytes
Subir y bajar archivos desde un browser
« en: ſeptiembre 12, 2013, 09:45:06 pm »
<EDIT 7-11-2013>
Agrego una version mas reciente.
</EDIT>

Para darle buen uso a mi raspberry pi, decidi usarla como una cloud. Para ello el script que posteo a continuacion. Una vez ejecutado, si se accede a la direccion de la pc en la que se ejecuta, permite subir y bajar archivos.

Se ve asi: You are not allowed to view links. Register or Login (a no ser que no-ip me vuelva a dar problemas).
No tiene (aun) un sistema de log-in, y la seguridad probablemente es practicamente inexistente, asi que por favor no hackeen.

Código: (python) You are not allowed to view links. Register or Login
#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from os import curdir, listdir, makedirs, chdir
from os.path import isfile, join, exists
import cgi, re

PORT_NUMBER = 80

def list_dir(path, htmlpath, wfile):
    wfile.write("<ol class='no_image_list'>")
    for thing in listdir(path):
        if isfile(join(path, thing)):
            wfile.write("<li><a href='"+htmlpath+"/"+thing+"'>"+thing+"</a></li>")
    for thing in listdir(path):
        if not isfile(join(path, thing)):
            wfile.write("<li><font color=red size=4pt>"+thing+"</font>\
            <button type='button' onclick='show_file_spoiler_hide_folder_spoiler();set_file_path_value(\""+htmlpath+"/"+thing+"\")'>add file</button>\
            <button type='button' onclick='show_folder_spoiler_hide_file_spoiler();set_folder_path_value(\""+htmlpath+"/"+thing+"\")'>add_folder</button></li>")
            list_dir(join(path, thing), htmlpath+"/"+thing, wfile)
    wfile.write("</ol>")

def check_string(string):
    valid_chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.-_!$&/\\=[]()@#"
    return all(c in valid_chars for c in string)

class myHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path=="/favicon.ico":
            try:
                f = open("icon.ico", "rb")
                self.send_response(200)
                self.send_header('Content-type',"image/x-icon")
                self.end_headers()
                self.wfile.write(f.read())
                f.close()
            except IOError as e:
                print "An error ocurred while sending the icon."
                print str(e)
        elif self.path=="/" or self.path=="/index.html":
            self.send_response(200)
            self.send_header('Content-type',"text/html")
            self.end_headers()
            page_start="""
<html><head><title>Enjoy your stay</title><style>
body{background-color:#b0c4de;}
ol.no_image_list {list-style-type:none;}

</style></head><body>
"""
            page_end="""
<div id='file_spoiler' style='display:none'>
<form action="/add_file" method=POST ENCTYPE=multipart/form-data>
    File Path: <input type='text' name='file_path' id='file_path_id' readonly><br>
    <input type=file name=upfile><br><input type=submit value=Submit>
    <input type="hidden" name="add_what" value="file">
</form></div>
<div id='folder_spoiler' style='display:none'>
<form action="/add_folder" method=POST>
    Folder Path: <input type='text' name='folder_path' id='folder_path_id' readonly><br>
    Folder Name: <input type='text' name='folder_name'><br>
    <input type=submit value=Submit>
    <input type="hidden" name="add_what" value="folder">
</form></div>
</body></html>
<script>function show_file_spoiler_hide_folder_spoiler(){document.getElementById('file_spoiler').style.display='';document.getElementById('folder_spoiler').style.display='none'}</script>
<script>function show_folder_spoiler_hide_file_spoiler(){document.getElementById('file_spoiler').style.display='none';document.getElementById('folder_spoiler').style.display=''}</script>
<script>function set_file_path_value(variable){document.getElementById("file_path_id").value=variable}</script>
<script>function set_folder_path_value(variable){document.getElementById("folder_path_id").value=variable}</script>
"""
            self.wfile.write(page_start)
            list_dir("./files", "/files", self.wfile)
            self.wfile.write(page_end)
        elif self.path.startswith("/files/") and self.path.find("..")<0:
            try:
                f = open(curdir + "/" + self.path, "rb")
                self.send_response(200)
                self.send_header('Content-type',"application/data")
                self.end_headers()
                self.wfile.write(f.read())
                f.close()
            except IOError as e:
                print "An error ocurred while sending a file."
                print str(e)



    def do_POST(self):
        if self.path=="/add_folder":
            form = cgi.FieldStorage(
                fp=self.rfile,
                headers=self.headers,
                environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['Content-Type'],})
            try:
                full_name="."+form["folder_path"].value+"/"+form["folder_name"].value
                if "/" in form["folder_name"].value or "\\" in form["folder_name"].value: raise Exception("/ in name")
                if not check_string(full_name): raise Exception("weird chars in name")
                if not exists(full_name):
                    makedirs(full_name)
                    self.send_response(200)
                    self.send_header('Content-type',"text/html")
                    self.end_headers()
                    self.wfile.write("<html><head><meta http-equiv='refresh' content='2;url=/'/><title>Folder Created</title></head><body>The folder was succesfully created. Redirectiong ...(<a href=\"/\">Go back NOW !</a>)</body></html>")
                else:
                    self.send_response(200)
                    self.send_header('Content-type',"text/html")
                    self.end_headers()
                    self.wfile.write("<html><head><title>No Folder Created</title></head><body>A folder or file with that name already exists. <a href=\"/\">Go back.</a></body></html>")
            except Exception as e:
                print e
                self.send_response(200)
                self.send_header('Content-type',"text/html")
                self.end_headers()
                self.wfile.write("<html><head><meta http-equiv='refresh' content='5;url=/'/><title>Some error</title></head><body>Some error occurred, redirecting...</body></html>")
        elif self.path=="/add_file":
            form = cgi.FieldStorage(
                fp=self.rfile,
                headers=self.headers,
                environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['Content-Type'],})
            try:
                full_name="."+form["file_path"].value+"/"+form['upfile'].filename
                if "/" in form['upfile'].filename or "\\" in form['upfile'].filename: raise Exception("/ in name")
                if not check_string(full_name): raise Exception("weird chars in name")
                if not exists(full_name):
                    # makedirs("."+form["folder_path"].value+"/"+form["folder_name"].value)
                    with open(full_name, 'wb') as fp:
                        while True:
                            chunk = form['upfile'].file.read(8192)
                            if len(chunk) == 0: break
                            fp.write(chunk)
                    self.send_response(200)
                    self.send_header('Content-type',"text/html")
                    self.end_headers()
                    self.wfile.write("<html><head><meta http-equiv='refresh' content='2;url=/'/><title>File Added</title></head><body>The file was succesfully created. Redirectiong ... (<a href=\"/\">Go back NOW !</a>)</body></html>")
                else:
                    self.send_response(200)
                    self.send_header('Content-type',"text/html")
                    self.end_headers()
                    self.wfile.write("<html><head><title>No File Added</title></head><body>A folder or file with that name already exists. <a href=\"/\">Go back.</a></body></html>")
            except Exception as e:
                print e
                self.send_response(200)
                self.send_header('Content-type',"text/html")
                self.end_headers()
                self.wfile.write("<html><head><meta http-equiv='refresh' content='5;url=/'/><title>Some error</title></head><body>Some error occurred, redirecting...</body></html>")
        return           
           
           
try:
    # chdir("/media/pendrive/file_server")
    server = HTTPServer(('', PORT_NUMBER), myHandler)
    print 'Started httpserver on port ' , PORT_NUMBER
   
    server.serve_forever()

except KeyboardInterrupt:
    print 'Shutting down the web server'
    server.socket.close()
   

ver 7-11-2013
Código: You are not allowed to view links. Register or Login
#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from SocketServer import ThreadingMixIn
from os import listdir, makedirs, chdir
from os.path import isfile, join, exists
import cgi, sys, threading, traceback

std_lock=threading.Lock()

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    def handle_error(self, request, client_address):#override
        with std_lock:
            sys.stderr.write('-'*40)
            sys.stderr.write('Exception happened during processing of request from')
            sys.stderr.write(str(client_address))
            traceback.print_exc()
            sys.stderr.write('-'*40+"\n\n")
        sys.stderr.flush()

PORT_NUMBER = 80
this_dir="/media/pendrive/file_server"
stdout_file="server_stdout.txt"
stderr_file="server_stderr.txt"

def list_dir(path, htmlpath, wfile):
    wfile.write("<ol class='no_image_list'>")
    for thing in listdir(path):
        if isfile(join(path, thing)):
            wfile.write("<li><a href='"+htmlpath+"/"+thing+"'>"+thing+"</a></li>")
    for thing in listdir(path):
        if not isfile(join(path, thing)):
            wfile.write("<li><font color=red size=4pt>"+thing+"</font>\
            <button type='button' onclick='show_file_spoiler_hide_folder_spoiler();set_file_path_value(\""+htmlpath+"/"+thing+"\")'>add file</button>\
            <button type='button' onclick='show_folder_spoiler_hide_file_spoiler();set_folder_path_value(\""+htmlpath+"/"+thing+"\")'>add_folder</button></li>")
            list_dir(join(path, thing), htmlpath+"/"+thing, wfile)
    wfile.write("</ol>")

def check_string(string):
    valid_chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.-_!$&/\\=[]()@#+"
    if not all(c in valid_chars for c in string): return False
    if "\\\\" in string or "//" in string or ".." in string: return False
    return True

class myHandler(BaseHTTPRequestHandler):
    def log_message(self, format, *args):#override
        with std_lock:
            sys.stdout.write("%s(%s) - - [%s] %s\n" %
                             (self.client_address[0],
                              self.address_string(),
                              self.log_date_time_string(),
                              format%args))
        sys.stdout.flush()
       
    def send_error_page(self):
        self.send_response(200)
        self.send_header('Content-type',"text/html")
        self.end_headers()
        self.wfile.write("<html><head><meta http-equiv='refresh' content='5;url=/'/><title>Some error</title></head><body>Some error occurred, redirecting...</body></html>")
   
    def my_log_error(self, error_string):
        with std_lock:
            sys.stderr.write('-'*40)
            sys.stderr.write('Exception happened during processing of request from')
            sys.stderr.write(str(self.client_address))
            sys.stderr.write("\n")
            sys.stderr.write(error_string)
            sys.stderr.write("\n"+'-'*40+"\n\n")
        sys.stderr.flush()
       
    def do_GET(self):
        # with log_file_lock:
            # with open(log_file, "a") as f:
                # f.write(self.log_date_time_string()+"\n")
                # f.write(self.address_string()+"\n")
                # f.write("client_address: "+str(self.client_address)+"\n")
                # f.write("command: "+str(self.command)+"\n")
                # f.write("path: "+str(self.path)+"\n")
                # f.write("request_version: "+str(self.request_version)+"\n")
                # f.write("<content>"+self.raw_requestline.strip()+"</content>\n")
                # f.write("\n\n")
                # sys.stdout.flush()
                # sys.stderr.flush()
               
        if self.path=="/favicon.ico":
            try:
                f = open("icon.ico", "rb")
                self.send_response(200)
                self.send_header('Content-type',"image/x-icon")
                self.end_headers()
                self.wfile.write(f.read())
                f.close()
            except IOError as e:
                self.my_log_error("An error occurred while sending the icon.\n"+str(e))
        elif self.path=="/" or self.path=="/index.html":
            self.send_response(200)
            self.send_header('Content-type',"text/html")
            self.end_headers()
            page_start="""
<html><head><title>Enjoy your stay</title><style>
body{background-color:#b0c4de;}
ol.no_image_list {list-style-type:none;}

</style></head><body>
"""
            page_end="""
<div id='file_spoiler' style='display:none'>
<form action="/add_file" method=POST ENCTYPE=multipart/form-data>
    File Path: <input type='text' name='file_path' id='file_path_id' readonly><br>
    <input type=file name=upfile><br><input type=submit value=Submit>
    <input type="hidden" name="add_what" value="file">
</form></div>
<div id='folder_spoiler' style='display:none'>
<form action="/add_folder" method=POST>
    Folder Path: <input type='text' name='folder_path' id='folder_path_id' readonly><br>
    Folder Name: <input type='text' name='folder_name'><br>
    <input type=submit value=Submit>
    <input type="hidden" name="add_what" value="folder">
</form></div>
</body></html>
<script>function show_file_spoiler_hide_folder_spoiler(){document.getElementById('file_spoiler').style.display='';document.getElementById('folder_spoiler').style.display='none'}</script>
<script>function show_folder_spoiler_hide_file_spoiler(){document.getElementById('file_spoiler').style.display='none';document.getElementById('folder_spoiler').style.display=''}</script>
<script>function set_file_path_value(variable){document.getElementById("file_path_id").value=variable}</script>
<script>function set_folder_path_value(variable){document.getElementById("folder_path_id").value=variable}</script>
"""
            self.wfile.write(page_start)
            list_dir("./files", "files", self.wfile)
            self.wfile.write(page_end)
        elif self.path.startswith("/files/") and not ".." in self.path:
            try:
                f = open(join(this_dir,self.path[1:]), "rb")
                self.send_response(200)
                self.send_header('Content-type',"application/data")
                self.end_headers()
                self.wfile.write(f.read())
                f.close()
            except IOError as e:
                self.my_log_error("An error occurred while sending a file.\n"+str(e))
                self.send_error_page()
        else:
            self.my_log_error("Invalid path requested (GET) ("+self.path+").")
            self.send_error_page()



    def do_POST(self):
        # with log_file_lock:
            # with open(log_file, "a") as f:
                # f.write(self.log_date_time_string()+"\n")
                # f.write(self.address_string()+"\n")
                # f.write("client_address: "+str(self.client_address)+"\n")
                # f.write("command: "+str(self.command)+"\n")
                # f.write("path: "+str(self.path)+"\n")
                # f.write("request_version: "+str(self.request_version)+"\n")
                # f.write("<content>"+self.raw_requestline.strip()+"</content>\n")
                # f.write("\n\n")
                # sys.stdout.flush()
                # sys.stderr.flush()
               
        if self.path=="/add_folder":
            form = cgi.FieldStorage(
                fp=self.rfile,
                headers=self.headers,
                environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['Content-Type'],})
            try:
                if "/" in form["folder_name"].value or "\\" in form["folder_name"].value: raise Exception("/ in name")
                full_path=join(join(this_dir,form["folder_path"].value),form["folder_name"].value)
                if not check_string(full_path): raise Exception("weird chars in path")
               
                if not exists(full_path):
                    makedirs(full_path)
                    self.send_response(200)
                    self.send_header('Content-type',"text/html")
                    self.end_headers()
                    self.wfile.write("<html><head><meta http-equiv='refresh' content='2;url=/'/><title>Folder Created</title></head><body>The folder was succesfully created. Redirectiong ...(<a href=\"/\">Go back NOW !</a>)</body></html>")
                else:
                    self.send_response(200)
                    self.send_header('Content-type',"text/html")
                    self.end_headers()
                    self.wfile.write("<html><head><title>No Folder Created</title></head><body>A folder or file with that name already exists. <a href=\"/\">Go back.</a></body></html>")
            except Exception as e:
                self.my_log_error("An error occurred while adding a folder.\n"+str(e))
                self.send_error_page()
            except TypeError as e:
                self.my_log_error("An error occurred while getting a post variable for adding folder.\n"+str(e))
                self.send_error_page()
            except KeyError as e:
                self.my_log_error("An error occurred while getting a post variable for adding folder.\n"+str(e))
                self.send_error_page()
            except:
                self.my_log_error("An error occurred while adding a folder.")
                self.send_error_page()
        elif self.path=="/add_file":
            form = cgi.FieldStorage(
                fp=self.rfile,
                headers=self.headers,
                environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['Content-Type'],})
            try:
                if "/" in form['upfile'].filename or "\\" in form['upfile'].filename: raise Exception("/ in name")
                full_path=join(join(this_dir,form["file_path"].value),form['upfile'].filename)
                if not check_string(full_path): raise Exception("weird chars in path")
               
                if not exists(full_path):
                    # makedirs("."+form["folder_path"].value+"/"+form["folder_name"].value)
                    with open(full_path, 'wb') as fp:
                        while True:
                            chunk = form['upfile'].file.read(8192)
                            if len(chunk) == 0: break
                            fp.write(chunk)
                    self.send_response(200)
                    self.send_header('Content-type',"text/html")
                    self.end_headers()
                    self.wfile.write("<html><head><meta http-equiv='refresh' content='2;url=/'/><title>File Added</title></head><body>The file was succesfully created. Redirectiong ... (<a href=\"/\">Go back NOW !</a>)</body></html>")
                else:
                    self.send_response(200)
                    self.send_header('Content-type',"text/html")
                    self.end_headers()
                    self.wfile.write("<html><head><title>No File Added</title></head><body>A folder or file with that name already exists. <a href=\"/\">Go back.</a></body></html>")
            except Exception as e:
                self.my_log_error("An error occurred while adding a file.\n"+str(e))
                self.send_error_page()
            except TypeError as e:
                self.my_log_error("An error occurred while getting a post variable for adding file.\n"+str(e))
                self.send_error_page()
            except KeyError as e:
                self.my_log_error("An error occurred while getting a post variable for adding file.\n"+str(e))
                self.send_error_page()
            except:
                self.my_log_error("An error occurred while adding a file.")
                self.send_error_page()
        else:
            self.my_log_error("Invalid path requested (POST) ("+self.path+").")
            self.send_error_page()
           


server = None           
try:
    chdir(this_dir)
    sys.stdout = open(stdout_file, "a")
    sys.stderr = open(stderr_file, "a")
    server = ThreadedHTTPServer(('', PORT_NUMBER), myHandler)
    print 'Started httpserver on port ' , PORT_NUMBER
    server.serve_forever()
    print 'serve_forever stopped'
except KeyboardInterrupt:
    print '^C received, shutting down the web server'
except:
    sys.stderr.write('some other exception')
finally:
    if server is not None: server.socket.close()
    sys.stdout.flush()
    sys.stderr.flush()
   
   

Código: You are not allowed to view links. Register or Login
#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from SocketServer import ThreadingMixIn
from os import listdir, makedirs, chdir
from os.path import isfile, join, exists, isdir
import cgi, sys, threading, traceback

folder_page_start="""
<html>
<head>
<title>Browsing files ...</title>
<style>
body{ background-color:black; }

a:link {color:#00FF00;text-decoration:none;}
a:visited {color:#00FF00;text-decoration:none;}
a:hover {color:#FF0000;text-decoration:none;}
//a:active {color:#0000FF;text-decoration:none;}

div.box_div{
border:1px dashed #000066;
width:640px;
padding:3px;
padding-bottom:5px;
//margin:0px;
}

div.folder_content{
margin-top:100px;
margin-left:50px;
}

form{
float: right;
}

</style>
</head>

<body>
"""

folder_page_end="""
</body>
</html>
"""



PORT_NUMBER = 80
this_dir="/media/pendrive/file_server"
stdout_file="server_stdout.txt"
stderr_file="server_stderr.txt"

std_lock=threading.Lock()
file_or_folder_add_lock=threading.Lock()

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    def handle_error(self, request, client_address):#override
        with std_lock:
            sys.stderr.write('-'*40)
            sys.stderr.write('Exception happened during processing of request from')
            sys.stderr.write(str(client_address))
            traceback.print_exc()
            sys.stderr.write('-'*40+"\n\n")
        sys.stderr.flush()

def check_string(string):
    valid_chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.-_!$&/\\=[]()@#+"
    if not all(c in valid_chars for c in string): return False
    if "\\\\" in string or "//" in string or ".." in string: return False
    return True

class myHandler(BaseHTTPRequestHandler):
    def log_message(self, format, *args):#override
        with std_lock:
            sys.stdout.write("%s(%s) - - [%s] %s\n" %
                             (self.client_address[0],
                              self.address_string(),
                              self.log_date_time_string(),
                              format%args))
        sys.stdout.flush()
       
    def send_error_page(self):
        self.send_response(200)
        self.send_header('Content-type',"text/html")
        self.end_headers()
        self.wfile.write("<html><head><meta http-equiv='refresh' content='5;url=/'/><title>Some error</title></head><body>Some error occurred, redirecting...</body></html>")
   
    def my_log_error(self, error_string):
        with std_lock:
            sys.stderr.write('-'*40)
            sys.stderr.write('Exception happened during processing of request from')
            sys.stderr.write(str(self.client_address))
            sys.stderr.write("\n")
            sys.stderr.write(error_string)
            sys.stderr.write("\n"+'-'*40+"\n\n")
        sys.stderr.flush()
       
    def do_GET(self):
        if self.path=="/favicon.ico":
            try:
                with open("icon.ico", "rb") as f:
                    self.send_response(200)
                    self.send_header('Content-type',"image/x-icon")
                    self.end_headers()
                    self.wfile.write(f.read())
            except IOError as e:
                self.my_log_error("An error occurred while sending the icon.\n"+str(e))
               
        elif self.path=="/" or self.path=="/index.html":
            self.send_response(200)
            self.send_header('Content-type',"text/html")
            self.end_headers()
            self.wfile.write("<meta http-equiv='refresh' content='0;url=/folder/'/>")
           
        elif self.path.startswith("/file/") and not ".." in self.path:
            try:
                with open("files/"+self.path[6:], "rb") as f:
                    self.send_response(200)
                    self.send_header('Content-type',"application/data")
                    self.end_headers()
                    self.wfile.write(f.read())
            except IOError as e:
                self.my_log_error("An error occurred while sending a file.\n"+str(e))
                self.send_error_page()
               
        elif self.path.startswith("/folder/") and not ".." in self.path:
            self.send_response(200)
            self.send_header('Content-type',"text/html")
            self.end_headers()
           
            html_folder_path=self.path[8:]
            folder_path=join("files", html_folder_path)
           
            if not isdir(folder_path):
                self.my_log_error("Non-existent folder requested("+folder_path+").")
                return
               
            self.wfile.write(folder_page_start)
            self.wfile.write("<div class='folder_content'><ul><div class='box_div'>")
            for thing in listdir(folder_path):
                if isdir(join(folder_path, thing)): self.wfile.write("<li><a href='"+"/folder/"+html_folder_path+thing+"/"+"'>"+thing+"</a></li>\n")
            self.wfile.write("<li><form action='/add_folder' method='POST'>\n")
            self.wfile.write("<input type='hidden' name='folder_path' value='"+html_folder_path+"'><input type='text' name='folder_name'><button type='submit'>Create Folder</button>\n")
            self.wfile.write("</form></li>\n")
            self.wfile.write("</div></ul><ul><div class='box_div'>\n")
            for thing in listdir(folder_path):
                if isfile(join(folder_path, thing)): self.wfile.write("<li><a href='"+"/file/"+html_folder_path+thing+"'>"+thing+"</a></li>\n")
            self.wfile.write("<li><form action='/add_file' method='POST' ENCTYPE='multipart/form-data'>\n")
            self.wfile.write("<input type='hidden' name='file_path' value='"+html_folder_path+"'><input type='file' name='upfile'><button type='submit'>Add File</button>\n")
            self.wfile.write("</form></li>\n")
            self.wfile.write("</div></ul>\n")
            self.wfile.write("</div>\n")
            self.wfile.write(folder_page_end)
           
        else:
            self.my_log_error("Invalid path requested (GET) ("+self.path+").")
            self.send_error_page()



    def do_POST(self):
        if self.path=="/add_folder":
            form = cgi.FieldStorage(
                fp=self.rfile,
                headers=self.headers,
                environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['Content-Type'],})
            try:
                if "/" in form["folder_name"].value or "\\" in form["folder_name"].value: raise Exception("/ in name")
                full_path=join("files/", form["folder_path"].value, form["folder_name"].value) if "folder_path" in form else join("files/", form["folder_name"].value)
                if not check_string(full_path): raise Exception("weird chars in path ("+full_path+")")
                if len(full_path) > 256:  raise Exception("path too long ("+full_path+")")
               
                with file_or_folder_add_lock:
                    if not exists(full_path):
                        makedirs(full_path)
                        self.send_response(200)
                        self.send_header('Content-type',"text/html")
                        self.end_headers()
                        self.wfile.write("<html><head><meta http-equiv='refresh' content='2;url=/'/><title>Folder Created</title></head><body>The folder was succesfully created. Redirectiong ...(<a href=\"/\">Go back NOW !</a>)</body></html>")
                    else:
                        self.send_response(200)
                        self.send_header('Content-type',"text/html")
                        self.end_headers()
                        self.wfile.write("<html><head><title>No Folder Created</title></head><body>A folder or file with that name already exists. <a href=\"/\">Go back.</a></body></html>")
                        raise Exception("Attempted to create a folder with a name of an existing folder or file")
            except TypeError as e:
                self.my_log_error("An error occurred while getting a post variable for adding folder.\n"+str(e))
                self.send_error_page()
            except KeyError as e:
                self.my_log_error("An error occurred while getting a post variable for adding folder.\n"+str(e))
                self.send_error_page()
            except Exception as e:
                self.my_log_error("An error occurred while adding a folder.\n"+str(e))
                self.send_error_page()
            except:
                self.my_log_error("An error occurred while adding a folder.")
                self.send_error_page()
        elif self.path=="/add_file":
            form = cgi.FieldStorage(
                fp=self.rfile,
                headers=self.headers,
                environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['Content-Type'],})
            try:
                if "/" in form['upfile'].filename or "\\" in form['upfile'].filename: raise Exception("/ in name")
                full_path=join("files/", form["file_path"].value, form['upfile'].filename) if "file_path" in form else join("files/", form['upfile'].filename)
                if not check_string(full_path): raise Exception("weird chars in path ("+full_path+")")
                if len(full_path) > 256:  raise Exception("path too long ("+full_path+")")
               
                with file_or_folder_add_lock:
                    if not exists(full_path):
                        with open(full_path, 'wb') as fp:
                            while True:
                                chunk = form['upfile'].file.read(8192)
                                if len(chunk) == 0: break
                                fp.write(chunk)
                        self.send_response(200)
                        self.send_header('Content-type',"text/html")
                        self.end_headers()
                        self.wfile.write("<html><head><meta http-equiv='refresh' content='2;url=/'/><title>File Added</title></head><body>The file was succesfully created. Redirectiong ... (<a href=\"/\">Go back NOW !</a>)</body></html>")
                    else:
                        self.send_response(200)
                        self.send_header('Content-type',"text/html")
                        self.end_headers()
                        self.wfile.write("<html><head><title>No File Added</title></head><body>A folder or file with that name already exists. <a href=\"/\">Go back.</a></body></html>")
                        raise Exception("Attempted to create a file with a name of an existing folder or file")
            except TypeError as e:
                self.my_log_error("An error occurred while getting a post variable for adding file.\n"+str(e))
                self.send_error_page()
            except KeyError as e:
                self.my_log_error("An error occurred while getting a post variable for adding file.\n"+str(e))
                self.send_error_page()
            except Exception as e:
                self.my_log_error("An error occurred while adding a file.\n"+str(e))
                self.send_error_page()
            except:
                self.my_log_error("An error occurred while adding a file.")
                self.send_error_page()
        else:
            self.my_log_error("Invalid path requested (POST) ("+self.path+").")
            self.send_error_page()
           


server = None           
try:
    chdir(this_dir)
    sys.stdout = open(stdout_file, "a")
    sys.stderr = open(stderr_file, "a")
    server = ThreadedHTTPServer(('', PORT_NUMBER), myHandler)
    print 'Started httpserver on port ' , PORT_NUMBER
    server.serve_forever()
    print 'serve_forever stopped'
except KeyboardInterrupt:
    print '^C received, shutting down the web server'
except:
    sys.stderr.write('some other exception')
finally:
    if server is not None: server.socket.close()
    sys.stdout.flush()
    sys.stderr.flush()
   
   


 :cura:
« Última modificación: Noviembre 09, 2013, 03:05:45 pm por Avoidance25 »
You are not allowed to view links. Register or Login
por ejemplo, se habla de emprender la You are not allowed to view links. Register or Login con el "fusil de carne" y se insta a una mujer a introducir You are not allowed to view links. Register or Login en su You are not allowed to view links. Register or Login

Desconectado jep

  • Night Elf Druid
  • Colaborador
  • ****
  • Mensajes: 1773
  • Sexo: Masculino
    • Ver Perfil
Re:Subir y bajar archivos desde un browser
« Respuesta #1 en: ſeptiembre 14, 2013, 11:30:26 am »
está muy bueno, yo hice algo parecido con el raspberry pi, coloqué un servidor svn y ftp, con acceso bajo ssh para darle más seguridad

Desconectado BigBear

  • Yo vivo en CPH
  • ***
  • Mensajes: 736
  • Sexo: Masculino
    • Ver Perfil
Re:Subir y bajar archivos desde un browser
« Respuesta #2 en: ſeptiembre 15, 2013, 03:13:01 pm »
yo habia hecho algo asi en perl pero para un troyano que se maneje via web en vez del server tradicional de sockets.


exclamation
Subir y bajar archivos del remoto

Iniciado por dante189

0 Respuestas
879 Vistas
Último mensaje Diciembre 27, 2010, 07:37:40 pm
por dante189
question
troyano - subir, bajar y ejecutar archivos

Iniciado por Manel92

2 Respuestas
1327 Vistas
Último mensaje Febrero 23, 2010, 04:51:21 pm
por alexmanycool
resuelto
[C]Problema al subir y bajar archivo desde FTP

Iniciado por wolf2000

1 Respuestas
1027 Vistas
Último mensaje Noviembre 02, 2009, 07:32:04 pm
por JaAViEr
resuelto
[S]Problema al subir y bajar archivo desde FTP

Iniciado por wolf2000

23 Respuestas
9315 Vistas
Último mensaje Noviembre 04, 2009, 04:30:38 am
por bolivianito
xx
Upload de archivos - Subir archivos al servidor

Iniciado por shevchenko

0 Respuestas
2087 Vistas
Último mensaje Julio 11, 2008, 09:36:09 am
por shevchenko
xx
Bajar archivos con C#

Iniciado por DarkCoolZeroLammer

2 Respuestas
6052 Vistas
Último mensaje Abril 12, 2010, 08:46:39 pm
por DarkCoolZeroLammer
grin
Como bajar archivos de Rapidshare

Iniciado por fizgon

30 Respuestas
14011 Vistas
Último mensaje Julio 27, 2007, 09:48:58 pm
por Assembler_C
xx
Subir archivos en VB

Iniciado por JanditoOo

3 Respuestas
1715 Vistas
Último mensaje ſeptiembre 04, 2006, 05:14:08 pm
por ranefi
xx
Subir archivos con PHP por FTP

Iniciado por shevchenko

0 Respuestas
2142 Vistas
Último mensaje Julio 11, 2008, 09:32:36 am
por shevchenko
xx
Ftp.. subir archivos

Iniciado por Azarug

5 Respuestas
2559 Vistas
Último mensaje ſeptiembre 16, 2005, 12:23:41 pm
por ghost