如何通过Python 3.6连接和访问Google Cloud Compute Engine VM [英] How to connect and access Google Cloud Compute Engine VM via Python 3.6

查看:300
本文介绍了如何通过Python 3.6连接和访问Google Cloud Compute Engine VM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Python 3.6访问Google Cloud Compute Engine VM,并且需要执行正常的CLI操作,例如远程计算机.

I want to access the Google Cloud Compute Engine VM using Python 3.6 and I need to perform normal CLI actions like remote machine.

我能够通过gcloud命令登录到VM实例,该命令是在VM实例页面上手动生成的,并且我能够使用googleapiclient.discovery Python模块执行一些操作,例如列表实例,创建实例和删除实例.但是,我无法登录到VM实例并进行访问,例如就像通过Python的远程计算机一样.

I am able to login to the VM instance via gcloud command, which is produced in VM instance's page manually, and I am able to use googleapiclient.discovery Python module to do some operations like list instances, create instances and delete instances. But, I am not able to login to the VM instance and access, e.g. like remote machine via Python.

请引导我使用正确的API来访问VM实例.

Please direct me to the correct API to access the VM instance.

推荐答案

我会使用 paramiko ,一个Python第三方库.

I'd use paramiko, a Python third party library.

但是首先,您需要在GCP端进行一些简单的设置,只需粘贴要连接的计算机的公共ssh密钥,这是

But first you've some simple setup to do on GCP side, just paste the public ssh key of the machine you want to connect from, here's the documentation, and grab the external IP address of the Google Compute Engine (GCE) instance you want to connect to.

然后:

import paramiko

#edit the following line please
username, hostname = "YOUR_USERNAME@EXTERNAL_IP_ADDRESS".split("@") 

client = paramiko.SSHClient()

#edit the following line also, with the path to the private ssh key (correspondent to the public one you've registered with your GCE instance)
key_filename=""
#on cloud shell would be something like /home/YOUR_USERNAME/.ssh/google_compute_engine

c = client.connect(username=username, hostname=hostname, key_filename=key_filename)

stdin, stdout, stderr = client.exec_command("cat /etc/os-release") #assuming is linux

print(stdout.read().decode())

client.close()

这篇关于如何通过Python 3.6连接和访问Google Cloud Compute Engine VM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆