python 读取yml实现shell指令

python 脚本

#!/usr/bin/python2.7
#coding=utf-8
#author wusheng

import yaml
import json
import os

f = open('/opt/dockerfile/handle.yml')
x = yaml.load(f) #[{'gather_facts': False, 'tasks': [{'cp': {'dest': '/etc/bbb', 'src': '/root/aaa'}, 'name': 'Copy a file to another'}, {'mv': {'dest': '/etc/ddd', 'src': '/root/ccc'}, 'name': 'Mv a file to another'}], 'hosts': 'all'}]
#json = json.dumps(x)
#print(x) #[{'gather_facts': False, 'tasks': [{'cp': {'dest': '/etc/bbb', 'src': '/root/aaa'}, 'name': 'Copy a file to another'}], 'hosts': 'all'}]
#print(json) #[{"gather_facts": false, "tasks": [{"cp": {"dest": "/etc/bbb", "src": "/root/aaa"}, "name": "Copy a file to another"}], "hosts": "all"}] 
#print x #[{'gather_facts': False, 'tasks': [{'cp': {'dest': '/etc/bbb', 'src': '/root/aaa'}, 'name': 'Copy a file to another'}, {'mv': {'dest': '/etc/ddd', 'src': '/root/ccc'}, 'name': 'Mv a file to another'}], 'hosts': 'all'}]

#dest = x[0]['tasks'][0]['cp']['dest']
#src = x[0]['tasks'][0]['cp']['src']

#print(dest)
#print(src)

len_dic=len(x[0]['tasks']) #读取list长度用于以下循环取value和key
dic=x[0]['tasks'] #读取tasks下的json
for i in range(0,len_dic):
        operate=dic[i].keys()[0]
        dest=dic[i].values()[0]['dest'] #/etc/bbb 
        src=dic[i].values()[0]['src'] #/root/aaa
        print("----------------")
        result=str(operate) +" "+ str(src) +" "+ str(dest)
        os.system(result)

yml

---
- hosts: all
  gather_facts: no
  tasks:
  - name: Copy a file to another
    cp:
      src: /root/aaaa
      dest: /etc/bbba

  - name: Mv a file to another
    mv:
      src: /root/cccc
      dest: /etc/dddd

注意:以上脚本只是初步调试成功,可以此为基础添加需要的功能

你可能感兴趣的:(个人学习,个人学习,python,ansible,yml)