close

引用網址:https://medium.com/@ianhutch90/google-drive-file-upload-using-the-terminal-3652ee90a6f6

 

In this article, I share with you a solution that authenticates a user to upload file data to a Google Drive repository. If you are interested in knowing how to do it, continue reading to find out.

Before we begin I would like to draw your attention to the following resources I stole. I mean borrowed from that were very helpful.

The first author is Daniel Ellis and the second author is Athiththan Kathirgamasegaran.

Prerequisite

  1. Your Google account has been signed up to use Google Drive.
  2. Have access to Google Cloud Platform
  3. Have cURL installed.
  • To check, type the following command “which curl”. You can install curl with:
Debian and Ubuntu Systems
sudo apt install curlRed hat, CentOS, Fedora
sudo rpm install curl
sudo yum install curl
sudo dnf install curlOpenSUSE
sudo zypper install curlArch Linux
pacman -S curl

What is the curl command in Linux?
The curl command is a tool to transfer data from or to a server. It offers a busload of useful tricks like proxy support, user authentication, FTP up‐load, HTTP post, SSL connections, cookies, file transfer resume, Metalink, and more.

First Steps
Research OAuth and methods for accessing Google APIs. Google’s cloud file storage service provides users with a personal storage space, called My Drive.

There are several OAuth methods available to access Google Drive but the one we are focusing on is client ID and secret. A client ID is used to identify a single app to Google’s OAuth servers.

This diagram below shows the relationship between your Google Drive app, Google Drive, and Google Drive API:

 

Image Source

Procedure

To use client ID and client secret to access Google Drive, create a new project.

Log in to Google Cloud Platform.
Select the drop down list to the left side of the search bar.
Select New Project “:”,

 

Give your project a suitable name and click on Create

 

Once the project has been created, a notification will appear confirming it has been successful.

Create Credentials
Navigate to the credentials panel (on the left) and then select create credentials from the top. From the drop down menu select OAuth client ID option.

 

Next, configure the consent screen. When you use OAuth 2.0 for authorization, your app requests authorizations for one or more scopes of access from a Google Account. Google displays a consent screen including a summary of the project and its policies and the requested scopes of access.

 

From the two options presented for user type, choose Internal or External and click Create. I have chosen internal as it limits the scope to users to within your organization.

 

You should see a similar page to the following image. The application name you provide will be displayed to the user on the consent screen when asking for permissions to use your Google accounts and services.

Enter the app name or ID you used when creating the project.

 

Adding an image or support email is optional.

Click on Save and Continue.
Accept the default scope configuration click on Save and Continue.

The following window will display the consent screen summary details.

 

Back at the dashboard, Navigate to Credentials
Select Create Credentials from the top.
When asked for the application type, select TVs and Limited input devices.

 

Finally, this will generate a client id and client secret. You have the option to download the credentials in a JSON format. It will contain additional information such as redirect uri, which is essentially your username and password so store it somewhere secure.

Enable Google Drive API

Navigate to the Dashboard and select Enable APIs and Services from the top. Use the API Library search box to find and enable “Google Drive API” .

 

Note: To ensure successful execution of the script there must be a compressed folder present in the same directory as the script. For this demo we are only concerned with the upload process.

Verify The Device

First we need to verify our device. Open a terminal on your machine and run the following commands.

VERIFY_DEVICE=`curl -d “client_id=”$CLIENT_ID”&scope=$SCOPE” https://oauth2.googleapis.com/device/code`

You should see a similar response by running the echo command.

echo $VERIFY_DEVICE
{ “device_code”: “XXXXXXXXXXXXXXXXXXXXXXXX”, “user_code”: “NRDJ-SHDX”, “expires_in”: 1800, “interval”: 5, “verification_url”: “https://www.google.com/device" }

Next, you will need to visit the verification_url in the response above and you will need to type the user to user_code to complete verification.

 

You are then required to accept requests for permissions.

 

Get The Bearer Code

Before an upload is possible, we need to extract the device_code from the response of the initial curl command. The jq option is used to filter the json response via a pipe. The device_code value is stored in the DEVICE_CODE variable.

DEVICE_CODE=`echo $VERIFY_DEVICE | jq -r ‘.device_code’`
echo $DEVICE_CODE

The client ID and secret are stored as global variables, as they are used several times throughout it is quicker and easier to use. They can be accessed from Credentials in APIs & Services.

BEARER=`curl -d client_id=$CLIENT_ID \
 -d client_secret=$CLIENT_SECRET \
 -d device_code=$DEVICE_CODE \
 -d grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code https://accounts.google.com/o/oauth2/token`

The response is as follows:

{ “access_token”: “XXXXXXXXXXXXX”, “expires_in”: 3599, “refresh_token”: “XXXXXXXXXXXXX”, “scope”: “https://www.googleapis.com/auth/drive.file", “token_type”: “Bearer” }

Next, we need the access_token as this is needed later for uploading the file.

ACCESS_TOKEN=`echo $BEARER | jq -r ‘.access_token’` 
echo $ACCESS_TOKEN

Upload File

For the purposes of this demo we are echoing the response to the terminal.

The folder ID is located in the URL of the Drive folder. For example, https://drive.google.com/drive/folders/1dyGErghjTY3Z467YfdGA7mfUH32g”, then the Folder ID would be “1dyGErghjTY3Z467YfdGA7mfUH32g”.

echo `curl -X POST -L \
 -H ‘Authorization: Bearer ‘${ACCESS_TOKEN} \
 -F ‘metadata={name : “backup.zip”, parents : [“<drive-folder-url>”]};type=application/json;charset=UTF-8’ \
 -F ‘file=@backup.zip;type=application/zip’ \
 ‘https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart'`

Here, we are performing a multipart upload request to send metadata along with the data to upload. We are using this option as the data we’re transferring is < 5MB. Refer to the client library documentation for additional details on how to use each of the upload types here.

Congratulations!!. You have just pushed your first file to your Google Drive

Putting it all Together

When you have tried all the commands in the terminal it is time to put it together into a single script. Depending on the system you are using you will have different text editor options (Vim, Vi, Nano, gedit, etc). The following script was created using the Nano editor.

#!/bin/bash# This script enables the user to upload a file to Google Drive# fail fast
set -e pipefailCLIENT_ID=<your-generated-client-id>
CLIENT_SECRET=<your-generated-client-secret>
SCOPE=https://www.googleapis.com/auth/drive.file # This is the URL we’ll send the user to first to get their authorization# verify device
VERIFY_DEVICE=`curl -d “client_id=”$CLIENT_ID”&scope=$SCOPE” https://oauth2.googleapis.com/device/code`
echo $VERIFY_DEVICE# extract device_code value from the json response using jq
DEVICE_CODE=`echo $VERIFY_DEVICE | jq -r ‘.device_code’`
echo $DEVICE_CODE# pause the script to give the user time to navigate to verification_url and enter the user_code.
sleep 25# get bearer code
BEARER=`curl -d client_id=$CLIENT_ID \
 -d client_secret=$CLIENT_SECRET \
 -d device_code=$DEVICE_CODE \
 -d grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code https://accounts.google.com/o/oauth2/token`#echo $BEARER# extract access_token value from the json response using jq
ACCESS_TOKEN=`echo $BEARER | jq -r ‘.access_token’` 
#echo $ACCESS_TOKENecho `curl -X POST -L \
 -H ‘Authorization: Bearer ‘${ACCESS_TOKEN} \
 -F ‘metadata={name : “backup.zip”, parents : [“<Google-Drive-Folder-URL-Here>”]};type=application/json;charset=UTF-8’ \
 -F ‘file=@backup.zip;type=application/zip’ \
 ‘https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart'`

Conclusion

That’s a wrap, you now have the ability to authenticate with Google APIs using this demo with file upload. I’m sure there is someone out there with a cleaner solution to push files from a computer to a Google Drive repository. Thank you for taking the time to read this post and I hope you got something from it. If you did, I would be delighted to get your feedback.
I would also challenge you to take this solution and fully automate the process, so the user_code is automatically posted to the verification_url. Thus, removing the one manual step.

 

arrow
arrow
    文章標籤
    google drive curl
    全站熱搜

    龍之家族 發表在 痞客邦 留言(0) 人氣()