I've never used python before but need to write a fairly simple script for a project I'm working on. All I need is a script that listens on port 80 for incoming HTTP POSTs and prints the posted variables/parameters and values to the command line.
What's the easiest way for a beginner to get this done?
Thanks.
Consider using Flask Framework. With just 7-8 lines your job is done.
It will print all parameter sent using post and get request to your console.
Also I would recommend to learn it.
from flask import Flask
app = Flask(__name__)
#app.route("/",methods=['POST','GET'])
def index():
print request.form
return "Please Check your command line"
if __name__ == "__main__":
app.run(host='0.0.0.0',port=80,debug=True)
Related
I finally made a project that I wanted to make since a long time :
I'm using an Arduino Uno to replace my PC power button (with a simple relay) and that Arduino Board is connected to a Raspi 3 for network connection purposes
My wish is to do a webpage (or a API-Like request) that at a touch of a button (preferably in a password-protected page) It'll power the PC on
I know how to code in Python, and my script to control the Arduino is already done but I can't find a way to run, only server-side, a Python Script from a button in a webpage
I found that CherryPy framework but I don't think it'll suit my needs
Can someone give me any ideas about that please?
As already mentioned by #ForceBru, you need a python webserver.
If this can be useful to you, this is a possible unsecure implementation using flask:
from flask import Flask
from flask import request
app = Flask(__name__)
#app.route('/turnOn')
def hello_world():
k = request.args.get('key')
if k == "superSecretKey":
# Do something ..
return 'Ok'
else:
return 'Nope'
If you put this in an app.py name file and, after having installed flask (pip install flask), you run flask run you should be able to see Ok if visiting the url http://localhost:5000/turnOn?key=superSecretKey .
You could write a brief html gui with a button and a key field in a form but I leaves that to you (you need to have fun too!).
To avoid potential security issues you could use a POST method and https.
Look at the flask documentation for more infos.
I am going through some CTF challenges at https://recruit.osiris.cyber.nyu.edu/challenges.
I got to one for Template Programming where the task is to "Read /flag.txt from the server. http://recruit.osiris.cyber.nyu.edu:2000"
I am not asking for a solution, but I would like some better understanding of what is going on below:
What is this code doing?
Should I be worried about running out of Debugging mode and/or using host="0.0.0.0"?
What are some resources that could help me understand this? I tried reading through the Flask documentation and the tutorialspoint page, but I am unclear as to how this doesn't just set up a local server for testing as opposed to accessing a remote server...
If I ctrl+C do I need to worry about leaving a server still running on an open port when I am not in Debugging mode?
#!/usr/bin/env python3
from flask import Flask, request, abort, render_template_string
import os.path
app = Flask(__name__)
#app.route('/', methods=['GET'])
def index():
name = request.args.get('name')
if name is not None:
return render_template_string(open('templates/hello.html').read().format(name=name))
return render_template_string(open('templates/index.html').read())
if __name__ == "__main__":
app.run(host="0.0.0.0")
I think I can answer most of these.
As you probably already figured out, Flask is a fairly basic web framework. By the look of things, what you have there is a copy of the code running at the CTF site. It displays just two pages; one that contains the initial web form (templates/index.html) and another that uses a query string variable to greet the user (templates/hello.html) when a name has been provided.
You don't really have to run this code yourself. The 0.0.0.0 host address is catch-all that matches all IPv4 addresses on the local machine, which would include local addresses like 192.168.0.1 and 127.0.0.1 as well as the IP address used for incoming connections to the server.
Like I said, this is the code running on the remote server.
I think what you need to do is find some way of crafting a request to this web service in such a way that it reveals the contents of /flag.txt instead of (or perhaps in addition to) just saying hello. A quick search for something like "flask include file vulnerability" should give you some idea of how to attack this problem.
I have a problem. I have a project that involves sending a value from a web page to a web server and using that value to generate a voltage by commanding a digital to analog converter. For the server side I am using a Python script that works very well and I have created a simple web page in which I can enter the value wanted. But the link between them is missing. I am trying to understand CGI scripts to use them for parsing the value from the web page to the Python script but with no luck. Does anyone have any other ideas or can anyone explain CGI for beginners? Thank you.
Here is a simple Python script that pipes the output of a locally executed command (dir on a Windows computer in this case) via a web request (using the excellent web.py library):
import web
from subprocess import check_output
urls = (
'/', 'index'
)
app = web.application(urls, globals())
class index:
def GET(self):
return '<pre>'+check_output('dir', shell=True)+'</pre>'
if __name__ == "__main__":
app.run()
I'm working on a website that uses Python web.py. There is a form where the user enters input and when the submit button is hit, a python page is called (matches) using the .getJSON JQuery function show below.
function buildMatches(input){
$.getJSON("/matches", {e:input}, function(json){
//Returned JSON object is worked on
}
}
The "matches" python page grabs a value from a DB, runs some string reg ex and returns a JSON object. Everything works fine, my question is how would I be able to output something from the python page "matches" to see what is exactly happening during the reg ex operations? I've tried print "" (python 2.5), but I understand that would print to the console. I've done some research but couldn't find anything for my situation. I don't necessarily need to print it out to the HTML page, just any where where I can see what's going on. Thanks in advance for any help.
I have access to the webserver (SSH, SFTP, etc.), I tried to log by importing the logging module, below is the code I used. I could get it to log if I ran the page from the command line, but not when it is called by the JS page.
import logging
logging.basicConfig(filename='./SomeClass.log', filemode='w', level=logging.DEBUG)
class SomeClass:
logging.info('Started')
logging.info('Another log')
def __init__(self, obj):
logging.info('In the init')
def another_functio(self):
logging.info('Logging inside the function')
I've tried setting the full path of the log and I still have the same problem where the log file will only be written or updated when I run this class from the console. This doesn't work when the class is called by the webserver.
logging.basicConfig(filename='/home/.../.../.../example.log', filemode='w', level=logging.DEBUG)
Depending on how much access you have to the web server you can run your code manually so web.py uses its built-in web server. Then print statements will end up on the console.
Otherwise, have you thought about simply writing to your own log file somewhere accessible with a browser?
Thanks again for all the help. After digging more into the setup of the Apache server and Python implementation I was able to find a solution to help me see what's going and debug my web app. I saw that Apache config is setup to log errors and WSGI also blocks (pukes on) std.out. What I was able to do is redirect the print command to the Apache error log files.
print >> sys.stderr, "Debugging print with variable" + variable
Then I check the Apache error log to start debugging the web app. I thought I would share this in case anyone else ran into this problem as it was a pain for me.
Thanks again.
I have written a python console based program. It takes few arguments (like file name ) for execution.
I want to run it from the browser...
How can I parse this arguments and execute that python code
Any clues..approaches.
Thanks
Maybe you should clarify your problem. At least i don't fully understand why you want to run a terminal program in the browser?
But if you want to reuse some code you have already written you could use a micro framework like Flask.
Check this example from flask's docs:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
So you could write a simple view that accepts the arguments you need and the view would then call your code and return whatever you want, most likely an http response.