如何通过python3.6连接和访问Google云计算引擎VM

2024-05-23 13:53:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用python3.6访问Google云计算引擎VM,我需要执行普通的CLI操作,比如远程机器。在

我可以通过gcloud命令登录到VM实例,这个命令是在VM实例的页面中手动生成的,我可以使用googleapiclient.discoveryPython模块可以执行列表实例、创建实例和删除实例等操作。但是,我无法登录到虚拟机实例并访问,例如通过Python访问远程机器。在

请告诉我正确的API以访问VM实例。在


Tags: 模块实例引擎命令机器列表cli远程
1条回答
网友
1楼 · 发布于 2024-05-23 13:53:14

我将使用paramiko,一个Python第三方库。在

但首先在GCP端做一些简单的设置,只需粘贴您想要连接的机器的公共ssh密钥,这是documentation,并获取您想要连接的Google计算引擎(GCE)实例的外部IP地址。在

然后:

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()

相关问题 更多 >