Search code examples
crontokenrootsudogdrive

gdrive upload fails with "Token has been expired or revoked." if it is executed with crontab but works as root (sudo -s)


I have written a script that uploads/updates an image to my gdrive. It should be executed every 15 min by a crontab entry.

I tested the script as root (sudo -s) and it works and has access to my gdrive. But it does not work when started by my crontab entry. I then get the following message as an error.

Uploading upload.jpg
Failed to upload file: Patch https://www.googleapis.com/upload/drive/v3/files/1y0000hMVV444qjuxC5xqL3hsmyAuoXya?alt=json&fields=id%2Cname%2Csize&uploadType=multipart: oauth2: cannot fetch token: 400 Bad Request
Response: {
  "error": "invalid_grant",
  "error_description": "Token has been expired or revoked."
}

This is my crontab entry

*/15  * * * *   root    /srv/media/webcam/nordbahnstrasse/scripts/upload_image.sh     >> /var/log/upload_image.txt

Solution

  • The gdrive command checks a token stored in token_v2.json. The default location for that file is within the user's home.

    $HOME/.gdrive/token_v2.json
    

    Using sudo -s changes the user, but the variable $HOME still points to the original user. Running a command with crontab as root checkes for /root/.gdrive/token_v2.json

    So the solution is to copy the file token_v2.json to /root/.gdrive/token_v2.json