How to connect and access Google Cloud Compute Engine VM via Python 3.6

懵懂的女人 提交于 2020-01-30 04:04:51

问题


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.

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.

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


回答1:


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

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.

Then:

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


来源:https://stackoverflow.com/questions/55393887/how-to-connect-and-access-google-cloud-compute-engine-vm-via-python-3-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!