Executing arbitrary Python code (user submitted) inside an Azure Function - python

I'm trying to run a sample function that allows a user to execute arbitrary code
Note: I"m assuming this is ok because Azure Functions will by default provide a sandbox. (And the end user will need to write code with dataframes, objects etc. I've looked into pypy.org but don't think I need it as I am not worried about attacks that use it as a spambot or something):
import os
import json
import ast
print('==============in python function========================')
postreqdata = json.loads(open(os.environ['req']).read())
response = open(os.environ['res'], 'w')
response.write("hello world from "+postreqdata['name'])
response.close()
logic = (postreqdata['logic'])
eval(logic)
but I keep getting the following output/error:
2018-01-17T09:09:08.949 ==============in python function========================
2018-01-17T09:09:09.207 Exception while executing function: Functions.ccfinopsRunModel. Microsoft.Azure.WebJobs.Script: Traceback (most recent call last):
File "D:\home\site\wwwroot\ccfinopsRunModel\run.py", line 12, in <module>
eval(logic)
File "<string>", line 1
print('code sent from client')
^
SyntaxError: invalid syntax
.
My POST request body contains the following:
{
"name": "Python Function App",
"logic": "print('code sent from client')"
}
So the "logic" variable is being read in, and eval() is trying to interpret the string as python code, but it is causing a Syntax Error where there appears to be none.
What am I doing wrong? If there was a restriction on 'eval' I'm assuming it would say that instead of "Syntax Error"
Thanks for any help you can provide!

Use exec to run your code. eval is used evaluating expressions.
logic = (postreqdata['logic'])
exec(logic)
Also can try sending your code as multi-line string as below,
>>> s = '''
for i in range(3):
print("i")
'''
>>> exec(s)
0
1
2

Related

Getting the last created item selection

I run a command in which it creates a new camera, however at the end of the said function, there is no selection nor does the function selects the object after it has run its course.
So are there any commands in which I could possible query for the last created item?
I tried using `cmds.listHistory' but that will only shows you results if there is already a selection..
Any ways in which I can get around with it?
Additionally, say I am using the following command using the
cameraShape...
aaa = "cameraShape1"
mel.eval('<Some mel-based command> cameraShape.transformX cameraShape.transformY cameraShape.transformZ;')
but when I tried writing that command in another way such as :
mel.eval('<Some mel-based command> %s.transformX %s.transformY %s.transformZ;' %aaa)
I got an error saying
# Error: not enough arguments for format string
# Traceback (most recent call last):
# File "<maya console>", line 1, in <module>
# TypeError: not enough arguments for format string #
Where am I writing it wrong exactly? I tried writing like %aaa, aaa, aaa still the same error occurs
Why can't you just stuff the new camera into a variable instead of relying on selection?
new_camera, new_camera_shape = cmds.camera()
You're not using the right syntax when formatting with %:
"My name is %s" % "Jon Snow" # Works for single
"My name is %s and I was born in %s" % ("Jon Snow", "Winterfell") # Multiple
Personally I prefer format() as it's suppose to be more forward compatible for Python 3:
"My name is {0} and I was born in {1}".format("Jon Snow", "Winterfell")
Detect new objects:
scene_before = cmds.ls(l=True, transforms=True)
# Run command to import object here
scene_after = cmds.ls(l=True, transforms=True)
new_objs = list( set(scene_after).difference(scene_before) )
If you want to keep the last created object. You can create a class that contain a variable history where your append in your other script the last object created.
class History:
idCounter = []
def __init__(self, name):
History.idCounter.append(name)
print(History.idCounter)
for name in ['nana', 'tata', 'zaza']:
objectCreated = History(name)

CGI with Python

I'm beginning to use CGI with Python.
After running the following piece of code:
#!c:\python34\python.exe
import cgi
print("Content-type: text/html\n\n") #important
def getData():
formData = cgi.FieldStorage()
InputUN = formData.getvalue('username')
InputPC = formData.getvalue('passcode')
TF = open("TempFile.txt", "w")
TF.write(InputUN)
TF.write(InputPC)
TF.close()
if __name__ =="__main__":
LoginInput = getData()
print("cgi worked")
The following error occurs:
Traceback (most recent call last):
File "C:\xampp\htdocs\actual\loginvalues.cgi", line 21, in <module>
LoginInput = getData()
File "C:\xampp\htdocs\actual\loginvalues.cgi", line 16, in getData
TF.write(InputUN)
TypeError: must be str, not None
>>>
I'm trying to write the values, inputted in html, to a text file.
Any help would be appreciated :)
Your calls to getValue() are returning None, meaning the form either didn't contain them, had them set to an empty string, or had them set by name only. Python's CGI module ignores inputs that aren't set to a non-null string.
Works for Python CGI:
mysite.com/loginvalues.cgi?username=myname&pass=mypass
Doesn't work for Python CGI:
mysite.com/loginvalues.cgi?username=&pass= (null value(s))
mysite.com/loginvalues.cgi?username&pass (Python requires the = part.)
To account for this, introduce a default value for when a form element is missing, or handle the None case manually:
TF.write('anonymous' if InputUN is None else InputUN)
TF.write('password' if InputPC is None else InputUN)
As a note, passwords and other private login credentials should never be used in a URL. URLs are not encrypted. Even in HTTPS, the URL is sent in plain text that anyone on the network(s) between you and your users can read.
The only time a URL is ever encrypted is over a tunneled SSH port or an encrypted VPN, but you can't control that, so never bank on it.

Python and Secpay (paypoint) xml-rpc call

I have the next code somewhere in Pyramid application
import xmlrpclib
....
#view_config(route_name='api-paypoint', renderer='string')
def api_paypoint(request):
call_data = ["mid", "password", "name"]
api_server = xmlrpclib.ServerProxy('https://www.secpay.com/secxmlrpc/make_call')
response = api_server.SECVPN.validateCardFull(call_data)
print response
return {}
What I'm trying is to call Secpay API (here's JAVA's example http://www.paypoint.net/support/gateway/soap-xmlrpc/xmlrpc-java/ )
I'm getting the next error:
Exception Value: <Fault 0: 'java.lang.NoSuchMethodException: com.secpay.secvpn.SECVPN.validateCardFull(java.util.Vector)'>
Any idea what is wrong here?
I found a problem. I was trying to pass to api_server.SECVPN.validateCardFull() which is wrong. This should be changed to
api_server.SECVPN.validateCardFull('mid', 'password', 'name')
You're calling with the wrong number of arguments, and the java serverside can't find a method matching that signature. If you call with 14 strings the exception changes (something about the serverside failing to encode a null).
proxy.SECVPN.validateCardFull("","","","","","","","","","","","","","")

Type error writing to file in Python

I am writing a Python script to notify me when changes are made to a webpage and store the current state of the page to a file in order to resume seamlessly after rebooting.
The code is as follows:
import urllib
url="http://example.com"
filepath="/path/to/file.txt"
try:
html=open(filepath,"r").read() # Restores imported code from previous session
except:
html="" # Blanks variable on first run of the script
while True:
imported=urllib.urlopen(url)
if imported!=html:
# Alert me
html=imported
open(filepath,"w").write(html)
# Time delay before next iteration
Running the script returns:
Traceback (most recent call last):
File "April_Fools.py", line 20, in <module>
open(filepath,"w").write(html)
TypeError: expected a character buffer object
------------------
(program exited with code: 1)
Press return to continue
I've no idea what this means. I'm relatively new to Python. Any help would be much appreciated.
urllib.urlopen does not return a string, it returns a response as a file-like object. You need to read that response:
html = imported.read()
Only then is html a string you can write to a file.
As an aside, using open(filename).read() is not considered good style, because you never close the file. The same goes for writing. Try using a context manager instead:
try:
with open(filepath,"r") as htmlfile:
html = htmlfile.read()
except:
html=""
The with block will automatically close the file when you leave the block.

How do I search for text in a page using regular expressions in Python?

I'm trying to create a simple module for phenny, a simple IRC bot framework in Python. The module is supposed to go to http://www.isup.me/websitetheuserrequested to check is a website was up or down. I assumed I could use regex for the module seeing as other built-in modules use it too, so I tried creating this simple script although I don't think I did it right.
import re, urllib
import web
isupuri = 'http://www.isup.me/%s'
check = re.compile(r'(?ims)<span class="body">.*?</span>')
def isup(phenny, input):
global isupuri
global cleanup
bytes = web.get(isupuri)
quote = check.findall(bytes)
result = re.sub(r'<[^>]*?>', '', str(quote[0]))
phenny.say(result)
isup.commands = ['isup']
isup.priority = 'low'
isup.example = '.isup google.com'
It imports the required web packages (I think), and defines the string and the text to look for within the page. I really don't know what I did in those four lines, I kinda just ripped the code off another phenny module.
Here is an example of a quotes module that grabs a random quote from some webpage, I kinda tried to use that as a base: http://pastebin.com/vs5ypHZy
Does anyone know what I am doing wrong? If something needs clarified I can tell you, I don't think I explained this enough.
Here is the error I get:
Traceback (most recent call last):
File "C:\phenny\bot.py", line 189, in call
try: func(phenny, input)
File "C:\phenny\modules\isup.py", line 18, in isup
result = re.sub(r'<[^>]*?>', '', str(quote[0]))
IndexError: list index out of range
try this (from http://docs.python.org/release/2.6.7/library/httplib.html#examples):
import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("HEAD","/index.html")
res = conn.getresponse()
if res.status >= 200 and res.status < 300:
print "up"
else:
print "down"
You will also need to add code to follow redirects before checking the response status.
edit
Alternative that does not need to handle redirects but uses exceptions for logic:
import urllib2
request = urllib2.Request('http://google.com')
request.get_method = lambda : 'HEAD'
try:
response = urllib2.urlopen(request)
print "up"
print response.code
except urllib2.URLError, e:
# failure
print "down"
print e
You should do your own tests and choose the best one.
The error means your regexp wasn't found anywhere on the page (the list quote has no element 0).

Categories