欢迎光临
我们一直在努力

第九章:Python渗透与安全自动化实战指南 (上)

python学习原因

  • 渗透方向:

    • 1.网络扫描何枚举

    • 2.漏洞开发

    • 3.密码破解

    • 4.web应用测试

    • 5.流量包,嗅探

    • 6.社工

  • 应急响应方向:

    • 1.配置管理

    • 2.安全自动化

    • 3.密码管理

    • 4.安全监控

    • 5.身份验证

  • python的特点:

    • 1.跨平台

    • 2.解释型

    • 3.脚本语言

    • 4.动态语言

    • 5.默认utf8编码


配置python (以kali为例)

  • 创建.vimrc文件

set nocompatible
set number
set nowrap
set showmatch
set scrolloff=3
set encoding=utf-8
set fenc=utf-8
set mouse=a
set hlsearch
syntax on

au BufNewFile,BufRead *.py
set tabstop=4
set softtabstop=4
set shiftwidth=4
set textwidth=79
set expandtab
set autoindent
set fileformat=unix

  • 创建python文件


数据类型与变量

  • None和Bool

    • None

      • 表示空对象
    • Bool

      • Python中使用True和False来表示布尔值,注意首字母大写,即判断Python对象、返回值、表达式真假的一组特殊数据类型
  • 保留字

    • 保留字,又称为关键字,每种语言都有自己的一套预先保留的特殊标识符,Python也不例外,它自带的keyword模块可以查看全部关键字

内置函数

Built-in Functions
abs() divmod() input() open() staticmethod()
all() enumerate() int() ord() str()
any() eval() isinstance() pow() stum()
basestring() execfile() issubclass() print() super()
bin() file() iter() property() tuple()
bool() filter() len() range() type()
bytearray() float() list() raw_input() unichr()
callable() format() locals() reduce() unicode()
chr() frozenset() long() reload() vars()
classmethod() getattr() map() repr() xrange()
cmp() globals() max() reversed() zip()
compile() hasattr() memoryview() round() _import_()
complex() hash() min() set()
delattr() help() next() setattr()
dict() hex() id() object() slice()
dir() id() oct() sorted()

变量

  • 编程语言中为了能够更好的处理数据,都需要使用一些变量。变量基本上就是代表(或是引用某值的名字)。Python语言的变量可以是各种不同的数据类型,使用变量的时候不需要声明,Python解释器会自动判断数据类型。使用 type(变量) 可以查看该变量的类型
  • 变量命名规则

    • 驼峰命名法

    • 下划线命名法

  • 空行, 缩进, 多行代码

    • 空行

      • 一般空行用于不同函数之间、不同类之间、以及类和函数之间进行分隔。空行不是Python的语法,即使不插入空行程序运行也不会出错。插入空行主要目的是方便代码阅读以及日后的维护

字符串

  • 概念

    • Python3 中的字符串可以使用双引号或单引号标示,如果字符串中出现引号,则可以使用 \\ 来去除引号标示字符串的特殊作用
  • 常用属性和方法

    • count

    • split 和 strip

      • split分割
        • str1 = 'hello world'
          list1 = str1.split()
          ## 输出 ['hello', 'world']

          str2 = 'hello:world'
          list2 = str2.split(':')
          ## 输出 ['hello', 'world']

      • strip去除
        • str2 = ' hello '
          list2 = str2.strip()
          ## 输出 'hello'

    • upper 和 lower

      • upper全部大写
      • lower全部小写
    • __len__

      • str.__len__()
        len(str)
        ## 这两种都可以


运算符

  • 算术运算符

    运算符名称描述
    + 两个对象相加
    得到负数或是一个数减去另- 个数
    * 两个数相乘或是返回 个被重复若干次的字符串
    / ×除以 y
    % 取模 返回除法的余数
    ** 返回×的y次幂
    // 取整除 返回商的整数部分 (向下取整)
  • 比较运算符

    运算符描述
    == 等于:比较对象是否相等
    != 不等于:比较两个对象是否不相等
    > 大于:返回×是否大于y
    < 小于:返回×是否小于 y
    >= 大于等于:返回×是否大于等于y
    <= 小于等于:返回×是否小于等于y
  • 赋值运算符

    运算符描述实例
    = 简单的赋值运算符 c= a+b 将a+b的运算结果赋值为 c
    += 加法赋值运算符 c+=a等效于c=c+a
    -= 减法赋值运算符 c-=a等效于c=c-a
    *= 乘法赋值运算符 c*=a等效于c=c*a
    /= 除法赋值运算符 c /= a 等效于c= c/a
    %= 取模赋值运算符 c%= a等效于 c = c % a
    **= 幂赋值运算符 c *= a 等效于 c= c **a
    //= 取整除赋值运算符 c //= a 等效干 c= c // a
  • 逻辑运算符

    运算符逻辑表达式描述
    and x and y 布尔"与": 如果×为 False,× and y 返回 False,否则它返回 y 的计算值
    or x or y 布尔"或": 如果×是非0,它返回×的值,否则它返回y的计算值
    not not x 布尔"非": 如果x为 True,返回 False。如果×为 False,它返回 True
  • 成员运算符

    运算符描述
    in 如果在指定的序列中找到值返回True,否则返回False
    not in 如果在指定的序列中没有找到值返回True,否则返回False
  • 身份运算符

    运算 符描述实例
    is is 是判断两个标识符是不是引 用自一个对象 x is y, 类似 id(x) == id(y),如果引l用的是同一个对象则返回 True,否则返回False
    is not isnot是判断两个标识符是不 是引用自不同对象 x is not y ,类似 id(a) != id(b)。如果引l用的不是同一个对象则 返回结果True,否则返回False
  • 运算符优先级

    运算符描述
    ** 指数 (最高优先级)
    按位翻转,一元加号和减号(最后两个的方法名为+@ 和-@)
    * / % // 乘,除,取模和取整除
    ± 加法减法

判断与循环

  • for循环

  • while循环

  • break关键字

  • continue关键字


命令行参数

  • 模块

    • __name__和__main__

      #!/usr/bin/env python3
      print('__name__ value is :{}'.format(__name__))

    • 引入模块的方式

    • 模块的搜索路径

      • import xxxx
      • from xxx import xxx
      • from xxx import xxx as xxx
    • 搜索的搜索路径


  • pip常用命令:

    • 显示版本和路径:

      • pip3 –version
    • 升级 pip: sudo pip3 install-upgrade pip

    • 安装包:(sudo)pip3 install package, 如果需要指定版本就是:pip3 install package:==1.0.3 (写具体的版本号)

    • 卸载包

      • pip3 uninstall package
    • 升级包

      • pip3 install-upgrade package
        • 可以使用 ==,>=,<=,<,> 来指定版本号
    • 查看安装已安装的包

      • pip3 list
    • 把需要安装的一系列包写入requirements.txt文件中, 然后执行:pip3 install-r requirements.txt


列表

  • 是一种有序的数据集合, 可以通过索引访问到每一个列表的元素
  • course.append('xxx')

  • course.insert('xxx')

  • course.remove('xxx')

  • course.extend('xxx')

  • course.pop('xxx')


元组 (tuple)

  • 是一种特殊的列表, 不同点是元组一旦创建就不能修改, 类似列表的所有会修改列表内容的操作等对于元组都不再适用
  • t1 = ('C')
    type(t1) ## 字符型

    t2 = ('C',)
    type(t2) ## 元组型


集合 (set)

  • 是一个无序不重复元素的数据集, 对比列表的区别首先是无序的, 不可以使用索引进行顺序的访问, 另外一个特点是不能够有重复的数据
    • ()是元组
    • []是数组
    • {}是集合
  • course.add('xxx')

  • course.remove('xxx')

  • 去重判断

  • add

  • 集合的运算

    • set1 | set2 或运算 (并集)
      • 重复的不算
    • set1 & set2 和运算 (交集)
      • 算重复的
    • set1 – set2
      • 将set1中的set2去除
    • set1 ^ set2
      • 重复的去除

字典 (dict)

  • 是无序的键值对集合, 字典中的每一个元素都是一个 key 和一个 value 的组合, key值在字典中必须是唯一的, 因为可以很方便的从字典中使用key获取其对应的 value 的值
  • coursesdict.get(1)

  • coursesdict.keys()

  • coursesdict.values()

  • coursesdict[1]

  • coursesdict.pop(2)


数据类型的转换

方法描述
int(x, base) 将 × 转换为一个整数
float(x) 将 × 转换为 个浮点数
str(x) 将对象 × 转换为字符串 人
list(s) 将序列 s 转换为 个列表
tuple(s) 将序列 s 转换为- -个元组
set(s) 将序列 s 转换为可变集合
dict(d) 创建一个字典,d 必须是 个序列 (key,value)元组

函数

  • 定义

  • 返回值

  • 作用域

    • 全局变量

    • 局部变量

  • 函数的参数

    • 必选参数

    • 默认参数

    • 可变参数

    • 关键字参数


文件处理

  • 文件处理是项目开发中使数据持久化和获取配置的主要方式。我们在平时的工作中接触到各种文件类型,比如 word、视频、txt文本等。Python中提供了很方便读写文件的函数,可以很方便的处理各种类型的文件
  • I/O

    • 标准输入输出流

  • open/close

    • file = open('xxx')

    • file.close()

    • with open('xxx') as file:

    • filename = 'xxx'

    • with open(filename) as file:

  • 读取文件内容

    • file.readline()

  • 文件写入与读取

    • ## 写入
      filename = 'xxx'
      with open(filename, 'w') as f:
      f.write('xxx')

      ## 读取
      filename = 'xxx'
      with open(filename, 'r') as f:
      print(file.readlines())

      ## 追加
      filename = 'xxx'
      with open(filename, 'a') as f:
      file.write('xxx')

  • json序列化

    • import pickle
      courses = {1: 'Linux', 2: 'vim', 3: 'Java'}
      with open('./courses.data', 'wb') as file:
      pickle.dump(courses, file)
      with open('./courses.data', 'rb') as file:
      new_courses = pickle.load(file)

      ## new_courses 输出 {1: 'Linux', 2: 'vim', 3: 'Java'}

      import json
      courses
      json.dumps(courses)
      with open('courses.json', 'w') as f:
      f.write(json.dumps(courses))

      ## cat courses.json 得到 {1: 'Linux', 2: 'vim', 3: 'Java'}

  • csv文件读取 (逗号分隔值)

在这里插入图片描述


异常

  • #!/usr/bin/env python3
    filename = '/etc/protocols'
    f = open(filename)
    try:
    f.write('1111')
    except:
    # raise:
    print('file write error')
    finally:
    print('finally')
    f.close()


面向对象

  • 面向对象编程 (OOB)

    • 核心概念

      • 抽象
      • 封装
      • 继承
      • 多态
  • 类与对象

      • 用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法
      • class 类名
        • 属性
        • 方法
        • 代码块 ()
    • 对象

      • 对象:某个类的一个实体,当有了对象后,这些属性便有了属性值,行为也就有了相应的意义
      • new 对象名
        • 对象名 = 类名 ()
  • 实例方法

    • 类中定义函数的方法与普通函数方法区别

      • 类中的函数必须有个self参数, 且处于第一位置, 用来表示实例化对象的引用
  • 封装

    • 在面向对象的语言中, 封装就是用类将数据与基于数据的操作封装在一起, 隐藏内部数据, 对外提供公共的访问接口

      #!/usr/bin/env python3

      class Dog(object):
      def __init__(self, name):
      self.name = name
      def get_name(self):
      return self.name
      def set_name(self, value):
      self.name = value
      def bark(self):
      print(self.get_name() + 'is making sound wangwang!')

      class Cat(object):
      def __init__(self, name):
      self.name = name
      def get_name(self):
      return self.name
      def set_name(self, value):
      self.name = value
      def bark(self):
      print(self.get_name() + 'is making sound miaomiaomiao!')

      dog = Dog('laifu')
      cat = Cat('kitty')

      dog.bark()
      cat.bark()

  • 继承

    • 继承就是子类继承父类的特征和行为,使得子类对象(实例)具有父类的实例域和方法,或子类从父类继承方法,使得子类具有父类相同的行为

    • 单继承

      #!/usr/bin/env python3

      class Animal(object):
      def __init__(self,name):
      self.name = name

      def get_name(self):
      return self.name

      def set_name(self,value):
      self.name = value

      def make_sound(self):
      pass

      class Dog(Animal):
      def make_sound(self):
      print(self.get_name()+' is making sound wowowowowo')

      class Cat(Animal):
      def make_sound(self):
      print(self.get_name()+ ' is making sound miao miao miao')

      dog = Dog('er ha')
      cat = Cat('jafei')

      dog.make_sound()
      cat.make_sound()

    • 多继承

      #!/usr/bin/env python3
      class A:
      def __init__(self):
      self.name = 'wuyue'

      def gongfuA(self):
      print('———python———')

      class B:
      def __init__(self):
      self.age = 38

      def gongfuA(self):
      print('———–XSS——–')

      class XueYuan(A,B):
      def __init__(self):
      A.__init__(self)
      B.__init__(self)

      def testXY(self):
      print('———xueyuan——-')

      person = XueYuan()
      person.gongfuA()
      print(XueYuan.mro())
      #person.gongfuB()
      #person.testXY()

  • 多态

    • 指的是一类事物有多种形态,一个抽象类有多个子类(因而多态的概念依赖于继承),不同的子类对象调用相同的方法,产生不同的执行结果,多态可以增加代码的灵活度

    • 形式上的非多态

      #!/usr/bin/env python3

      class Duck():
      def who(self):
      print('i am a duck')

      class Dog():
      def who(self):
      print('i am a dog')

      class Cat():
      def who(self):
      print('i am a cat')

      duck = Duck()
      dog = Dog()
      cat = Cat()

      duck.who()
      dog.who()
      cat.who()

    • 形式上的多态

      #!/usr/bin/env python3

      class Animal():
      def who(self):
      print('i am an animal')

      class Duck(Animal):
      def who(self):
      print('i am a duck')

      class Dog(Animal):
      def who(self):
      print('i am a dog')

      class Cat(Animal):
      def who(self):
      print('i am a cat')

      duck = Duck()
      dog = Dog()
      cat = Cat()

      duck.who()
      dog.who()
      cat.who()

    • 实际上的多态

      #!/usr/bin/env python3

      class Animal():
      def who(self):
      print('i am an animal')

      class Duck(Animal):
      def who(self):
      print('i am a duck')

      class Dog(Animal):
      def who(self):
      print('i am a dog')

      class Cat(Animal):
      def who(self):
      print('i am a cat')

      def func(obj):
      obj.who()

      duck = Duck()
      dog = Dog()
      cat = Cat()

      func(duck)
      func(dog)
      func(cat)

  • 私有属性和方法

    class Person:
    def __init__(self, name, age, secret):
    self.name = name # 公有
    self._age = age # 约定私有(程序员间默契)
    self.__secret = secret # 真正私有(名称改写)

    def show(self):
    print(f"名字: {self.name}")
    print(f"年龄: {self._age}")
    print(f"秘密: {self.__secret}")

    p = Person("小明", 18, "我喜欢隔壁班小红")

    # 可以访问的
    print(p.name) # 小明
    print(p._age) # 18 (能访问,但不建议)
    # print(p.__secret) # AttributeError: 'Person' object has no attribute '__secret'

    # 但其实可以通过“改写后的名字”访问(不推荐这么干)
    print(p._Person__secret) # 我喜欢隔壁班小红 ← 这就是名称改写

    p.show() # 正常输出所有信息

  • 类属性

    #!/usr/bin/env python3

    class Animal(Object):
    owner = 'xxx'
    def __init__(self, name):
    self.name = name

    print(Animal.owner)

  • 类方法

    #!/usr/bin/env python3

    class Animal(object):
    owner = 'xxx'
    def __init__(self, name):
    self.name = name

    @classmethod
    def get_owner(cls):
    return cls.owner

    @classmethod
    def set_owner(cls, name):
    cls.owner = name

    print(Animal.owner)
    Animal.set_owner('chenchen')
    print(Animal.owner)

  • 静态方法

    • 一个函数完全可以放到类外卖单独实现, 但是这个函数和类有一定的逻辑关系, 放入类中更好理解, 更好组织代码理解, 这种情况适用静态方法

      #!/usr/bin/env python3

      class Animal(object):
      owner = 'xxx'
      def __init__(self, name):
      self.name = name

      @staticmethod
      def order_animal_food():
      print('111')
      print('ok')

      Animal.order_animal_food()

  • 魔术方法

    # 例如
    __init__
    __new__
    __del__


Python 高级特性

  • 装饰器

    • 装饰器是给现有的模块增添新的小功能,可以对原函数进行功能扩展,而且还不需要修改原函数的内容,也不需要修改原函数的调用

  • 迭代器

    • 对于python中的对象, 只要它定义了可以返回一个迭代器的 __iter__ 方法后, 或者定义了可以支持下表索引的 __getitem__ 方法, 那么它就是一个可迭代对象, 对可迭代对象使用 __iter__ 方法后, 会返回一个迭代器

      # 这是一个普通列表(不是迭代器)
      lst = [10, 20, 30]

      # 把它变成迭代器
      it = iter(lst) # 相当于售票员开始上班

      print(next(it)) # 10
      print(next(it)) # 20
      print(next(it)) # 30
      # print(next(it)) # 再要 → StopIteration(报错)

      # ————————————

      # for循环其实偷偷帮你做了这三件事:
      # 1. it = iter(可迭代对象)
      # 2. while True:
      # 3. try: x = next(it)
      # 4. except StopIteration: break

  • 生成器 (迭代器)

    • 在python中, 一边迭代 (循环) 一边计算的机制, 称为生成器, 生成器能够迭代的关键是因为他有一个 __next__ 方法

      # 普通函数:一次性全做完
      def 全部数字():
      result = []
      for i in range(1, 1000001):
      result.append(i)
      return result

      # —————————————-

      # 生成器:超级懒,一次给一个
      def 懒惰数字():
      for i in range(1, 1000001):
      yield i # “给你一个,暂停,等你再来要”

    • 使用 yield 编写生成器 (构造斐波那契数列生成器)

      #!/usr/bin/env python

      def fib(n):
      current = 0
      a, b = 1, 1
      while current < n:
      yield a
      a, b = b, a + b
      current += 1

      f5 = fib(5)

      for i in f5:
      print(i)

  • 高阶函数

    • 接收函数作为参数的函数

      • 常见

        def process_numbers(numbers, operation):
        result = []
        for num in numbers:
        result.append(operation(num))
        return result

        def square(x):
        return x * x

        def double(x):
        return x * 2

        def make_negative(x):
        return x

        nums = [1, 4, 3, 7]

        print(process_numbers(nums, square)) # [1, 16, 9, 49]
        print(process_numbers(nums, double)) # [2, 8, -6, 14]
        print(process_numbers(nums, make_negative)) # [-1, -4, 3, -7]

      • 更高级

        numbers = [5, 2, 8, 1, 10, 3]

        # map:对每个元素都应用函数
        squared = list(map(square, numbers))
        print(squared) # [25, 4, 64, 1, 100, 9]

        # filter:保留函数返回 True 的元素
        positives = list(filter(lambda x: x > 0, numbers))
        print(positives) # [5, 8, 10, 3]

        # sorted:可以自定义排序规则
        words = ["apple", "banana", "kiwi", "dragonfruit"]
        sorted_by_length = sorted(words, key=len)
        print(sorted_by_length) # ['kiwi', 'apple', 'banana', 'dragonfruit']

  • 匿名函数

    • 这类函数没有函数名, 这个特点的好处是避免自定义变量名冲突, 减少代码量, 使代码结构更加紧凑, 缺点是不可重复使用

    • lambda

      double = lambda x: x * 2
      double(2)

      b = [1, 2 , 4, 1, 13]
      list(map(lamba i: i ** 2, b))

  • 偏函数

    • 是python的functools模块提供的一个很有用的功能

    • 简单总结functools.partial的作用就是把一个函数的某些参数给固定住 (也就是设置默认值), 返回一个新的函数, 调用这个新函数会更简单

      def at_will(i, m):
      return i ** m
      at_will(2, 4)

      def at_will(i, m = 2):
      return i ** m
      at_will(2, 3) ## 得到 8
      at_will(2) ## 得到 4

      # 偏函数
      from fuctools import partial
      at_will4 = partial(at_will, m = 4)
      at_will4(3)
      at_will4(3, m = 2)

  • 切片 (slice)

    • 在pytohn中, 切片是对序列化对象 (如list, string, tuple) 的一种高级索引方法, 普通索引只取出序列中的一个下标对应的元素, 而切片取出序列中一个范围对应的元素, 这里的范围不是狭义上的连续片段

      letters = ['a', 'b', 'c', 'd']
      letters[1, 3]
      letters[1, 1]
      letters[:3]
      letters[1:]

  • 列表解析式

    • Python的强大特性之一, 是其对 list 的解析, 它提供一种紧凑的方法, 可以通过对 list 中的每一个元素应用函数, 从而将一个 list 映射为另一个 list

    • Python2.x 添加的特性

      numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

      # 求偶数
      [x for x in numbers if x % 2 == 0] ## [2, 4, 6, 8, 10]

      # 求平方
      [x * x for x in numbers] ## [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

      # 结合前面的高阶函数之filter
      f = filter(lambda x: x % 2 == 0, numbers)
      list(f)

      # 字典
      d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
      {k: x * x for k, x in d.items()} ## 字典是不能被迭代的

  • 元组拆包

    • 将元组内的每个元素按照位置, 对应的值赋给不同变量

    • Python 函数 return 多个对象, 默认就是以 tuple 形式返回

    • 特殊格式用 * 达到拆包的目的

    • 作用

      • 变量赋值
      • 变量值交换
      • 函数参数赋值
      • 获取元组中特定位置的元素值等

      t = ('xiaoming', 18)
      print('I am {}, I am {} years old.' . format(*t))
      ## I am xiaoming, I am 18 years old.


赞(0)
未经允许不得转载:171主机测评 » 第九章:Python渗透与安全自动化实战指南 (上)
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址