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
注意:以上脚本只是初步调试成功,可以此为基础添加需要的功能
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值