给fabric增加API接口

自动化运维工具

有Ansible, Fabric, puppet 等,其中我选择了Fabric ,因为我觉得这个工具够简单。
这里有个支持Python3的fabric模块:https://github.com/mathiasertl/fabric

但是通过 fab.exe task 这样的命令行,感觉不好交互,如果有API的话,就可以很方便的跟其他项目集成在一起。

不知道fabric本身有没有提供,自己研究了一下安装好后的源码:

1)看文件名应该是从main.py 着手:

        if remainder_command:
            r = '<remainder>'
            #remainder_command 包含了要执行的命令
            #api.run 定义在operations.py文件,是一个用@needs_host装饰了的函数
            state.commands[r] = lambda: api.run(remainder_command)
            commands_to_run.append((r, [], {}, [], [], []))
        # Ditto for a default, if found
        if not commands_to_run and default:
            commands_to_run.append((default.name, [], {}, [], [], []))

        # Initial password prompt, if requested
        if options.initial_password_prompt:
            prompt = "Initial value for env.password: "
            state.env.password = getpass.getpass(prompt)

        # Ditto sudo_password
        if options.initial_sudo_password_prompt:
            prompt = "Initial value for env.sudo_password: "
            state.env.sudo_password = getpass.getpass(prompt)

        if state.output.debug:
            names = ", ".join(x[0] for x in commands_to_run)
            print("Commands to run: %s" % names)

        # At this point all commands must exist, so execute them in order.
        #除了name之外,其他参数几乎都是空,没用上
        #print打印,发现更多信息都是包含在state.env 这个字典上面
        for name, args, kwargs, arg_hosts, arg_roles, arg_exclude_hosts in commands_to_run:
        #execute 能返回一个字典,里面包含了执行结果,这正是我需要的。
            execute(
                name,
                hosts=arg_hosts,
                roles=arg_roles,
                exclude_hosts=arg_exclude_hosts,
                *args, **kwargs
            )
        # If we got here, no errors occurred, so print a final note.
        if state.output.status:

2)

我自己加了一个py文件:Python36\Lib\site-packages\fabric\simple_task.py

内容如下:

from fabric import api, state
from fabric.tasks import execute

def simple_execute(host, port, user, password, shell):
    r = '<remainder>'
    state.env.hosts  = host
    state.env.port = port
    state.env.user = user
    state.env.password = password
    state.commands[r] = lambda: api.run(shell)
    return execute(r)

3)结果如下:

150847_rkeb_214112.png

嗯,正好大概是我需要的效果!后面根据需要慢慢修改了,谢谢分享

转载于:https://my.oschina.net/huanghongqiao/blog/1556073

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值