![](/img/trans.png)
[英]How to enable the Google Compute Engine API using python APIs
[英]How to open a specific port such as 9090 in Google Compute Engine using Python
我正在使用Python与Google Compute Engine进行交互。 我可以直接使用Python创建/停止计算机。 为此,我使用了GoogleCloudPlatform的示例代码 ,它运行正常。
现在,我想打开一些端口,以便使用Python API与外界的机器进行交互。
这个相关的问题已经说明了如何通过Google控制台Web和gcloud命令打开特定端口 ,所以我的问题特别是如何使用Python API进行操作。
以下是一些示例代码,可以帮助您入门,但是我建议您检查一下计算API的整个防火墙部分 ,以确保使用所需的所有选项:
这可以在使用应用程序默认凭据的云外壳上成功运行。 您可能需要以其他方式进行身份验证 。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.