【问题标题】:How to suppress gcloud connection closed warning when executed from python从python执行时如何抑制gcloud连接关闭警告
【发布时间】:2021-04-08 15:27:12
【问题描述】:
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)

执行时输出返回为

实例名称 us-east1-b 与 31.196.126.66 的连接已关闭。

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

【问题讨论】:

    标签: python google-cloud-platform gcloud


    【解决方案1】:

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

    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 or uptime_total,我不确定其中的区别)。

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

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

    【讨论】:

      猜你喜欢
      • 2014-07-16
      • 1970-01-01
      • 2020-10-08
      • 1970-01-01
      • 1970-01-01
      • 2016-04-20
      • 1970-01-01
      • 2018-03-03
      • 2019-05-08
      相关资源
      最近更新 更多