From d94a4cd5ebe42cc0a3e523f0242c50edae438879 Mon Sep 17 00:00:00 2001 From: Johannes 'josch' Schauer Date: Sun, 17 Jan 2016 11:02:12 +0100 Subject: [PATCH] initial-commit --- cgi-bin/upload.cgi | 56 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100755 cgi-bin/upload.cgi diff --git a/cgi-bin/upload.cgi b/cgi-bin/upload.cgi new file mode 100755 index 0000000..ae72a82 --- /dev/null +++ b/cgi-bin/upload.cgi @@ -0,0 +1,56 @@ +#!/usr/bin/env python3 +# +# run server with: +# +# python3 -m http.server --cgi 8000 +# +# upload file with: +# +# echo foobar | curl -F 'arg=@-;filename=bla.txt' http://127.0.0.1:8000/cgi-bin/upload.cgi +# +# or: +# +# curl -F 'arg=@blub/bla.txt' http://127.0.0.1:8000/cgi-bin/upload.cgi + +import cgi +from os.path import basename + +print("Content-Type: text/plain") +print() + +form = cgi.FieldStorage() + +if "arg" not in form: + print("no arg field") + exit() + +fileitem = form["arg"] + +if not hasattr(fileitem, "file") or not fileitem.file: + print("not a file") + exit() + +if not fileitem.filename or fileitem.filename == "-": + print("no filename") + exit() + +filename = basename(fileitem.filename) +if not filename: + print("invalid filename") + exit() + +try: + with open(filename, 'wb') as f: + while True: + data = fileitem.file.read(4096) + if not data: + break + f.write(data) +except PermissionError: + print("cannot open file for writing") +except IsADirectoryError: + print("is a directory") +except FileNotFoundError: + print("path doesn't exist") +else: + print("uploaded as %s" % filename)