I'm trying to download a file from google drive in a script, and I'm having a little trouble doing so. The files I'm trying to download are here.

I've looked online extensively and I finally managed to get one of them to download. I got the UIDs of the files and the smaller one (1.6MB) downloads fine, however the larger file (3.7GB) always redirects to a page which asks me whether I want to proceed with the download without a virus scan. Could someone help me get past that screen?

Here's how I got the first file working -

curl -L "https://docs.google.com/uc?export=download&id=0Bz-w5tutuZIYeDU0VDRFWG9IVUE" > phlat-1.0.tar.gz

When I run the same on the other file,

curl -L "https://docs.google.com/uc?export=download&id=0Bz-w5tutuZIYY3h5YlMzTjhnbGM" > index4phlat.tar.gz

I get the the following output - enter image description here

I notice on the third-to-last line in the link, there a &confirm=JwkK which is a random 4 character string but suggests there's a way to add a confirmation to my URL. One of the links I visited suggested &confirm=no_antivirus but that's not working.

I hope someone here can help with this!

Thanks in advance.

share|improve this question
    
can you please provide the curl script you used to download the file from google drive as I am unable to download a working file ( image) from this script curl -u username:pass https://drive.google.com/open?id=0B0QQY4sFRhIDRk1LN3g2TjBIRU‌​0 >image.jpg – Kasun Siyambalapitiya Nov 18 '16 at 9:06
    
Look at the accepted answer. I used the gdown.pl script gdown.pl https://drive.google.com/uc?export=download&confirm=yAjx&id=‌​0Bz-w5tutuZIYY3h5YlM‌​zTjhnbGM index4phlat.tar.gz – Arjun Nov 20 '16 at 21:03
1  
Don't be afraid to scroll! This answer provides a very nice python script to download in one go. – Ciprian Tomoiaga Dec 21 '16 at 19:36

15 Answers 15

up vote 26 down vote accepted

Have a look at this question: Direct download from Google Drive using Google Drive API

Basically you have to create a public directory and access your files by relative reference with something like

wget https://googledrive.com/host/LARGEPUBLICFOLDERID/index4phlat.tar.gz

WARNING: This functionality is deprecated. See warning below in comments.

Alternatively, you can use this script: https://gitlab.com/Nanolx/patchimage/blob/master/tools/gdown.pl

share|improve this answer
2  
another good way is to use the linux command line tool "gdrive" github.com/prasmussen/gdrive – Tobi Jan 3 '15 at 21:04
1  
I was able to use Nanolx's perl script in combination with the google drive permalink created at gdurl.com --Thanks! – jadik Feb 25 '15 at 8:09
    
The LARGEPUBLICID make-up url did it for me, thanks @guadafan – Javier López Jul 1 '15 at 23:44
7  
WARNING: Web hosting support in Google Drive is deprecated. "Beginning August 31, 2015, web hosting in Google Drive for users and developers will be deprecated. Google Apps customers can continue to use this feature for a period of one year until August 31, 2016, when serving content via googledrive.com/host/doc id will be discontinued." googleappsupdates.blogspot.com/2015/08/… – chrish Sep 18 '15 at 14:44
    
the file should also be under your ownership – davidtaubmann Jun 22 '16 at 5:45

I wrote a Python snippet that downloads a file from Google Drive, given a shareable link. It works, as of August 2017.

The snipped does not use gdrive, nor the Google Drive API. It uses the requests module.

When downloading large files from Google Drive, a single GET request is not sufficient. A second one is needed, and this one has an extra URL parameter called confirm, whose value should equal the value of a certain cookie.

import requests

def download_file_from_google_drive(id, destination):
    def get_confirm_token(response):
        for key, value in response.cookies.items():
            if key.startswith('download_warning'):
                return value

        return None

    def save_response_content(response, destination):
        CHUNK_SIZE = 32768

        with open(destination, "wb") as f:
            for chunk in response.iter_content(CHUNK_SIZE):
                if chunk: # filter out keep-alive new chunks
                    f.write(chunk)

    URL = "https://docs.google.com/uc?export=download"

    session = requests.Session()

    response = session.get(URL, params = { 'id' : id }, stream = True)
    token = get_confirm_token(response)

    if token:
        params = { 'id' : id, 'confirm' : token }
        response = session.get(URL, params = params, stream = True)

    save_response_content(response, destination)    


if __name__ == "__main__":
    import sys
    if len(sys.argv) is not 3:
        print "Usage: python google_drive.py drive_file_id destination_file_path"
    else:
        # TAKE ID FROM SHAREABLE LINK
        file_id = sys.argv[1]
        # DESTINATION FILE ON YOUR DISK
        destination = sys.argv[2]
        download_file_from_google_drive(file_id, destination)
share|improve this answer
1  
this is awesomely nice! Thank you ! Love it that it writes it in chunks. Do you think you could add some sorts of progress tracking ? – Ciprian Tomoiaga Dec 21 '16 at 19:33
4  
Still works as of March, 2017 – Serkan Arıkuşu Mar 22 '17 at 9:31
3  
How to run this code? Where do I put my google drive file URL? @SerkanArıkuşu – user13107 Apr 28 '17 at 4:02
2  
This solution should be accepted. It is self-contained and it doesn't require external tools besides Python. – Yamaneko May 23 '17 at 21:09
2  
Oct 2017 still works :). Thank you a lot! – Maciek Sawicki Oct 8 '17 at 2:06

You can use the open source Linux / Unix command line tool gdrive.

To install it:

  1. Download the binary. Choose the one that fits your architecture, for example gdrive-linux-x64.

  2. Copy it to your path.

    sudo cp gdrive-linux-x64 /usr/local/bin/gdrive;
    sudo chmod a+x /usr/local/bin/gdrive;
    

To use it:

  1. Determine the Google Drive file ID. For that, right-click the desired file in the Google Drive website and choose "Get Link …". It will return something like https://drive.google.com/open?id=0B7_OwkDsUIgFWXA1B2FPQfV5S8H. Obtain the string behind the ?id= and copy it to your clipboard. That's the file's ID.

  2. Download the file. Of course, use your file's ID instead in the following command.

    gdrive download 0B7_OwkDsUIgFWXA1B2FPQfV5S8H
    

At first usage, the tool will need to obtain access permissions to the Google Drive API. For that, it will show you a link which you have to visit in a browser, and then you will get a verification code to copy&paste back to the tool. The download then starts automatically. There is no progress indicator, but you can observe the progress in a file manager or second terminal.

Source: A comment by Tobi on another answer here.

share|improve this answer
    
error message: "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.", code: 403 – Nianliang Nov 10 '16 at 2:37
    
@Nianliang Didn't experience this yet, but here's a guess: You used gdrive to download a publicly accessible file, so it would not ask you for authentication at first use. Try a non-public file first, make sure authentication succeeds (as described in the answer: "At first usage,…"). Did it help? – tanius Nov 10 '16 at 21:34
ggID='put_googleID_here'  
ggURL='https://drive.google.com/uc?export=download'  
filename="$(curl -sc /tmp/gcokie "${ggURL}&id=${ggID}" | grep -o '="uc-name.*</span>' | sed 's/.*">//;s/<.a> .*//')"  
getcode="$(awk '/_warning_/ {print $NF}' /tmp/gcokie)"  
curl -Lb /tmp/gcokie "${ggURL}&confirm=${getcode}&id=${ggID}" -o "${filename}"  

How does it work?
Get cookie file and html code with curl.
Pipe html to grep and sed and search for file name.
Get confirm code from cookie file with awk.
Finally download file with cookie enabled, confirm code and filename.

curl -Lb /tmp/gcokie "https://drive.google.com/uc?export=download&confirm=Uq6r&id=0B5IRsLTwEO6CVXFURmpQZ1Jxc0U" -o "SomeBigFile.zip"

If you dont need filename variable curl can guess it
-L Follow redirects
-O Remote-name
-J Remote-header-name

curl -sc /tmp/gcokie "${ggURL}&id=${ggID}" >/dev/null  
getcode="$(awk '/_warning_/ {print $NF}' /tmp/gcokie)"  
curl -LOJb /tmp/gcokie "${ggURL}&confirm=${getcode}&id=${ggID}" 

To extract google file ID from URL you can use:

echo "gURL" | egrep -o '(\w|-){26,}'  
# match more than 26 word characters  

OR

echo "gURL" | sed 's/[^A-Za-z0-9_-]/\n/g' | sed -rn '/.{26}/p'  
# replace non-word characters with new line,   
# print only line with more than 26 word characters 
share|improve this answer
    
Very nicely done. Got rid of the virus warning on a 5GB+ file when all other answers failed. – user636044 Sep 29 '16 at 18:45
    
This is terrific. I did have to add the --insecure option to both curl requests to make it work. – Taylor R Jan 11 '17 at 3:06
    
-C - will add resume finctionality. Well done! – Wojciech Migda Jan 27 '17 at 12:21
    
It Works Flawless! – Cristian Sepulveda Jul 11 '17 at 2:00
    
This works great! – RubyFanatic Dec 19 '17 at 1:56

The default behavior of google drive is to scan files for viruses if the file is to big it will prompte the user and notifies him that the file could not be scanned.

At the moment the only workaround I found is to share the file with the web and create a web resource.

Quote from the google drive help page:

With Drive, you can make web resources — like HTML, CSS, and Javascript files — viewable as a website.

To host a webpage with Drive:

  1. Open Drive at drive.google.com and select a file.
  2. Click the Share button at the top of the page.
  3. Click Advanced in the bottom right corner of the sharing box.
  4. Click Change....
  5. Choose On - Public on the web and click Save.
  6. Before closing the sharing box, copy the document ID from the URL in the field below "Link to share". The document ID is a string of uppercase and lowercase letters and numbers between slashes in the URL.
  7. Share the URL that looks like "www.googledrive.com/host/[doc id] where [doc id] is replaced by the document ID you copied in step 6.
    Anyone can now view your webpage.

Found here: https://support.google.com/drive/answer/2881970?hl=en

So for example when you share a file on google drive publicly the sharelink looks like this:

https://drive.google.com/file/d/0B5IRsLTwEO6CVXFURmpQZ1Jxc0U/view?usp=sharing

Then you copy the file id and create a googledrive.com linke that look like this:

https://www.googledrive.com/host/0B5IRsLTwEO6CVXFURmpQZ1Jxc0U
share|improve this answer
4  
This one did the trick in late 2015. Thanks! – user3285866 Oct 22 '15 at 11:46
4  
It doesn't worked for me. – Fırat KÜÇÜK Oct 29 '15 at 19:09
1  
@FıratKÜÇÜK are you sure you had the right url format? (note the www.googledrive.com and not drive.google.com) I just tried and it worked. – Charles Forest Nov 2 '15 at 20:21
    
My file is over 50 MB. it asks a virus scan confirmation. So the solution is not suitable for my case. Instead I used "gdrive" console application solution. – Fırat KÜÇÜK Nov 3 '15 at 21:25
3  
This feature is deprecated and no longer supported – Daniel Gonsales Kasas Feb 16 '17 at 10:28

Here's a quick way to do this.

Make sure the link is shared, and it will look something like this:

https://drive.google.com/open?id=FILEID&authuser=0

Then, copy that FILEID and use it like this

wget --no-check-certificate 'https://docs.google.com/uc?export=download&id=FILEID' -O FILENAME
share|improve this answer
2  
Hi, Thanks for the reply. If you look at the files on the link i shared, you will see that while the files are shared, they lack the 'authuser=0' tag in the link. Your method didn't work on the files provided! Arjun – Arjun Jun 19 '15 at 21:24
2  
Did not even try with public access, this one worked well for link-only shared files atow. Used it like this: wget 'https://docs.google.com/uc?export=download&id=SECRET_ID' -O 'filename.pdf' – Sampo Sarrala May 17 '16 at 13:49

No answer proposes what works for me as of december 2016 (source):

curl -L https://drive.google.com/uc?id={FileID}

provided the Google Drive file has been shared with those having the link and {FileID} is the string behind ?id= in the shared URL.

Although I did not check with huge files, I believe it might be useful to know.

share|improve this answer
    
Hmmm... didn't work for me :( Just downloads web content - not the file – kgingeri Jan 19 '17 at 21:20
1  
curl -L -o {filename} https://drive.google.com/uc?id={FileID} worked for me, thanks! – Dário May 18 '17 at 14:47
    
This doesn't work for me. My link is below (anyone with the link can view): drive.google.com/file/d/0B7Jh6M91b83bdFlWX2RIU2hYSWM/… . I tried: <code>curl -O -J -L drive.google.com/uc?id=0B7Jh6M91b83bdFlWX2RIU2hYSWM</code>‌​; and I get this result: curl: (56) Received HTTP code 403 from proxy after CONNECT – Steve May 21 '17 at 5:42
    
Worked for me with @Dário's command line – victorkohl Jun 8 '17 at 11:38
3  
Only works for files up to 25MB, larger files give virus scan warning page – cen Jul 26 '17 at 18:18

There's an open-source multi-platform client, written in Go: drive. It's quite nice and full-featured, and also is in active development.

$ drive help pull
Name
        pull - pulls remote changes from Google Drive
Description
        Downloads content from the remote drive or modifies
         local content to match that on your Google Drive

Note: You can skip checksum verification by passing in flag `-ignore-checksum`

* For usage flags: `drive pull -h`
share|improve this answer

I was unable to get Nanoix's perl script to work, or other curl examples I had seen, so I started looking into the api myself in python. This worked fine for small files, but large files choked past available ram so I found some other nice chunking code that uses the api's ability to partial download. Gist here: https://gist.github.com/csik/c4c90987224150e4a0b2

Note the bit about downloading client_secret json file from the API interface to your local directory.

Source
$ cat gdrive_dl.py
from pydrive.auth import GoogleAuth  
from pydrive.drive import GoogleDrive    

"""API calls to download a very large google drive file.  The drive API only allows downloading to ram 
   (unlike, say, the Requests library's streaming option) so the files has to be partially downloaded
   and chunked.  Authentication requires a google api key, and a local download of client_secrets.json
   Thanks to Radek for the key functions: http://stackoverflow.com/questions/27617258/memoryerror-how-to-download-large-file-via-google-drive-sdk-using-python
"""

def partial(total_byte_len, part_size_limit):
    s = []
    for p in range(0, total_byte_len, part_size_limit):
        last = min(total_byte_len - 1, p + part_size_limit - 1)
        s.append([p, last])
    return s

def GD_download_file(service, file_id):
  drive_file = service.files().get(fileId=file_id).execute()
  download_url = drive_file.get('downloadUrl')
  total_size = int(drive_file.get('fileSize'))
  s = partial(total_size, 100000000) # I'm downloading BIG files, so 100M chunk size is fine for me
  title = drive_file.get('title')
  originalFilename = drive_file.get('originalFilename')
  filename = './' + originalFilename
  if download_url:
      with open(filename, 'wb') as file:
        print "Bytes downloaded: "
        for bytes in s:
          headers = {"Range" : 'bytes=%s-%s' % (bytes[0], bytes[1])}
          resp, content = service._http.request(download_url, headers=headers)
          if resp.status == 206 :
                file.write(content)
                file.flush()
          else:
            print 'An error occurred: %s' % resp
            return None
          print str(bytes[1])+"..."
      return title, filename
  else:
    return None          


gauth = GoogleAuth()
gauth.CommandLineAuth() #requires cut and paste from a browser 

FILE_ID = 'SOMEID' #FileID is the simple file hash, like 0B1NzlxZ5RpdKS0NOS0x0Ym9kR0U

drive = GoogleDrive(gauth)
service = gauth.service
#file = drive.CreateFile({'id':FILE_ID})    # Use this to get file metadata
GD_download_file(service, FILE_ID) 
share|improve this answer

Here's a little bash script I wrote that does the job today. It works on large files and can resume partially fetched files too. It takes two arguments, the first is the file_id and the second is the name of the output file. The main improvements over previous answers here are that it works on large files and only needs commonly available tools: bash, curl, tr, grep, du, cut and mv.

#!/usr/bin/env bash
fileid="$1"
destination="$2"

# try to download the file
curl -c /tmp/cookie -L -o /tmp/probe.bin "https://drive.google.com/uc?export=download&id=${fileid}"
probeSize=`du -b /tmp/probe.bin | cut -f1`

# did we get a virus message?
# this will be the first line we get when trying to retrive a large file
bigFileSig='<!DOCTYPE html><html><head><title>Google Drive - Virus scan warning</title><meta http-equiv="content-type" content="text/html; charset=utf-8"/>'
sigSize=${#bigFileSig}

if (( probeSize <= sigSize )); then
  virusMessage=false
else
  firstBytes=$(head -c $sigSize /tmp/probe.bin)
  if [ "$firstBytes" = "$bigFileSig" ]; then
    virusMessage=true
  else
    virusMessage=false
  fi
fi

if [ "$virusMessage" = true ] ; then
  confirm=$(tr ';' '\n' </tmp/probe.bin | grep confirm)
  confirm=${confirm:8:4}
  curl -C - -b /tmp/cookie -L -o "$destination" "https://drive.google.com/uc?export=download&id=${fileid}&confirm=${confirm}"
else
  mv /tmp/probe.bin "$destination"
fi
share|improve this answer
    
Welcome to SO. If you have used any reference for this purpose please include them in your answer. Anyhow, nice job +1 – Masoud Apr 18 '17 at 17:47

Here is workaround which I came up download files from Google Drive to my Google Cloud Linux shell.

  1. Share the file to PUBLIC and with Edit permissions using advanced sharing.
  2. You will get a sharing link which would have an ID. See the link:- drive.google.com/file/d/[ID]/view?usp=sharing
  3. Copy that ID and Paste it in the following link:-

googledrive.com/host/[ID]

  1. The above link would be our download link.
  2. Use wget to download the file:-

wget https://googledrive.com/host/[ID]

  1. This command will download the file with name as [ID] with no extension and but with same file size on the same location where you ran the wget command.
  2. Actually, I downloaded a zipped folder in my practice. so I renamed that awkward file using:-

mv [ID] 1.zip

  1. then using

unzip 1.zip

we will get the files.

share|improve this answer
    
http 502 for that one googledrive.com/host/0BwPIpgeJ2AdnUGUzVGJuak5abDg – user2284570 Oct 5 '16 at 21:25
    
Google has taken away hosting from drive, so this no longer works. – kgingeri Jan 19 '17 at 21:22
    
try drive.google.com/uc?id=[ID] then. – Vikas Gautam Jan 20 '17 at 12:27

The easy way:

(if you just need it for a one-off download)

  1. Go to the Google Drive webpage that has the download link
  2. Open your browser console and go to the "network" tab
  3. Click the download link
  4. Wait for it the file to start downloading, and find the corresponding request (should be the last one in the list), then you can cancel the download
  5. Right click on the request and click "Copy as cURL" (or similar)

You should end up with something like:

curl 'https://doc-0s-80-docs.googleusercontent.com/docs/securesc/aa51s66fhf9273i....................blah blah blah...............gEIqZ3KAQ==' --compressed

Past it in your console, add > my-file-name.extension to the end (otherwise it will write the file into your console), then press enter :)

share|improve this answer

I had the same problem with Google Drive.

Here's how I solved the problem using Links 2.

  1. Open a browser on your PC, navigate to your file in Google Drive. Give your file a public link.

  2. Copy the public link to your clipboard (eg right click, Copy link address)

  3. Open a Terminal. If you're downloading to another PC/server/machine you should SSH to it as this point

  4. Install Links 2 (debian/ubuntu method, use your distro or OS equivalent)

    sudo apt-get install links2

  5. Paste the link in to your terminal and open it with Links like so:

    links2 "paste url here"

  6. Navigate to the download link within Links using your Arrow Keys and press Enter

  7. Choose a filename and it'll download your file

share|improve this answer
    
Links totally did the trick! And it's much much better than w3m – alvas Jan 11 '16 at 2:32

This works as of Nov 2017 https://gist.github.com/ppetraki/258ea8240041e19ab258a736781f06db

#!/bin/bash

SOURCE="$1"
if [ "${SOURCE}" == "" ]; then
    echo "Must specify a source url"
    exit 1
fi

DEST="$2"
if [ "${DEST}" == "" ]; then
    echo "Must specify a destination filename"
    exit 1
fi

FILEID=$(echo $SOURCE | rev | cut -d= -f1 | rev)
COOKIES=$(mktemp)

CODE=$(wget --save-cookies $COOKIES --keep-session-cookies --no-check-certificate "https://docs.google.com/uc?export=download&id=${FILEID}" -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/Code: \1\n/p')

# cleanup the code, format is 'Code: XXXX'
CODE=$(echo $CODE | rev | cut -d: -f1 | rev | xargs)

wget --load-cookies $COOKIES "https://docs.google.com/uc?export=download&confirm=${CODE}&id=${FILEID}" -O $DEST

rm -f $COOKIES
share|improve this answer
    
Although there is stated "source url" and there is some parsing I didn't try to understand it worked by simply directly using what is called fileid here and in other answers as first parameter. – jan Nov 13 '17 at 9:12
    
@jan That may mean there is more than one url style. I'm glad it still worked for you over all. – ppetraki Nov 14 '17 at 17:30

The easiest way to is put what ever you want to download in a folder. Share that folder and then grab the Folder ID from the URL Bar.

Then go to https://googledrive.com/host/[ID] (Replace the ID with your folder ID) You should see a list of all the files in that folder, click the one you want to download. A download should then visit your download page (Ctrl+J on Chrome), you then want to copy the download link then use wget "download link"

Enjoy :)

share|improve this answer
    
Doesn't work now – Jay Chakra Dec 22 '16 at 8:26

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.