Skip to main content
 首页 » 编程设计

python之如何使用 Python 在 Google Compute Engine 中打开特定端口,例如 9090

2025年01月19日10mengfanrong

我正在使用 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 来完成。

请您参考如下方法:

这里有一些示例代码可以帮助您入门,但我建议您查看 entire firewalls portion计算 API 以确保您使用所需的所有选项:

这在使用应用程序默认凭据的云外壳上成功运行。您可能需要 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)