问题描述
我正在尝试从python中的标准输出中获取值。这是我从命令行运行的命令,用于列出GKE群集中的防火墙。
gcloud compute firewall-rules list \
--project <myproject> \
--filter="name~gke-cluster-123456789*"
在堡垒服务器上执行命令时,输出如下:
NAME NETWORK DIRECTION PRIORITY ALLOW DENY disABLED
gke-cluster-XXX-all default INGRESS 1000 tcp,udp,XXX False
gke-cluster-XXX-ssh default INGRESS 1000 tcp:XX False
gke-cluster-XXX-vms default INGRESS 1000 icmp,tcp:1-XXXXX,udp:1-XXXXX False
我需要在python中做同样的事情,但只获取名称字段。但是,下面的代码将获取防火墙名称以及 NAME 标签。
我的部分代码
cmd = gcloud compute firewall-rules list --project <myproject> --filter="name~gke-cluster-123456789*"
stdin,stdout,stderr = ssh.exec_command(cmd)
for line in stdout.read().splitlines():
print(line.split()[0])
实际输出:
NAME
gke-cluster-XXX-all
gke-cluster-XXX-ssh
gke-cluster-XXX-vms
预期的输出:(我需要的是)
gke-cluster-XXX-all
gke-cluster-XXX-ssh
gke-cluster-XXX-vms
解决方法
for index,line in enumerate(text.splitlines()):
if index != 0:
print(line.split()[0])
,
您可以单独使用gcloud进行此操作:
gcloud compute firewall-rules list \
--filter=${FILTER} \
--format="value[no-heading](name)" \
--project=${PROJECT}
请参阅:https://cloud.google.com/sdk/gcloud/reference/topic/formats
,为完整起见,您还可以在bash命令行中处理跳行:
python <script> | tail -n +2