Installing Google Chrome on a Google Cloud VM (such as a Compute Engine instance) using Python involves automating the execution of shell commands that download and install the Chrome browser. Below, I'll guide you through the process for both Ubuntu/Debian-based and Windows-based VMs.
Prerequisites
-
Google Cloud VM Instance: Ensure you have a running VM instance on Google Cloud Platform (GCP). You can use either an Ubuntu/Debian-based or Windows-based instance.
-
Python Installed: The VM should have Python installed. Most Linux distributions come with Python pre-installed. For Windows, you might need to install it manually.
-
Access Permissions: Ensure you have the necessary permissions to install software on the VM. You might need sudo privileges on Linux.
For Ubuntu/Debian-Based Linux VMs
Step 1: Create the Python Script
Create a Python script (e.g., install_chrome.py) with the following content:
import subprocess
import sys
def run_command(command):
"""
Executes a shell command and streams the output in real-time.
"""
process = subprocess.Popen(
command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True
)
for line in process.stdout:
print(line, end='')
process.wait()
if process.returncode != 0:
print(f"Error: Command failed -> {command}", file=sys.stderr)
sys.exit(process.returncode)
def install_google_chrome():
print("Updating package list...")
run_command("sudo apt-get update -y")
print("Installing dependencies (wget and gdebi)...")
run_command("sudo apt-get install -y wget gdebi-core")
print("Downloading Google Chrome...")
run_command(
"wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb"
)
print("Installing Google Chrome...")
run_command("sudo gdebi -n google-chrome-stable_current_amd64.deb")
print("Cleaning up...")
run_command("rm google-chrome-stable_current_amd64.deb")
print("Google Chrome installation completed successfully.")
if __name__ == "__main__":
install_google_chrome()
Step 2: Transfer the Script to Your VM
Use scp, gcloud, or any other method to transfer install_chrome.py to your VM. For example, using gcloud:
gcloud compute scp install_chrome.py your-vm-name:~
Step 3: Execute the Script
SSH into your VM:
gcloud compute ssh your-vm-name
Navigate to the directory containing the script and run it:
python3 install_chrome.py
Note: You might need to install Python 3 if it's not already installed.
Explanation of the Script
- Updating Package List: Ensures you have the latest package information.
- Installing Dependencies:
wget is used to download files, and gdebi handles .deb package installations, resolving dependencies automatically.
- Downloading Chrome: Fetches the latest stable
.deb package of Google Chrome.
- Installing Chrome: Installs the downloaded package.
- Cleanup: Removes the downloaded
.deb file to save space.
For Windows-Based VMs
Installing Chrome on a Windows VM using Python involves downloading the Chrome installer and executing it silently.
Step 1: Create the Python Script
Create a Python script (e.g., install_chrome_windows.py) with the following content:
import subprocess
import sys
import os
import urllib.request
def download_file(url, dest):
"""
Downloads a file from a URL to a destination path.
"""
print(f"Downloading from {url}...")
urllib.request.urlretrieve(url, dest)
print(f"Downloaded to {dest}.")
def run_command(command, shell=True):
"""
Runs a command on the shell.
"""
print(f"Executing: {command}")
result = subprocess.run(command, shell=shell)
if result.returncode != 0:
print(f"Error: Command failed -> {command}", file=sys.stderr)
sys.exit(result.returncode)
def install_google_chrome():
chrome_url = "https://dl.google.com/tag/s/appguid%3D%7B8A69D345-D564-463c-AFF1-A69D9E530F96%7D%26iid%3D%7B33A3E1E9-FE76-1234-5678-9ABCDEF01234%7D%26lang%3Den%26browser%3D4%26usagestats%3D0%26appname%3DGoogle%2520Chrome%26needsadmin%3Dprefers%26ap%3Dx64-stable-statsdef_1%26installdataindex%3Ddefaultbrowser/update2/installers/ChromeSetup.exe"
installer_path = os.path.join(os.getcwd(), "ChromeSetup.exe")
download_file(chrome_url, installer_path)
print("Running the Chrome installer silently...")
# /silent /install for silent installation
run_command(f'"{installer_path}" /silent /install')
print("Installation completed. Removing the installer...")
os.remove(installer_path)
print("Google Chrome installed successfully.")
if __name__ == "__main__":
install_google_chrome()
Step 2: Transfer the Script to Your VM
Use RDP, file sharing, or any other method to transfer install_chrome_windows.py to your Windows VM.
Step 3: Execute the Script
- Open Command Prompt as Administrator: Some installation steps require administrative privileges.
- Navigate to the Script Location:
cd path\to\your\script
- Run the Script:
python install_chrome_windows.py
Note: Ensure Python is installed on your Windows VM. You can download it from python.org.
Explanation of the Script
- Downloading Chrome Installer: Fetches the latest Chrome installer executable.
- Silent Installation: Runs the installer with flags (
/silent /install) to perform a background installation without user interaction.
- Cleanup: Deletes the installer after successful installation.
Additional Considerations
-
Headless Installation: If you're installing Chrome for automation purposes (e.g., using Selenium), consider installing Chrome in headless mode.
-
Environment Variables: Ensure that the installation paths are added to the system's PATH environment variable if needed.
-
Error Handling: The provided scripts have basic error handling. For production use, consider enhancing error checks and logging.
-
Security: Always verify the source URLs and ensure secure downloads. Consider using HTTPS links and validating file integrity if necessary.
-
Dependencies: Ensure all dependencies (like wget, gdebi on Linux) are properly installed before attempting to install Chrome.
By following the above instructions tailored to your VM's operating system, you can automate the installation of Google Chrome using Python on your Google Cloud VM.