python - 从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 的连接已关闭”。并仅打印实例名称和区域。
解决方案
我认为如果没有以下内容,您将无法做到这一点:
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
推荐阅读
- javascript - 带有“remote: true”的表单即使使用重定向也会返回 200 响应
- java - 对象中列表的 Lambda
- python-3.x - 使用 Mikrotik API 脚本登录后如何修复卡住?
- google-sheets - 如何附加到电子表格中的工作表
- docker - 命令 eval $(minikube docker-env) 不起作用,因为错误提示“无法连接到 docker daemon”
- excel - 仅在适用的情况下显示项目描述——如何在 Excel 中没有多个嵌套 IF 函数的情况下做到这一点?
- regex - 打击点。在组 []
- mysql - 存储过程问题无法正常工作
- python - 如何在 Python 中使用此错误处理?
- elasticsearch - Elasticsearch 地理查询显示没有结果