Professional Documents
Culture Documents
Pickle Serialize
Pickle Serialize
Example
import pickle
hello everyone
0
In the above example, the unpickler imports the os.system function, and then
applies the string argument "echo hello everyone ". This is inoffensive, however,
it could have been a damaging one.
Example
import builtins
import io
import pickle
safe_builtins = {
'range',
'complex',
'set',
'frozenset',
'slice',
}
class RestrictedUnpickler(pickle.Unpickler):
def restricted_loads(s):
"""Helper function analogous to pickle.loads()."""
return RestrictedUnpickler(io.BytesIO(s)).load()
restricted_loads(pickle.dumps([5,3,range(20)]))
The above code generates the following output:
import os
import builtins
import pickle
import sys
sys.tracebacklimit=0
import traceback
import io
from logging import Logger
safe_builtins = {
'range',
'complex',
'set',
'frozenset'
class RestrictedUnpickler(pickle.Unpickler):
def restricted_loads(s):
"""Helper function analogous to pickle.loads()."""
return RestrictedUnpickler(io.BytesIO(s)).load()
def func1(a):
try:
x = restricted_loads(pickle.dumps(a))
return x
except pickle.UnpicklingError:
s = traceback.format_exc()
print("Traceback (most recent call last):")
return s
def func2(s):
try:
x = restricted_loads(pickle.dumps(slice(0,8,3)))
return s[x]
except pickle.UnpicklingError:
s = traceback.format_exc()
print("Traceback (most recent call last):")
return s
if __name__ == "__main__":
a=range(int(input()))
b=func1(a)
print(b)
y=tuple(input())
z=func2(y)
print(z)
Input (stdin)
Download
range(0, 50)
Traceback (most recent call last):
_pickle.UnpicklingError: global 'builtins.slice' is forbidden
import os
import json
def func1(value):
a = json.loads(value)
datas = []
for item in a["data"]:
datas.append(item)
return datas
if __name__ == "__main__":
try:
data=input()
b=func1(data)
print(True)
print(b)
except ValueError as error:
print(False)
Input (stdin)
Download
True
[{'name': 'John', 'age': 30, 'city': 'New York'}, {'name': 'Smith', 'age': 35,
'city': 'California'}]
import os
import json
def func1(value):
a = json.dumps(value)
b = json.loads(value)
return b
if __name__ == "__main__":
try:
data=input()
b=func1(data)
print(True)
print(b[1].values())
except ValueError as error:
print(False)
Input (stdin)
Download
True
dict_values(['Student2', 95])
value
# Enter your code here.
import pickle
import os
data = {"a":[5,9],"b":[5,6],"c":["Pickle is","helpful"]}
#Dump file in pickle
with open("test.pkl","wb") as f:
pickle.dump(data, f)
data.clear() #deleting dictionary data
#Read data back from pickle
with open("test.pkl","rb") as f:
data = pickle.load(f)
print(data)
pickles = []
for root,dirs,files in os.walk("./"):
# root is the dir we are currently in, f the filename that ends on ...
pickles.extend( (os.path.join(root,f) for f in files if f.endswith(".pkl")) )
pickles=str(pickles)
print(pickles)
collected 1 item
test.py .
#Write code here to access value for name and runs from class PLayer
myPlayer = Player("dhoni",10000)