zoukankan      html  css  js  c++  java
  • Fabric实例

    参考《Python自动化运维 技术与最佳实践》
     

    1:查看本地与远程主机信息

    #!/usr/bin/python
    from fabric.api import *
    
    env.user="lile"
    env.hosts=['10.0.0.145','10.0.0.147']
    env.password="123456"
    
    #@runs_once
    def local_task():
        local('uname -r')
    def remote_task():
        with cd("/tmp"):
            run("ls")
    with 的作用是让后面的表达式的语句继承当前状态,实现“cd /tmp && ls”的效果
    上面的remote_task也可表示为:
    def remote_task():
          run("cd /tmp" && ls)
     
    2:动态的获取远程目录列表
    #!/usr/bin/python
    from fabric.api import *
    
    env.user="lile"
    env.hosts=['10.0.0.145','10.0.0.147']
    env.password='123456'
    
    @runs_once
    def input_raw():
        return prompt("please input directory name:",default="/home")
    
    def worktask(dirname):
        run("ls " + dirname)
    
    @task
    def go():
        getdirname = input_raw()
        worktask(getdirname)
     
    prompt 表示获取用户的信息
    @task 函数修饰符,表示只有函数标记了,才为fab可调用,非标记的不可用
     
     若注释掉@task,三个都可见
     
    执行结果为:
     这里的@runs_once表示只要输入一个,然后所有的主机都是查看这个路径下的东西,画红圈圈的[10.0.0.145]可以不用管。
     
    3:上传tomcat,并解压,通过堡垒机的形式
    #!/usr/bin/python
    from fabric.api import *
    from fabric.context_managers import *
    from fabric.contrib.console import confirm
    
    env.user="root"
    env.gateway="10.0.0.12"
    env.hosts=['10.0.0.145','10.0.0.147']
    env.passwords={
        'root@10.0.0.12:22':'root123456',
        'root@10.0.0.145:22':'123456',
        'root@10.0.0.147:22':'123456'
    }
    
    lpath="/fabric/5/apache-tomcat-8.5.12.tar.gz"
    rpath="/tmp/install"
    
    @task
    def put_task():
        run('mkdir -p /tmp/install')
        with settings(warn_only=True):
            result = put(lpath,rpath)
        if result.failed and not confirm("put file failed,Continue[Y/N]?"):
            abort("Aborting file put task!")
    
    @task
    def tar():
        with cd("/tmp/install"):
            run("tar -zxvf apache-tomcat-8.5.12.tar.gz")
    
    @task
    def go():
        put_task()
        tar()
     
    这里是通过堡垒机的形式上传本地文件,文件不是放在堡垒机上,而是放在执行此脚本的本地机器上
    env.gateway:定义网关IP(也就是中转,堡垒机IP)
    env.passwords:设置密码,但是需要设置账户,主机,端口等信息
     
  • 相关阅读:
    Tensorflow 学习
    几种常见损失函数
    两人比赛先选后选谁获胜系列的动态规划问题
    LeetCode 全解(bug free 训练)
    局部敏感哈希LSH
    Annoy解析
    MCMC例子
    TinyBERT简单note
    ALBERT简单note
    求根号2, 网易的一道面试题
  • 原文地址:https://www.cnblogs.com/lemon-le/p/6934576.html
Copyright © 2011-2022 走看看