python类,魔术方法等学习&&部分ssti常见操作知识点复习加深

python类学习&&部分ssti常见操作知识点复习加深

在做ssti的模块注入的时候经常觉得自己python基础的薄弱,来学习一下,其实还是要多练习多背。
在python中所有类默认继承object类。而object类提供了了很多原始的内建属性和方法,所以用户自定义的类在Python中也会继承这些内建属性。可以使用dir()函数可以查看.

#coding:utf-8
class Person(object):
    pass
print(dir(Person))

OUTPUT:

['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', 
'__hash__', '__init__', '__module__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']

class Paishenclassname(Jileiclassname):
    ...

#class  派生类名(基类名):
    ....
#即:表示Paishenclass  类   继承了  Jileiclass的所有属性、方法。
基类即超类,派生类即子类

判断A类是否是B类的子类:issubclass(A,B)
判断a是否是A类的对象:isinstance(a,A)
A.__bases__,返回A类的基类,如果没有基类,返回<class'object'>

__main__模块的作用,if __name__ == '__main__':,这个判断语句的作用是能让该python文件可以独立运行,name的名字其实是导入模块的名字,这里我们导入了main模块。

dict

__dict__属性:__dict__里存储了类的静态函数、类函数、普通函数、全局变量以及一些内置的属性,对象的__dict__中存储了一些self.xxx的一些东西,但是一些内置的数据类型是没有__dict__属性的,例如int, list, dict等这些常用的数据类型,他们是没有__dict__属性的。 

1) 内置的数据类型没有__dict__属性

2) 每个类有自己的__dict__属性,就算存着继承关系,父类的__dict__ 并不会影响子类的__dict__

3) 对象也有自己的__dict__属性, 存储self.xxx 信息,父子类对象公用__dict__  

所以我们可以通过操作对象dict属性来获取对象的属性。

# -*- coding: utf-8 -*-
class A(object):
    a = 0
    name = None
    b = 1
    def __init__(self,name):
        self.a = 2
        self.b = 3
        self.name = name
    def test(self):
        print ('a normal func.')
class B(A):
    def test_B(self):
        print ('func named test_B')
obj = A('Tom')
obj1 = B('Jerry')
print (A.__dict__)
print (obj.__dict__)
print (obj.__dict__['name'])
print (B.__dict__)
print (obj1.__dict__)
#执行结果如下
{'__module__': '__main__', 'a': 0, 'name': None, 'b': 1, '__init__': <function A.__init__ at 0x00000200C2D61840>, 'test': <function A.test at 0x00000200C2D618C8>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}

{'a': 2, 'b': 3, 'name': 'Tom'}

Tom #可以通过键来获取对象__dict__属性中的值
{'__module__': '__main__', 'test_B': <function B.test_B at 0x00000200C2D61950>, '__doc__': None}

{'a': 2, 'b': 3, 'name': 'Jerry'}
init

__init__方法的第一个参数永远是self,表示创建的实例本身,因此,在__init__方法内部,就可以把各种属性绑定到self,因为self就指向创建的实例本身,__init__()这个特殊的方法可以方便地自己对类的属性进行定义,所以__init__又被称为构造器。

对比:

class Rectangle():
   def __init__(self,a,b):
       self.a = a
       self.b = b
   def getPeri(self):
        return (self.a + self.b)*2
   def getArea(self):
       return self.a * self.b

rect = Rectangle(3,4)
print(rect.getPeri())
print(rect.getArea())
print(rect.__dict__)

OUTPUT:

14
12
{'a': 3, 'b': 4}

class Rectangle():
    def getPeri(self,a,b):
        return (a + b)*2
    def getArea(self,a,b):
        return a*b

rect = Rectangle()
print(rect.getPeri(3,4))
print(rect.getArea(3,4))
print(rect.__dict__)

OUTPUT:

14
12
{}
__str__

通过__str__()函数就可以帮助我们打印对象中具体的属性值。

class ss:
    def __init__(self,age,name):
        self.age = age
        self.name = name
    def __str__(self):
        return str(self.age)+",,wozenmezhemeshuai,,"+self.name
if __name__=="__main__":
    s = ss(21,'aitebao')
    print(s)
__del__

创建对象后,Python解释器默认调用init()方法。当删除一个对象时,Python解释器也会默认调用一个方法,这个方法为del()方法。

class Person(object):
    def __init__(self,name):
        self.name = name
    def __del__(self):
        print("实例对象:%s"%self.name,id(self))
        print("python解释器开始回收%s对象了" % self.name)

print("类对象",id(Person))
zhangsan  = Person("张三")
print("实例对象张三:",id(zhangsan))
print("------------")
lisi  = Person("李四")
print("实例对象李四:",id(lisi))

OUTPUT:

C:Python27python.exe C:/Users/Dell/Downloads/sshop/__init__.py
('xe7xb1xbbxe5xafxb9xe8xb1xa1', 53187592L)
('xe5xaex9exe4xbex8bxe5xafxb9xe8xb1xa1xe5xbcxa0xe4xb8x89:', 58654664L)
------------
('xe5xaex9exe4xbex8bxe5xafxb9xe8xb1xa1xe6x9dx8exe5x9bx9b:', 58683464L)
('xe5xaex9exe4xbex8bxe5xafxb9xe8xb1xa1:xe6x9dx8exe5x9bx9b', 58683464L)
python解释器开始回收李四对象了
('xe5xaex9exe4xbex8bxe5xafxb9xe8xb1xa1:xe5xbcxa0xe4xb8x89', 58654664L)
python解释器开始回收张三对象了

不知道为什么给转码了。

__class__

__class__功能与用法:
1.__class__功能和type()函数一样,都是查看对象所在的类。
2.__class__可以套用

#coding:utf-8
class Student(object):
    def __init__(self,name):
        self.name = name
stu = Student("tom")
print(type(stu),type(Student))
print(stu.__class__, Student.__class__, stu.__class__.__class__,stu.__class__.__base__)
print(' '.__class__.__mro__)
print(' '.__class__)
print(' '.__class__.__mro__[2].__subclasses__() )

根据网上的脚本我拓展了一下,显示了更多的类

OUTPUT:

(<class '__main__.Student'>, <type 'type'>)
(<class '__main__.Student'>, <type 'type'>, <type 'type'>, <type 'object'>)
(<type 'str'>, <type 'basestring'>, <type 'object'>)
<type 'str'>
[<type 'type'>, <type 'weakref'>, <type 'weakcallableproxy'>, <type 'weakproxy'>, <type 'int'>, <type 'basestring'>, <type 'bytearray'>, <type 'list'>, <type 'NoneType'>, <type 'NotImplementedType'>, <type 'traceback'>, <type 'super'>, <type 'xrange'>, <type 'dict'>, <type 'set'>, <type 'slice'>, <type 'staticmethod'>, <type 'complex'>, <type 'float'>, <type 'buffer'>, <type 'long'>, <type 'frozenset'>, <type 'property'>, <type 'memoryview'>, <type 'tuple'>, <type 'enumerate'>, <type 'reversed'>, <type 'code'>, <type 'frame'>, <type 'builtin_function_or_method'>, <type 'instancemethod'>, <type 'function'>, <type 'classobj'>, <type 'dictproxy'>, <type 'generator'>, <type 'getset_descriptor'>, <type 'wrapper_descriptor'>, <type 'instance'>, <type 'ellipsis'>, <type 'member_descriptor'>, <type 'file'>, <type 'PyCapsule'>, <type 'cell'>, <type 'callable-iterator'>, <type 'iterator'>, <type 'sys.long_info'>, <type 'sys.float_info'>, <type 'EncodingMap'>, <type 'fieldnameiterator'>, <type 'formatteriterator'>, <type 'sys.version_info'>, <type 'sys.flags'>, <type 'sys.getwindowsversion'>, <type 'exceptions.BaseException'>, <type 'module'>, <type 'imp.NullImporter'>, <type 'zipimport.zipimporter'>, <type 'nt.stat_result'>, <type 'nt.statvfs_result'>, <class 'warnings.WarningMessage'>, <class 'warnings.catch_warnings'>, <class '_weakrefset._IterationGuard'>, <class '_weakrefset.WeakSet'>, <class '_abcoll.Hashable'>, <type 'classmethod'>, <class '_abcoll.Iterable'>, <class '_abcoll.Sized'>, <class '_abcoll.Container'>, <class '_abcoll.Callable'>, <type 'dict_keys'>, <type 'dict_items'>, <type 'dict_values'>, <class 'site._Printer'>, <class 'site._Helper'>, <type '_sre.SRE_Pattern'>, <type '_sre.SRE_Match'>, <type '_sre.SRE_Scanner'>, <class 'site.Quitter'>, <class 'codecs.IncrementalEncoder'>, <class 'codecs.IncrementalDecoder'>, <type 'operator.itemgetter'>, <type 'operator.attrgetter'>, <type 'operator.methodcaller'>, <type 'functools.partial'>, <type 'MultibyteCodec'>, <type 'MultibyteIncrementalEncoder'>, <type 'MultibyteIncrementalDecoder'>, <type 'MultibyteStreamReader'>, <type 'MultibyteStreamWriter'>, <class '__main__.Student'>]

看到最后一项,发现了当前的<class '__main__.Student'>也被归入到可引用的类当中,当然是在__main__模块下。

利用上面的特性,我尝试读取文件,发现file内置函数在第40处:
其实这里就跟ssti有点关系了:
print(' '.__class__.__mro__[2].__subclasses__()[40]('C:README.txt').read()),这里我们没指定size,常用的格式为file.read([size])
成功的读取到了文件:
OUTPUT:

C:Python27python.exe C:/Users/Dell/Downloads/sshop/__init__.py
(<class '__main__.Student'>, <type 'type'>)
(<class '__main__.Student'>, <type 'type'>, <type 'type'>, (<type 'object'>,))
(<type 'str'>, <type 'basestring'>, <type 'object'>)
<type 'str'>
PuTTY README
============

This is the README file for the PuTTY MSI installer distribution. If
you're reading this, you've probably just run our installer and
installed PuTTY on your system.

What should I do next?
----------------------

If you want to use PuTTY to connect to other computers, or use PSFTP
to transfer files, you should just be able to run them from the
Start menu.

If you want to use the command-line file transfer utility PSCP, you
will need to run this from a Command Prompt or equivalent, because it
will not do anything useful without command-line options telling it
what files to copy to and from where. You can do this by just running
the command 'pscp' from a Command Prompt, if you used the installer's
option to put the PuTTY installation directory on your PATH.
Alternatively, you can always run pscp.exe by its full pathname, e.g.
"C:Program FilesPuTTYpscp.exe".

另外object中有部分python的内置函数,我查找并对比了一下https://www.runoob.com/python/python-built-in-functions.html 另外还有os模块:https://www.runoob.com/python/os-file-methods.html
当想使用某个类的时候,我自己编写了一个脚本,只需要替换那个file为你想找的类即可:

#coding:utf-8
class Student(object):
    def __init__(self,name):
        self.name = name
stu = Student("tom")
print(type(stu),type(Student))
print(stu.__class__, Student.__class__, stu.__class__.__class__,stu.__class__.__mro__)
print(' '.__class__.__mro__)
print(' '.__class__)
#print(' '.__class__.__mro__[2].__subclasses__()[40]('C:README.txt').read())    #这里是file.read的写法
for i in range(0,90):          #这里我的泪有90个,超过了的话会有提示,但还是会进行。
    a=' '.__class__.__mro__[2].__subclasses__()[i]
    if "file" in str(a) :
        print i
        print a
__new__
1.__new__功能:用所给类创建一个对象,并且返回这个对象。
  2.因为是给类创建实例,所以至少传一个参数cls,参数cls,代表要实例化的类,此参数在实例化时由Python解释器自动提供
  3.在类实例化时内部创建类实例的函数,并且返回这个实例,所以它是类实例时最先被调用的方法,一般不要人为定义该方法。
  4.因为要创建实例返回实例,所以要有返回值。return父类__new__出来的实例,或者直接是object的__new__出来的实例
__subclasses__

__subclasses__()函数获取类的所有子类。
通过这个例子我想可以对上面的__class__中的脚本有更好的理解,企业级理解!
网上找的脚本稍微改写了一下。

class A(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def add(self, a, b):
        return a + b

    def sub(self, a, b):
        return a - b


class B(A):
    def funb(self):
        print "Class B"


class C(A):
    def func(self):
        print "Class C"

print A.__subclasses__()

OUTPUT:

C:Python27python.exe C:/Users/Dell/PycharmProjects/pythonstudy/subclasses.py
[<class '__main__.B'>, <class '__main__.C'>]
init.globals

根据我之前的一篇文章,还有一种获取文件内容的方法{{''.__class__.__mro__[1].__subclasses__()[118].__init__.__globals__['popen']('命令').read()这里我们是使用到了os的模块,至于这个__init__.__globals__['popen']('命令').read(),这里我推测是当我们找到os模块后,继续使用init进行初始化的设置,此时我们想要读取文件,我们读取了os模块下的所有方法,所以使用globals,这时候我们想要利用popen这个函数,调用读取。
这里是os模块:

os 模块提供了非常丰富的方法用来处理文件和目录。
Python os.popen() 方法:
popen()方法语法格式如下: os.popen(command[, mode[, bufsize]]) 实例:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os, sys

# 使用 mkdir 命令
a = 'mkdir nwdir'

b = os.popen(a,'r',1)

print b

OUTPUT:

open file 'mkdir nwdir', mode 'r' at 0x81614d0  

所以根据上面的我们能够读取到文件,read不能去掉,read()方法能够帮我们进行读取返回信息,应该是吧hhh。

关于os模块的常用方法:
https://www.runoob.com/python/os-file-methods.html

python搞完,就要去冲PHP得了,像PHP的模板smarty等等,其实python里面还是有很多的模块操作,还值得更加深入。

原文地址:https://www.cnblogs.com/ophxc/p/12981447.html