首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何通过Python 3.6连接和访问Google Cloud Compute Engine虚拟机

如何通过Python 3.6连接和访问Google Cloud Compute Engine虚拟机
EN

Stack Overflow用户
提问于 2019-03-28 17:15:09
回答 1查看 1.3K关注 0票数 0

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

我可以通过手动在VM实例页面中生成的gcloud命令登录到VM实例,还可以使用googleapiclient.discovery Python模块进行列出实例、创建实例和删除实例等操作。但是,我无法登录到VM实例并进行访问,例如,通过Python访问远程计算机。

请指引我使用正确的API来访问虚拟机实例。

EN

回答 1

Stack Overflow用户

发布于 2019-03-29 01:20:05

我会使用paramiko,这是一个Python第三方库。

但是首先,您需要在gcp端进行一些简单的设置,只需粘贴您想要连接的机器的公共ssh密钥,这是documentation,并获取您想要连接到的Google Compute Engine (GCE)实例的外部IP地址。

然后:

代码语言:javascript
复制
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()
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55393887

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档