Sunday, June 26, 2016

small web shell implement in python

directory strtucture
$ tree -r -a shell/
shell/
├── http-starter.py
├── htbin
└── cgi-bin
    └── shell.py



1- http-starter.py code
from http.server import CGIHTTPRequestHandler, HTTPServer

handler = CGIHTTPRequestHandler
handler.cgi_directories = ['/cgi-bin', '/htbin']  # this is the default
server = HTTPServer(('localhost', 8080), handler)
server.serve_forever()



2- shell.py code
#!/usr/bin/env python
import subprocess
import re
import os
import shlex

import cgi
print "Content-Type: text/html"
print
print """\
<html>
<body>
<h2>SHELL!</h2>
"""

#print re.sub("\n", "<br>",lss.stdout.read())
#print "exec form"
print "<br>"


#pprint.pprint(dir(cgi))
if os.environ['REQUEST_METHOD'] == 'POST':
    #print "get posting"
    form = cgi.FieldStorage()
    inputs = form["username"].value
    command = shlex.split(inputs)
    lss = subprocess.Popen(command ,stdout=subprocess.PIPE, \

    stderr=subprocess.PIPE)
    

    print "$ " + " ".join(command) + "<br>"
    print re.sub("\n", "<br>", lss.stdout.read())
    print "----------------<br>"
    print "error part<br>"
    print "----------------<br>"
    print re.sub("\n", "<br>", lss.stderr.read())

print """<br>
<form method="post"  action="/cgi-bin/shell.py">
<input type="text" name="username">
<input type="submit" value="submit">
</form>
"""
print """
</body>
</html>
"""


2- usange
$ cd shell
$ python http-starter.py

to access the shell using url http://localhost:8080/cgi-bin/shell.py

--screenshot


- it also report the error message




No comments:

Post a Comment