我正在使用Python与Google Compute Engine进行交互。我可以直接使用Python创建/停止机器。为此,我使用了sample code from GoogleCloudPlatform,它工作得很好。
现在,我想打开一些端口,以便使用Python API与外部世界的机器进行交互。
这个相关的问题已经告诉了how to open a specific port from Google console web and gcloud command,所以我的问题特别是如何使用Python API来实现它。
发布于 2019-10-24 00:12:15
以下是一些示例代码,可以帮助您入门,但我建议您查看计算API的entire firewalls portion,以确保您使用了所需的所有选项:
这在使用应用程序默认凭据的云shell上成功运行。您可能需要authenticate in a different way。
import googleapiclient.discovery
if __name__ == '__main__':
MY_PROJECT = 'your-project-name'
# Get the firewalls resource
firewalls = googleapiclient.discovery.build('compute', 'v1').firewalls()
# Build the REST parameters for a port 9090 ingress allow-all firewall.
firewall_definition = {
"name": "default-allow-9090",
"direction": "INGRESS",
# targetTags: "add tags here if you need them -- default is apply to all",
"sourceRanges" : "0.0.0.0/0",
"allowed": { "IPProtocol": "tcp", "ports": [ 9090 ] },
"priority": 1000,
"network": "https://www.googleapis.com/compute/v1/projects/%s/global/networks/default" % MY_PROJECT,
}
# Execute the call.
result = firewalls.insert(project=MY_PROJECT, body=firewall_definition).execute()
# View Response
print(result)
https://stackoverflow.com/questions/48418457
复制相似问题