2017-01-25 74 views
2

我有一個小布腳本改變服務器的IP:如何更改計算機IP地址與Fabric沒有掛?

from cStringIO import StringIO 
import os 

import fabric 
import fabric.api 
import jinja2 

fabric.state.env['hosts'] = '10.1.0.4' 

def render(tpl_path, context): 
    path, filename = os.path.split(tpl_path) 
    template_stream = jinja2.Environment(loader=jinja2.FileSystemLoader(path or './')).get_template(filename).stream(context) 
    output_stream = StringIO() 
    for chunk in template_stream: 
     output_stream.write(chunk) 
    return output_stream 

def change_ip(): 
    ifcfg_ens192 = render("ifcfg.j2", { 
     "device": "ens192", 
     "ip_address": "10.1.0.20", 
     "prefix": "24" 
    }) 

    fabric.operations.put(ifcfg_ens192, "/etc/sysconfig/network-scripts/ifcfg-ens192", use_sudo=True, mirror_local_mode=True) 

    fabric.operations.sudo("service network restart") 

fabric.tasks.execute(change_ip) 

不幸的是,當IP地址發生變化時,織物下面的輸出掛起。

[10.1.0.4] Executing task 'change_ip' 
[10.1.0.4] Login password for 'root': 
[10.1.0.4] put: <file obj> -> /etc/sysconfig/network-scripts/ifcfg-ens192 
[10.1.0.4] sudo: service network restart 
[10.1.0.4] out: Restarting network (via systemctl): 

我想在更改IP任務後執行其他任務。有沒有解決這個問題的好方法?

回答

0

下面的腳本似乎做的伎倆:

from cStringIO import StringIO 
import os 

import fabric 
import fabric.api 
import jinja2 

change_host = '10.1.0.4' 
change_to = '10.1.0.20' 

fabric.state.env['hosts'] = [change_host] 
fabric.state.env['user'] = 'user' 

def render(tpl_path, context): 
    path, filename = os.path.split(tpl_path) 
    template_stream = jinja2.Environment(loader=jinja2.FileSystemLoader(path or './')).get_template(filename).stream(context) 
    output_stream = StringIO() 
    for chunk in template_stream: 
     output_stream.write(chunk) 
    return output_stream 

def change_ip(): 
    ifcfg_ens192 = render("ifcfg.j2", { 
     "device": "ens192", 
     "ip_address": change_to, 
     "prefix": "24" 
    }) 

    fabric.operations.put(ifcfg_ens192, "/etc/sysconfig/network-scripts/ifcfg-ens192", use_sudo=True, mirror_local_mode=True) 

    try: 
     fabric.operations.sudo("service network restart", timeout=0.5) 
    except fabric.exceptions.CommandTimeout: 
     pass 

    fabric.state.env['hosts'] = [change_to] 

def test_task(): 
    fabric.operations.run("echo 'hi'") 

它運行使用下面的命令:fab -f fabfile.py change_ip test_task

,併產生下列輸出:

[10.1.0.4] Executing task 'change_ip' 
[10.1.0.4] Login password for 'user': 
[10.1.0.4] put: <file obj> -> /etc/sysconfig/network-scripts/ifcfg-ens192 
[10.1.0.4] sudo: service network restart 
[10.1.0.4] out: sudo password: 
[10.1.0.4] out: Restarting network (via systemctl): [10.1.0.20] Executing task 'test_task' 
[10.1.0.20] run: echo 'hi' 
[10.1.0.20] out: hi 
[10.1.0.20] out: 
相關問題