How do I call a python function with parameters in CGI? - python

I want to build an interface for browsing an Apache2 server using python scripts.
I spent the past days learning python and today getting familiar with CGI. I want to test out some stuff, like the possibility for the user to navigate to the path he wants from the base directory
/var/www/cgi-bin
by inputting the path he wants to visit, for example
/etc/httpd/conf.d.
For that i have the change_path.py script which looks like this:
import os
def changePath(path):
os.chdir(path)
I already got this script running to make sure everything is set up properly:
#!/usr/bin/python
# Import modules for CGI handling
import cgi, cgitb, os
cwd = os.getcwd()
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>TestScript</title>"
print "</head>"
print "<body>"
print "<h2> Current working directory is: %s</h2>" % cwd
print "</body>"

Related

Synology webstation settings to run python

On my synology I have webstation up and running (tested) Default server is Apache 2.4.
By default, on DSM 7, Python is installed. Now I created a simple test.py script which I call from my browser:
#!/usr/bin/python
import os
print ("Content-type: text/html\n\n")
print ("<html>Hello world!</html>")
if 'REQUEST_METHOD' in os.environ :
print ("This is a webpage")
else :
print ("This is not a webpage")
When I run this "192.bla.bla/web/test.py" the code is not executed but just displayed. So I get this in my browser:
#!/usr/bin/python
import os
print ("Content-type: text/html\n\n")
print ("<html>Hello world!</html>")
if 'REQUEST_METHOD' in os.environ :
print ("This is a webpage")
else :
print ("This is not a webpage")
Obviously Python is not executed so I searched the internet and found this, outdated German, topic: Link to Topic
Telling me to change some config files. However the directories these files should contain are not on my system. I'm also not sure if this even is the solution as this topic is outdated.
Does anyone have Python running on Synology webstation?
Try using a php server and page and then using this in the index.php
<?php
$command = escapeshellcmd('/usr/custom/test.py');
$output = shell_exec($command);
echo $output;
?>

Python script autorun on windows startup

I am trying to create a script that will display a page in chrome on startup. That is, I am trying to run a python script on startup. I am using the winreg module to do so.
Here is my script to add a my page display script on startup:
import winreg
import os
import sys, traceback
def AddToRegistry():
pth = os.path.dirname(os.path.realpath(path_to_page_display_script))
s_name="test.py"
address=os.path.join(pth,s_name)
try:
open = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\\Microsoft\\Windows\\CurrentVersion\\Run", reserved=0, access = winreg.KEY_ALL_ACCESS)
winreg.SetValueEx(open,"pytest",0,winreg.REG_SZ,address)
winreg.CloseKey(open)
except Exception:
traceback.print_exc(file=sys.stdout)
if __name__=="__main__":
AddToRegistry()
Here is my page display script:
import webbrowser
url = 'http://docs.python.org/'
chrome_path = 'path_to_chrome/chrome.exe %s'
webbrowser.get(chrome_path).open(url)
The script runs fine without any errors but on restarting my machine, the chrome does not open up by itself nor does it display the page. Basically, my script does not run. What is wrong ? Kindly help me out.
The problem isn't with your script. It's with your registry key.
You need to tell windows to invoke Python.exe C:\path_to_script\test.py, not test.py.
So instead of this:
This:
path_to_python_exe = "C:\\python\\python38";
address=os.path.join(pth,s_name)
address = os.path.join(path_to_python_exe, "python.exe") + " " + address;
Or if Python.exe is guaranteed to be in your PATH, simply this:
address = "Python.exe" + " " + os.path.join(pth,s_name)

First Python CGI working, the one called in its GET method is not working

My hello.py (working fine) passes data through GET method (can be seen in URL) to test.py (not working).
Test.py working on -bash and gives no error but with http://localhost/cgi-bin/test.py it gives an error
500 Internal Server Error.
In -bash it gives "EMPTY" as values passed.
Code for test.py (access mode for this file is -rwxrwxrwx# so that is not an issue)
#!/usr/bin/python
import os
import cgi
import cgitb ;cgitb.enable()
form = cgi.FieldStorage()
first_name = str(form.getvalue('first_name','EMPTY'))
last_name = str(form.getvalue('last_name', 'EMPTY'))
print ("Content-Type:text/html\r\n\r\n")
print ('<html>')
print ('<head>')
print ('<title>Second CGI Program</title>')
print ('</head>')
print ('<body>')
print ('Hello %s %s' %(first_name,last_name))
print ('</body>')
print ('</html>')

CGI script end of script before headers

I have a VPS server with Apache on it. I want to execute simple CGI script. I created a python script, saved it as .cgi file and placed it to the folder cgi-bin, but it only displays error message: "End of script output before headers".
However when I saved this script as .py file and did not place it into cgi-bin folder, it worked, but whenever there was an error, it did not show any error message, just server error. Command cgitb.enable() did not show any error.
I tried to give the file 755 permission, but that still did not solve my problem.
Where could be a problem?
Source code:
#!/usr/local/bin/python3
print("Content-type:text/html")
print("")
print ("<html><head><title>CGI</title></head>")
print ("<body>")
print ("hello cgi")
print ("</body>")
print ("</html>")
Thank you for your answers.
It might be more useful to use sys.stdout.write and add \n so that you know exactly what gets written to standard output:
#!/usr/bin/env python
import sys
import os
sys.stdout.write('Status: 200 OK\n')
sys.stdout.write('Content-Type: text/html; charset=utf-8\n\n')
sys.stdout.write('<html><body>Hello, world!</body></html>\n')
sys.exit(os.EX_OK)
Run the script with python script.py | cat -e so that you can verify line endings.
Make sure you aren't sending any more HTTP headers after you start sending content.

Executing Code in Python Web

im creating a webpage that will show me the SSID's available in my Network
For this I have use this code:
nm-tool | grep "Infra" | cut -d " " -f5 > /home/nunukene/SSID3.txt
Im saving this into a file called SSID3, to later open it using the open() , read() and str.split
My problem is that the code I want to execute in the page, wont get executed, the file SSID3.txt wont be created
This is my website code so far:
#!/usr/bin/python
import os
import subprocess
import cgitb
cgitb.enable()
a=os.system("""nm-tool | grep "Infra" | cut -d " " -f5 > /home/nunukene/SSID3.txt""")
#SSIDStr = subprocess.check_output('nm-tool | grep "Infra" | cut -d " " -f5-6', shell=True)
#SSIDArray = str.split(SSIDStr)
ID = subprocess.check_output('ls', shell=True)
a='devilman'
print "Content-type:text/html\r\n\r\n"
print "<!DOCTYPE html>"
print "<html>"
print "<title> Not Hacking lol</title>"
print "<body>"
print "<h1> Join %s One of this networks <h1>" %(a)
print "</body>"
print "</html>"
I dont know how to get this process working before the rest!
I highly suggest using the logging module to help you diagnose where your problem is.
a reason your subprocess call didn't work is you would need to make a list out of all of the arguments to the command.
SSIDStr = subprocess.check_output(['nm-tool','|','grep','"Infra"','|','cut','-d','" "','-f5'])
(I'm not sure if you have to escape the double-quotes in this string)
using the subprocess call this way avoids using the text file and it's permission problems that the web server user may be experiencing writing files.
you were re-writing the "a" variable and you weren't using the text file in the output.
and I hope the cgitb.enable() line wasn't the problem. Haven't seen that before. Have you thought of using Flask?
If you are using python 3 then the print statements need to be functions.

Categories

Resources