I want to build a python program to automate the entire process from starting a VM instance to running a program on that instance. I understand that I need to use command line to SSH into the instance, but I’m not sure how to answer the yes/no questions or multiple choice questions using python. Is this possible?
# code
import google-api-client
# code
Yes, it is possible to automate the process using Python and the Google Cloud APIs. You can use the google-api-client
library to interact with the Compute Engine API and create, start, and stop VM instances. You can also use the paramiko
library to SSH into the instance and run commands. To answer yes/no questions or multiple choice questions, you can use the stdin
and stdout
streams of the SSH connection to send and receive data. Here’s an example of how to SSH into a VM instance using paramiko
:
import paramiko
# create SSH client
ssh = paramiko.SSHClient()
# automatically add host key
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# connect to instance
ssh.connect('instance-ip', username='username', key_filename='path/to/private/key')
# send command and receive output
stdin, stdout, stderr = ssh.exec_command('ls')
output = stdout.read().decode('utf-8')
# send data to stdin
stdin.write('yes\n')
stdin.flush()
# close SSH connection
ssh.close()