- Go to the Google APIs Console and create a project when prompted. (It doesn’t matter if you choose an organization or not.)
- If unprompted, click the dropdown menu in the top left corner to select a project. In the top right corner of the popup, click New Project.
- Click the hamburger menu icon on the left and select "APIs & Services". (This is the APIs & Services Dashboard.)
- Click Enable APIs and Services. Search for and enable the Google Drive and Google Sheets APIs.
- Return to the APIs & Services Dashboard.
- Click Credentials on the left side bar and then click Create Credentials, in the dropdown, select Service account.
- Name it whatever you want, set some reasonable account ID, and you don't have to put a description. Then click Create and Continue.
- When you get a dropdown to "Select a role", scroll down and click on "Project" on the left side and then select "Editor" on the right hand side. Click Continue.
- You don't need to grant users access to the service. Simply click Done to continue
- You'll be returned to the API Credentials screen. Click on the Manage service accounts text link.
- Click the three dots (options) on the right under "Actions" column and select Manage keys.
- Press Add Key and then select "Create new key", then select JSON key type and click Create. It’ll download automatically.
- Now go to your target machine/VM and copy the JSON file into a file called
health_log_creds.json
- Open the JSON file and copy the
client_email
field. Now create a Google Sheets document and share it with this email, giving it Editing permissions. - Download
pip3
for Python
sudo apt update
sudo apt install python3-pip
- Download the
gspread
andoauth2client
Python libraries
pip3 install gspread oauth2client
- Copy the following code into your Python health script.
#!/usr/bin/python3
import gspread
from oauth2client.service_account import ServiceAccountCredentials
# use creds to create a client to interact with the Google Drive and Google Sheets API
scope = [
"https://spreadsheets.google.com/feeds",
'https://www.googleapis.com/auth/spreadsheets',
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/drive"
]
creds = gspread.service_account(filename='<FULL PATH TO FILE>/health_log_creds.json')
# Put the name of your spreadsheet here
sheet = creds.open("<NAME OF SPREADSHEET>").sheet1
# Example of how to insert a row
row = ["I'm","inserting","a","row","into","a,","Spreadsheet","with","Python"]
index = 1
sheet.insert_row(row, index)
# Example of how to delete a row. This deletes the first row.
#sheet.delete_rows(1)
# Example of how to update a single cell
#sheet.update_cell(1, 1, "Update top left cell")
# How to get the number of rows in the spreadsheet
#sheet.row_count
- Give the Python script executable permissions and run it as a test.
- Check your Google Sheets document to see it updated!
- Modify the Python script as necessary to fit your needs.