首页 > 解决方案 > 从python执行时如何抑制gcloud连接关闭警告

问题描述

def instance_list():
instances_list = "gcloud compute instances list --format='json(name, status, zone)' --filter='(status=running)' --project reference-ether-853"
instance_output_json = json.loads(subprocess.check_output(shlex.split(instances_list)))
# instance_output_table = "gcloud compute instances list --format='table(name, status, zone)' --filter='(status=running)' --project reference-ether-853"
# result = subprocess.check_output(shlex.split(instance_output_table))
for instance_row in instance_output_json:
    instance_name = instance_row['name']
    instance_status = instance_row['status']
    instance_zone = instance_row['zone'].rsplit("/")[-1]
    if instance_name.startswith('ci-') and instance_status == 'RUNNING':
        uptime = "gcloud compute ssh --zone {} {} --ssh-flag='-t' -- command 'uptime'".format(instance_zone,
                                                                                              instance_name)
        instances_up = subprocess.check_output(shlex.split(uptime))
        print(instance_name, instance_zone)

执行输出时返回为

instanceName us-east1-b 与 31.196.126.66 的连接已关闭。

我想禁止“与 31.196.126.66 的连接已关闭”。并仅打印实例名称和区域。

标签: pythongoogle-cloud-platformgcloud

解决方案


我认为如果没有以下内容,您将无法做到这一点:

gcloud compute ssh --zone {} {} --ssh-flag='-t' --command 'uptime' 2>&1 \
| head --lines=1

gcloud compute ssh是您机器ssh命令的包装器,因此您必须求助于解析 stdout|stderr。

我没有使用 Python 尝试过这个,subprocess但你应该明确地管理管道(即你需要两个命令和subprocess.PIPE

从编程语言编写 shell 命令通常是不优雅的,因为正如您所体验的那样,很难“键入”输出以便例如解析它,处理错误。

通常最好使用 Google 提供的库之一(可用于多种语言的每种服务)与 Python 中的 Compute Engine 等服务进行交互。

看:

https://cloud.google.com/compute/docs/tutorials/python-guide

但是 (:-)),在这种情况下,替代方案相当具有挑战性。

IIUC,您无法从 Compute Engine API 获取实例的正常运行时间测量值,但需要使用监控指标(uptime或者uptime_total,我不确定区别)。

我鼓励您考虑用gcloud compute instances list等效的 API 方法替换 shell 命令。请参阅 Google APIs Explorer 上的示例:

https://cloud.google.com/compute/docs/reference/rest/v1/instances/list#examples


推荐阅读