load()并不安全

原理在于加载用户提供的字符串可能带来风险,例如:

!!python/object/apply:os.system
args: ['ls /']

print(yaml.load(open('a.yaml'))) 会返回:

bin   etc   lib    lost+found  opt   root  sbin  tmp  var sys
boot  dev   efi    home        lib64 mnt   proc  run  srv usr
0

如果传入rf -rm 之类的命令后果不堪设想,因此务必采用安全加载

safe_load() 参考

#!/usr/bin/env python

import yaml

with open("example.yaml", "r") as stream:
    try:
        print(yaml.safe_load(stream))
    except yaml.YAMLError as exc:
        print(exc)