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

标签 python google-compute-engine

我正在使用 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)

关于python - 如何使用 Python 在 Google Compute Engine 中打开特定端口,例如 9090,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48418457/

相关文章:

python - 如何用monkeypatch替换常量

google-compute-engine - 如何从计算引擎访问谷歌驱动器

kubernetes - 更改Kubernetes实例模板以打开HTTPS端口

ssh - Google 计算引擎 - 访问 SSH 几次后被阻止

python - 删除已保存图像周围的空白

python - 分配许多简单网络任务的解决方案?

python - 无法从 'Bootstrap5' 导入名称 'flask_bootstrap' ?

python - 为什么 OOP 版本中的小部件会重叠

google-cloud-platform - 为什么我的谷歌云平台显示流量?

google-compute-engine - 每个区域 24 的 CPUS 配额。是否每个区域分配 8 个?