Fabric - 通过env.gateway检测主机操作系统信息

时间:2017-12-20 20:26:01

标签: python google-cloud-platform fabric

  select t.order_id
  from ( 
        Select OI.order_ID, S.product_ID, S.supplier_ID
        from Orders_Items OI 
        INNER JOIN Supplies S on OI.product_ID=S.product_ID
        group by OI.order_ID, S.product_ID, S.supplier_ID) t
  group by t.order_id, t.supplier_ID
  having count(distinct t.product_id) >= 3

以上代码获取堡垒主机#! /usr/bin/env python # -*- coding: utf-8 -*- from fabric.api import env, run, sudo, task from googleapiclient.discovery import build from oauth2client.client import GoogleCredentials credentials = GoogleCredentials.get_application_default() compute = build('compute', 'v1', credentials=credentials) # sets static project # project = 'test1' env.key_filename = 'google_compute_engine' forward_agent = True @task # gets bastion host and sets env.gateway to be used as ssh gateway def ag_get_bh(project): request = compute.instances().aggregatedList(project=project) response = request.execute() for zone, instances in response['items'].items(): for host in instances.get("instances", []): if host['status'] == 'RUNNING': if 'bh' in host['name']: env.gateway = host['networkInterfaces'][0]['accessConfigs'][0]['natIP'] else: print('No bastion host found') @task # gets running hosts in a single project across all zones def ag_get_host(project): request = compute.instances().aggregatedList(project=project) response = request.execute() env.hosts = [] for zone, instances in response['items'].items(): for host in instances.get("instances", []): if host['status'] == 'RUNNING': env.hosts.append(host['name']) @task # identifies OS platform to be used in sec_update() def get_platform(): x = sudo("python -c 'import platform; print(platform.platform())'") if x.failed: raise Exception("Python not installed") else: return x print(x) @task # runs security updates def sec_update(): if 'redhat' or 'centos' in get_platform().lower(): sudo('echo 3 > /proc/sys/vm/drop_caches') sudo('yum -y --disablerepo=rhui* install google-rhui-client-rhel7') sudo('yum update yum -y') sudo('yum update-minimal --security -y') elif 'ubuntu' or 'debian' in get_platform().lower(): sudo('apt-get install unattended-upgrades') sudo('unattended-upgrades –v') ,然后它从GCP API获取主机并设置env.gateway,然后检查主机操作系统,然后应用安全更新。

仅当通过ssh代理(env.hostsenv.gateway运行脚本时才会运行,因此sec_updates中的if语句永远不会执行,因此我的操作系统特定逻辑永远不会执行。在本地运行时,(不使用get_platform()env.gateway正确执行。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

不完全确定这里发生了什么,但我最终复制并粘贴了另一个正在运行且代码正确执行的备份文件中的脚本。如果有人有兴趣,下面是工作脚本:

#!  /usr/bin/env python
# -*- coding: utf-8 -*-

from fabric.api import env, run, sudo, task
from googleapiclient.discovery import build
from oauth2client.client import GoogleCredentials

credentials = GoogleCredentials.get_application_default()
compute = build('compute', 'v1', credentials=credentials)

# set to path of private key
env.key_filename = 'google_compute_engine'
forward_agent = True


@task
# gets bastion host and sets env.gateway to be used as ssh gateway
def ag_get_bh(project):
    request = compute.instances().aggregatedList(project=project)
    response = request.execute()

    for zone, instances in response['items'].items():
        for host in instances.get("instances", []):
            if host['status'] == 'RUNNING':
                if 'bh' in host['name']:
                    env.gateway = host['networkInterfaces'][0]['accessConfigs'][0]['natIP']
            else:
                print('No bastion host found')


@task
# gets running hosts in a single project across all zones
def ag_get_host(project):
    request = compute.instances().aggregatedList(project=project)
    response = request.execute()

    env.hosts = []
    for zone, instances in response['items'].items():
        for host in instances.get("instances", []):
            if host['status'] == 'RUNNING':
                env.hosts.append(host['name'])


@task
# gets uptime
def uptime():
    run('uptime')


@task
# gets disk space
def disk_space():
    run('df -h')


# gets OS platform to be used in sec_update()
def get_platform():
    x = sudo("python -c 'import platform; print(platform.platform())'")
    if x.failed:
        raise Exception("Python not installed")
    else:
        return x

@task
# runs OS security updates
def sec_update():
    if 'redhat' in get_platform().lower():
        sudo('echo 3 > /proc/sys/vm/drop_caches')
        sudo('yum -y --disablerepo=rhui* install google-rhui-client-rhel7')
        sudo('yum update yum -y')
        sudo('yum update-minimal --security -y')
    elif 'centos' in get_platform().lower():
        sudo('echo 3 > /proc/sys/vm/drop_caches')
        sudo('yum update yum -y')
        sudo('yum update-minimal --security -y')
    elif 'ubuntu' or 'debian' in get_platform().lower():
        sudo('apt-get install unattended-upgrades')
        sudo('unattended-upgrades -v')
    else:
        print("No supported OS found")