我试图在脚本中从谷歌驱动器下载一个文件,我这样做有点麻烦。我要下载的文件在这里。

我在网上搜了很多,终于下载了其中一个。我得到了文件的uid,较小的文件(1.6MB)下载正常,但较大的文件(3.7GB)总是重定向到一个页面,询问我是否想在不进行病毒扫描的情况下继续下载。谁能帮我跳过那个屏幕?

下面是我如何让第一个文件工作-

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

当我对另一个文件进行同样操作时,

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

我得到以下输出-

我注意到在链接的第三行到最后一行,有一个&confirm=JwkK,这是一个随机的4个字符的字符串,但建议有一种方法添加到我的URL确认。我访问的一个链接建议&confirm=no_antivirus,但这不起作用。

我希望这里有人能帮忙!


警告:此功能已弃用。见下面评论中的警告。


看看这个问题:直接从谷歌驱动器使用谷歌驱动器API下载

基本上,你必须创建一个公共目录,并通过相对引用来访问你的文件

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

或者,您可以使用这个脚本:https://github.com/circulosmeos/gdown.pl

我无法让Nanoix的perl脚本工作,或者我看到的其他curl示例,所以我开始自己用python研究api。这适用于小文件,但大文件阻塞了可用的ram,所以我找到了一些其他不错的分块代码,使用api的部分下载功能。要点: https://gist.github.com/csik/c4c90987224150e4a0b2

注意从API接口下载client_secret json文件到本地目录的部分。

$ 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) 

谷歌驱动器的默认行为是扫描文件的病毒,如果文件太大,它将提示用户,并通知他,该文件无法扫描。

目前我找到的唯一解决办法是在网络上共享文件并创建一个网络资源。

引用自谷歌驱动器帮助页面:

使用Drive,您可以使web资源-如HTML, CSS和Javascript文件-可作为网站查看。

使用Drive托管网页:

Open Drive at drive.google.com and select a file. Click the Share button at the top of the page. Click Advanced in the bottom right corner of the sharing box. Click Change.... Choose On - Public on the web and click Save. 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. 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.

在这里找到:https://support.google.com/drive/answer/2881970?hl=en

例如,当你在谷歌驱动器上公开共享一个文件时,共享链接看起来是这样的:

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

然后复制文件id,创建googledrive.com链接,如下所示:

https://www.googledrive.com/host/0B5IRsLTwEO6CVXFURmpQZ1Jxc0U

这里有一个快速的方法。

确保链接是共享的,它看起来会像这样:

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

然后,复制该FILEID并像这样使用它

wget --no-check-certificate 'https://docs.google.com/uc?export=download&id=FILEID' -O FILENAME

如果文件很大并且触发了病毒检查页面,您可以使用这样做(但它会下载两个文件,一个html文件和实际文件):

wget --no-check-certificate 'https://docs.google.com/uc?export=download&id=FILEID' -r -A 'uc*' -e robots=off -nd

有一个开源的多平台客户端,用Go: drive编写。它非常漂亮,功能齐全,而且还在积极开发中。

$ 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`

从2022年3月开始,你可以使用开源的跨平台命令行工具gdrive。与其他解决方案相比,它还可以不受限制地下载文件夹,也可以使用非公共文件。

来源:我从Tobi对另一个答案的评论中发现了gdrive。

当前状态

以前有问题,这个工具没有被谷歌验证,它没有维护。自2021-05-28提交以来,这两个问题都已解决。这也意味着,以前需要谷歌服务帐户的解决方案不再需要。(在极少数情况下,您可能仍会遇到问题;如果是,请尝试ntechp-fork。)

安装gdrive

下载2.1.1二进制文件。选择适合您的操作系统的软件包,例如gdrive_2.1.1 1_linux_amd64.tar.gz。 将其复制到您的路径。 gunzip gdrive_2.1.1_linux_amd64.tar.gz Sudo mkdir /usr/local/bin/gdrive Sudo cp gdrive-linux-amd64 /usr/local/bin/gdrive Sudo chmod a+x /usr/local/bin/gdrive

使用gdrive

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. 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.

额外的技巧:速率限制。要以有限的最大速率下载gdrive(以不淹没本地网络中的上行链路…),您可以使用这样的命令:

gdrive download --stdout 0B7_OwkDsUIgFWXA1B2FPQfV5S8H | \
    pv -br -L 90k | cat > file.ext

pv是PipeViewer。该命令将显示下载的数据量(-b)和下载速率(-r),并将下载速率限制为90kib /s (-L 90k)。

这是我从谷歌驱动器下载文件到我的谷歌云Linux外壳的解决方案。

使用高级共享将文件共享给PUBLIC并具有Edit权限。 你会得到一个共享链接,它会有一个ID。参见链接:- drive.google.com/file/d/ (ID) /视图? usp =分享 复制该ID并粘贴在以下链接:-

googledrive.com/host/ (ID)

以上链接为我们的下载链接。 使用wget下载文件:-

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

该命令将下载名称为[ID]的文件,没有扩展名,但文件大小与运行wget命令的位置相同。 实际上,我在实习时下载了一个压缩文件夹。所以我重命名了这个尴尬的文件使用:-

mv [id] 1.zip

然后使用

1.压缩解压缩

我们会拿到文件的。

谷歌硬盘也有同样的问题。

下面是我如何使用Links 2解决这个问题。

Open a browser on your PC, navigate to your file in Google Drive. Give your file a public link. Copy the public link to your clipboard (eg right click, Copy link address) Open a Terminal. If you're downloading to another PC/server/machine you should SSH to it as this point Install Links 2 (debian/ubuntu method, use your distro or OS equivalent) sudo apt-get install links2 Paste the link in to your terminal and open it with Links like so: links2 "paste url here" Navigate to the download link within Links using your Arrow Keys and press Enter Choose a filename and it'll download your file

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}"  

它是如何工作的? 使用curl获取cookie文件和html代码。 管道html到grep和sed和搜索文件名。 使用awk从cookie文件中获取确认代码。 最后下载启用cookie的文件,确认代码和文件名。

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

如果你不需要文件名变量卷曲可以猜出来 -L Follow重定向 - o远程名称 - 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}" 

要从URL提取谷歌文件ID,您可以使用:

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 

我写了一个从谷歌驱动器下载文件的Python代码片段,给出了一个可共享的链接。截至2017年8月,它是有效的。

剪切不使用gdrive,也没有谷歌驱动器API。它使用请求模块。

当从谷歌驱动器下载大文件时,单个GET请求是不够的。需要第二个URL,这个URL有一个额外的URL参数confirm,它的值应该等于某个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)

最简单的方法就是把你想下载的东西放在一个文件夹里。共享该文件夹,然后从URL栏中抓取文件夹ID。

然后进入https://googledrive.com/host/[ID](用你的文件夹ID替换ID) 您应该看到该文件夹中所有文件的列表,单击要下载的文件。一个下载应该然后访问你的下载页面(Ctrl+J在Chrome上),然后你想复制下载链接,然后使用 Wget“下载链接”

享受:)

截至2016年12月,没有任何答案能告诉我什么适合我(来源):

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

前提是谷歌驱动器文件已经与那些拥有该链接的人共享,并且{FileID}是共享URL中?id=后面的字符串。

虽然我没有检查过大的文件,但我相信知道它可能是有用的。

下面是我写的一个小bash脚本,它今天完成了这项工作。它适用于大文件,也可以恢复部分获取的文件。它有两个参数,第一个是file_id,第二个是输出文件的名称。与之前的答案相比,主要的改进是它可以在大文件上工作,只需要常用的工具:bash, curl, tr, grep, du, cut和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

简单的方法:

(如果你只需要一次性下载)

去谷歌驱动器的网页,有下载链接 打开浏览器控制台,转到“网络”选项卡 点击下载链接 等待它的文件开始下载,并找到相应的请求(应该是列表中的最后一个),然后可以取消下载 右键单击请求并单击“复制为cURL”(或类似的)

你应该得到如下内容:

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

在控制台中,添加> my-file-name。扩展到最后(否则它会把文件写到你的控制台),然后按enter:)

这个链接确实有某种过期时间,所以在生成第一个请求后几分钟就不能开始下载了。

自2017年11月起生效 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

我找到了一个有效的解决方案…简单地使用以下方法

wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=1HlzTR1-YVoBPlXo0gMFJ_xY4ogMnfzDi' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=1HlzTR1-YVoBPlXo0gMFJ_xY4ogMnfzDi" -O besteyewear.zip && rm -rf /tmp/cookies.txt

Skicka是一个cli工具,用于从谷歌硬盘上传、下载访问文件。

的例子,

skicka download /Pictures/2014 ~/Pictures.copy/2014
10 / 10 [=====================================================] 100.00 % 
skicka: preparation time 1s, sync time 6s
skicka: updated 0 Drive files, 10 local files
skicka: 0 B read from disk, 16.18 MiB written to disk
skicka: 0 B uploaded (0 B/s), 16.18 MiB downloaded (2.33 MiB/s)
skicka: 50.23 MiB peak memory used

截至2018年3月更新。

我尝试了其他答案中给出的各种技术,直接从谷歌驱动器下载我的文件(6 GB)到我的AWS ec2实例,但没有一个有效(可能是因为它们太旧了)。

所以,为了让其他人知道,下面是我是如何成功做到的:

Right-click on the file you want to download, click share, under link sharing section, select "anyone with this link can edit". Copy the link. It should be in this format: https://drive.google.com/file/d/FILEIDENTIFIER/view?usp=sharing Copy the FILEIDENTIFIER portion from the link. Copy the below script to a file. It uses curl and processes the cookie to automate the downloading of the file. #!/bin/bash fileid="FILEIDENTIFIER" filename="FILENAME" curl -c ./cookie -s -L "https://drive.google.com/uc?export=download&id=${fileid}" > /dev/null curl -Lb ./cookie "https://drive.google.com/uc?export=download&confirm=`awk '/download/ {print $NF}' ./cookie`&id=${fileid}" -o ${filename} As shown above, paste the FILEIDENTIFIER in the script. Remember to keep the double quotes! Provide a name for the file in place of FILENAME. Remember to keep the double quotes and also include the extension in FILENAME (for example, myfile.zip). Now, save the file and make the file executable by running this command in terminal sudo chmod +x download-gdrive.sh. Run the script using `./download-gdrive.sh".

PS:这是上面给出的脚本的Github要点:https://gist.github.com/amit-chahar/db49ce64f46367325293e4cce13d2424

2018年5月工作

嗨,根据这些评论…我创建一个bash导出URL列表从文件URL .txt到URLS_DECODED.txt 在一些加速器如flashget中使用(我使用cygwin来结合Windows和Linux)

引入命令爬行器是为了避免下载并(直接)获得最终链接

命令GREP HEAD和CUT,处理并获得最终链接,是基于西班牙语,也许你可以移植到英语语言

echo -e "$URL_TO_DOWNLOAD\r"可能\r只是cywin,必须用\n(换行符)代替

**********user***********为用户文件夹

*******Localización***********是西班牙语,清除星号,让英语单词定位和适应头部和切割数字适当的方法。

rm -rf /home/**********user***********/URLS_DECODED.txt
COUNTER=0
while read p; do 
    string=$p
    hash="${string#*id=}"
    hash="${hash%&*}"
    hash="${hash#*file/d/}"
    hash="${hash%/*}"
    let COUNTER=COUNTER+1
    echo "Enlace "$COUNTER" id="$hash
    URL_TO_DOWNLOAD=$(wget --spider --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id='$hash -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id="$hash 2>&1 | grep *******Localización***********: | head -c-13 | cut -c16-)
    rm -rf /tmp/cookies.txt
    echo -e "$URL_TO_DOWNLOAD\r" >> /home/**********user***********/URLS_DECODED.txt
    echo "Enlace "$COUNTER" URL="$URL_TO_DOWNLOAD
done < /home/**********user***********/URLS.txt

2018年5月

如果你想使用curl从谷歌驱动器下载文件,除了驱动器中的文件id,你还需要谷歌驱动器API的OAuth2 access_token。获取令牌涉及谷歌API框架的几个步骤。谷歌的注册步骤(目前)是免费的。

OAuth2 access_token可能允许所有类型的活动,因此要小心使用它。此外,令牌会在一小段时间后超时(1小时?),但如果有人捕获它,时间还不够短,无法防止滥用。

一旦你有一个access_token和fileid,这将工作:

AUTH="Authorization: Bearer the_access_token_goes_here"
FILEID="fileid_goes_here"
URL=https://www.googleapis.com/drive/v3/files/$FILEID?alt=media
curl --header "$AUTH" $URL >myfile.ext

参见:谷歌驱动器api—REST—下载文件

根据Roshan Sethia的回答

2018年5月

使用WGET:

Create a shell script called wgetgdrive.sh as below: #!/bin/bash # Get files from Google Drive # $1 = file ID # $2 = file name URL="https://docs.google.com/uc?export=download&id=$1" wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate $URL -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=$1" -O $2 && rm -rf /tmp/cookies.txt Give the right permissions to execute the script In terminal, run: ./wgetgdrive.sh <file ID> <filename> for example: ./wgetgdrive.sh 1lsDPURlTNzS62xEOAIG98gsaW6x2PYd2 images.zip

2022年6月

你可以用gdown。也可以考虑访问该页面以获得完整的说明;这只是一个总结,源回购可能有更多最新的说明。


指令

使用以下命令安装:

pip install gdown

在此之后,您可以通过运行以下命令之一从谷歌驱动器下载任何文件:

gdown https://drive.google.com/uc?id=<file_id>  # for files
gdown <file_id>                                 # alternative format
gdown --folder https://drive.google.com/drive/folders/<file_id>  # for folders
gdown --folder --id <file_id>                                   # this format works for folders too

示例:从该目录下载自述文件

gdown https://drive.google.com/uc?id=0B7EVK8r0v71pOXBhSUdJWU1MYUk

file_id应该类似于0Bz8a_Dbh9QhbNU3SGlFaDg。您可以通过右键单击感兴趣的文件并选择Get link来找到这个ID。自2021年11月起,该链接的形式为:

# Files
https://drive.google.com/file/d/<file_id>/view?usp=sharing
# Folders
https://drive.google.com/drive/folders/<file_id>

警告

只对开放文件有效。(“任何有链接的人都可以查看”) 不能下载超过50个文件到一个文件夹。 如果您可以访问源文件,您可以考虑使用tar/zip将其变成一个单独的文件来解决这个限制。

最简单的方法是:

创建下载链接并复制文件id 用WGET下载:WGET——load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget——quiet——save-cookies /tmp/cookies.txt——keep-session-cookies——no-check-certificate 'https://docs.google.com/uc?export=download&id=FILEID' - o- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=FILEID" - o FILENAME && rm -rf /tmp/cookies.txt

你只需要使用wget:

 https://drive.google.com/uc?authuser=0&id=[your ID without brackets]&export=download

PD。该文件必须是公共的。

使用youtube-dl !

优酷-DL https://drive.google.com/open?id=ABCDEFG1234567890

你也可以传递——get- URL来获取一个直接下载的URL。

有一个更简单的方法。

从firefox/chrome扩展安装cliget/CURLWGET。

从浏览器下载文件。这将创建一个curl/wget链接,用于记住下载文件时使用的cookie和头文件。使用此命令从任何shell下载

获得可共享的链接,并以隐身方式打开它(非常重要)。 它会说它无法扫描。

打开检查器并跟踪网络流量。 点击“无论如何下载”按钮。

复制最后一个请求的url。 这是你的链接。在wget中使用它。

——更新

要下载该文件,请从这里获取python的youtube-dl:

YouTube-DL: https://rg3.github.io/youtube-dl/download.html

或者用pip安装:

sudo python2.7 -m pip install --upgrade youtube_dl 
# or 
# sudo python3.6 -m pip install --upgrade youtube_dl

更新:

我刚刚发现了这个:

右击要从drive.google.com下载的文件 点击获取共享链接 开启链路共享 点击共享设置 点击顶部下拉菜单的选项 点击更多 选择[x]打开-任何有链接的人 复制链接

https://drive.google.com/file/d/3PIY9dCoWRs-930HHvY-3-FOOPrIVoBAR/view?usp=sharing       
(This is not a real file address)

将id复制到https://drive.google.com/file/d/:之后

3PIY9dCoWRs-930HHvY-3-FOOPrIVoBAR

粘贴到命令行:

youtube-dl https://drive.google.com/open?id=

把id贴在后面?id =

youtube-dl https://drive.google.com/open?id=3PIY9dCoWRs-930HHvY-3-FOOPrIVoBAR
[GoogleDrive] 3PIY9dCoWRs-930HHvY-3-FOOPrIVoBAR: Downloading webpage
[GoogleDrive] 3PIY9dCoWRs-930HHvY-3-FOOPrIVoBAR: Requesting source file
[download] Destination: your_requested_filename_here-3PIY9dCoWRs-930HHvY-3-FOOPrIVoBAR
[download] 240.37MiB at  2321.53MiB/s (00:01)

希望能有所帮助

在弄了这些垃圾之后。我找到了一种方法来下载我的甜蜜文件使用chrome开发工具。

At your google docs tab, Ctr+Shift+J (Setting --> Developer tools) Switch to Network tabs At your docs file, click "Download" --> Download as CSV, xlsx,.... It will show you the request in the "Network" console Right click -> Copy -> Copy as Curl Your Curl command will be like this, and add -o to create a exported file. curl 'https://docs.google.com/spreadsheets/d/1Cjsryejgn29BDiInOrGZWvg/export?format=xlsx&id=1Cjsryejgn29BDiInOrGZWvg' -H 'authority: docs.google.com' -H 'upgrade-insecure-requests: 1' -H 'user-agent: Mozilla/5.0 (X..... -o server.xlsx

解决了!

我用python脚本和谷歌驱动器api做到了这一点, 您可以尝试以下片段:

//using chunk download

file_id = 'someid'
request = drive_service.files().get_media(fileId=file_id)
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print "Download %d%%." % int(status.progress() * 100)

从谷歌驱动器上下载文件的简单方法,您也可以在colab上下载文件

pip install gdown

import gdown

Then

url = 'https://drive.google.com/uc?id=0B9P1L--7Wd2vU3VUVlFnbTgtS2c'
output = 'spam.txt'
gdown.download(url, output, quiet=False)

or

fileid='0B9P1L7Wd2vU3VUVlFnbTgtS2c'

gdown https://drive.google.com/uc?id=+fileid

文档https://pypi.org/project/gdown/

以上所有的回答似乎都掩盖了答案的简单性,或者有一些没有解释的细微差别。

如果文件是公开共享的,您只需知道文件ID就可以生成一个直接下载链接。URL必须是“https://drive.google.com/uc?id=[FILEID]&export=download”的形式。此格式自2019年11月22日起生效。这并不要求接收方登录到谷歌,但要求公开共享该文件。

在浏览器中,导航到drive.google.com。 右键点击文件,点击“获取可共享链接”

打开一个新选项卡,选择地址栏,并粘贴到剪贴板的内容,这将是可共享的链接。您将看到谷歌的查看器显示的文件。ID是URL的“View”组件前面的数字:

编辑URL,使其为以下格式,将“[FILEID]”替换为共享文件的ID: https://drive.google.com/uc?id=[文件标识]进出口=下载 这是你的直接下载链接。如果你在浏览器中点击它,文件现在会被“推送”到你的浏览器,打开下载对话框,允许你保存或打开文件。您也可以在下载脚本中使用此链接。 所以等价的curl命令是:

curl -L "https://drive.google.com/uc?id=AgOATNfjpovfFrft9QYa-P1IeF9e7GWcH&export=download" > phlat-1.0.tar.gz

我一直在使用@Amit Chahar的curl片段,他在这个帖子中给出了一个很好的答案。我发现它很有用 将其放在bash函数中,而不是单独的.sh文件中

function curl_gdrive {

    GDRIVE_FILE_ID=$1
    DEST_PATH=$2

    curl -c ./cookie -s -L "https://drive.google.com/uc?export=download&id=${GDRIVE_FILE_ID}" > /dev/null
    curl -Lb ./cookie "https://drive.google.com/uc?export=download&confirm=`awk '/download/ {print $NF}' ./cookie`&id=${GDRIVE_FILE_ID}" -o ${DEST_PATH}
    rm -f cookie
}

可以包含在例如a ~/。Bashrc(当然,如果不是自动源),并以以下方式使用

   $ curl_gdrive 153bpzybhfqDspyO_gdbcG5CMlI19ASba imagenet.tar

UPDATE 2022-03-01 - wget版本,当病毒扫描被触发时也可以工作

function wget_gdrive {

    GDRIVE_FILE_ID=$1
    DEST_PATH=$2

    wget --save-cookies cookies.txt 'https://docs.google.com/uc?export=download&id='$GDRIVE_FILE_ID -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1/p' > confirm.txt
    wget --load-cookies cookies.txt -O $DEST_PATH 'https://docs.google.com/uc?export=download&id='$GDRIVE_FILE_ID'&confirm='$(<confirm.txt)
    rm -fr cookies.txt confirm.txt
}

示例用法:

    $ wget_gdrive 1gzp8zIDo888AwMXRTZ4uzKCMiwKynHYP foo.out

以上答案对于2020年4月已经过时,因为谷歌驱动器现在使用重定向到文件的实际位置。

截至2020年4月,在macOS 10.15.4上工作的公共文档:

# this is used for drive directly downloads
function download-google(){
  echo "https://drive.google.com/uc?export=download&id=$1"
  mkdir -p .tmp
  curl -c .tmp/$1cookies "https://drive.google.com/uc?export=download&id=$1" > .tmp/$1intermezzo.html;
  curl -L -b .tmp/$1cookies "$(egrep -o "https.+download" .tmp/$1intermezzo.html)" > $2;
}

# some files are shared using an indirect download
function download-google-2(){
  echo "https://drive.google.com/uc?export=download&id=$1"
  mkdir -p .tmp
  curl -c .tmp/$1cookies "https://drive.google.com/uc?export=download&id=$1" > .tmp/$1intermezzo.html;
  code=$(egrep -o "confirm=(.+)&amp;id=" .tmp/$1intermezzo.html | cut -d"=" -f2 | cut -d"&" -f1)
  curl -L -b .tmp/$1cookies "https://drive.google.com/uc?export=download&confirm=$code&id=$1" > $2;
}

# used like this
download-google <id> <name of item.extension>

2020年7月- Windows用户批处理文件解决方案

我想为windows用户添加一个简单的批处理文件解决方案,因为我只发现了linux解决方案,我花了几天时间来学习为windows创建解决方案的所有这些东西。因此,为了避免其他人可能需要它,这里是。

你需要的工具

wget for windows (5KB exe小程序,无需安装) 从这里下载。 https://eternallybored.org/misc/wget/ jrepl for windows (117KB的批处理程序,无需安装) 该工具类似于linux的sed工具。 从这里下载: https://www.dostips.com/forum/viewtopic.php?t=6044

假设

%filename% -你想下载的文件将被保存到的文件名。 %fileid% =谷歌文件id(前面已经解释过了)

批量代码下载小文件从谷歌驱动器

wget -O "%filename%" "https://docs.google.com/uc?export=download&id=%fileid%"        

批量代码下载大文件从谷歌驱动器

set cookieFile="cookie.txt"
set confirmFile="confirm.txt"
   
REM downlaod cooky and message with request for confirmation
wget --quiet --save-cookies "%cookieFile%" --keep-session-cookies --no-check-certificate "https://docs.google.com/uc?export=download&id=%fileid%" -O "%confirmFile%"
   
REM extract confirmation key from message saved in confirm file and keep in variable resVar
jrepl ".*confirm=([0-9A-Za-z_]+).*" "$1" /F "%confirmFile%" /A /rtn resVar
   
REM when jrepl writes to variable, it adds carriage return (CR) (0x0D) and a line feed (LF) (0x0A), so remove these two last characters
set confirmKey=%resVar:~0,-2%
   
REM download the file using cookie and confirmation key
wget --load-cookies "%cookieFile%" -O "%filename%" "https://docs.google.com/uc?export=download&id=%fileid%&confirm=%confirmKey%"
   
REM clear temporary files 
del %cookieFile%
del %confirmFile%

2022年4月

首先,从谷歌驱动器中提取所需文件的ID: 在浏览器中,导航到drive.google.com。 右键单击文件,点击“获取可共享链接” 然后从URL中提取文件的ID: 接下来,使用pip安装gdown PyPI模块: PIP安装gdown 最后,使用gdown和预期的ID下载文件: gdown——id <put-the-ID>


【注意】:

在google-colab你必须使用!在bash命令之前。 (即!gdown——id 1-1wAx7b-USG0eQwIBVwVDUl3K1_1ReCt) 您应该将目标文件的权限从“受限”更改为“任何拥有该链接的人”。

替代方法,2020年

适用于无头服务器。我试图下载一个200GB的私人文件,但无法获得任何其他方法,在这个线程中提到,工作。

解决方案

(如果文件已经在您自己的谷歌驱动器中,则跳过此步骤)将想要从公共/共享文件夹下载的文件复制到您的谷歌驱动器帐户中。选择“文件”->右键单击->拷贝

安装Rclone(一个开源命令行工具),在本地存储和谷歌驱动器之间同步文件。这是一个快速教程,安装和设置rclone的谷歌驱动器。 使用Rclone将您的文件从谷歌驱动器复制到您的机器

rclone copy mygoogledrive:path/to/file /path/to/file/on/local/machine -P

-P参数帮助跟踪下载的进度,并让您知道下载何时完成。

2020年11月

如果你更喜欢使用bash脚本,这对我来说是有效的: (5Gb文件,已公开)

#!/bin/bash
if [ $# != 2 ]; then
echo "Usage: googledown.sh ID save_name"
exit 0
fi
confirm=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id='$1 -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')
echo $confirm
wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$confirm&id=$1" -O $2 && rm -rf /tmp/cookies.txt

解决方案只使用谷歌驱动器API

在运行下面的代码之前,您必须激活谷歌驱动器API,安装依赖项并验证您的帐户。说明可以在原来的谷歌驱动器API指南页面上找到

import io
import os
import pickle
import sys, argparse
from googleapiclient.discovery import build
from google.auth.transport.requests import Request
from googleapiclient.http import MediaIoBaseDownload
from google_auth_oauthlib.flow import InstalledAppFlow

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/drive.readonly']


def _main(file_id, output):
    """ Shows basic usage of the Drive v3 API.
        Prints the names and ids of the first 10 files the user has access to.
    """
    if not file_id:
        sys.exit('\nMissing arguments. Correct usage:\ndrive_api_download.py --file_id <file_id> [--output output_name]\n')
    elif not output:
        output = "./" + file_id
    
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('drive', 'v3', credentials=creds)

    # Downloads file
    request = service.files().get_media(fileId=file_id)
    fp = open(output, "wb")
    downloader = MediaIoBaseDownload(fp, request)
    done = False
    while done is False:
        status, done = downloader.next_chunk(num_retries=3)
        print("Download %d%%." % int(status.progress() * 100))

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-i', '--file_id')
    parser.add_argument('-o', '--output')
    args = parser.parse_args()
    
    _main(args.file_id, args.output)

获取文件ID:

1.在浏览器中打开谷歌驱动器。

2.右键单击要下载的文件,单击“获取可共享链接”。链接如下所示:https://drive.google.com/file/d/XXX/view?usp=sharing。记录文件ID XXX;你将在下面需要它。

获取一个OAuth令牌:

1.去OAuth 2.0游乐场

2.在“选择和授权API”框中,向下滚动,展开Drive API v3,并选择https://www.googleapis.com/auth/drive.readonly。

3.单击“授权api”,然后为令牌交换授权代码。复制Access令牌YYY;你将在下面需要它。

从命令行下载文件:

如果操作系统为OS X或Linux,打开“终端”程序,输入以下命令。

curl -H "Authorization: Bearer YYY" https://www.googleapis.com/drive/v3/files/XXX?alt=media -o ZZZ 

如果使用Windows操作系统,打开PowerShell程序,输入以下命令。

Invoke-RestMethod -Uri https://www.googleapis.com/drive/v3/files/XXX?alt=media -Method Get Headers @{"Authorization"="Bearer YYY"} -OutFile ZZZ

在您的命令中,将XXX替换为上面的文件ID, YYY替换为上面的访问令牌,ZZZ替换为将保存的文件名(例如,如果您下载的是zip文件,则替换为“myFile.zip”)。

对于无意中发现这条线索的任何人,以下工作截至2022年5月,以绕过大文件的反病毒检查:

#!/bin/bash
fileid="FILEIDENTIFIER"
filename="FILENAME"
html=`curl -c ./cookie -s -L "https://drive.google.com/uc?export=download&id=${fileid}"`
curl -Lb ./cookie "https://drive.google.com/uc?export=download&`echo ${html}|grep -Po '(confirm=[a-zA-Z0-9\-_]+)'`&id=${fileid}" -o ${filename}

我使用这个小脚本,只得到从谷歌驱动器复制的URL:

#!/bin/bash

name=`curl $1 |  grep -w \"name\" | sed 's/.*"name" content="//' | 
sed 's/".*//'`
id=`echo $1 | sed 's#.*/d/##; s#/view.*##'`
curl -L https://drive.google.com/uc?id=$id > $name
# or
# wget -O $name https://drive.google.com/uc?id=$id

您可以安装“lynx”,在“lynx”的帮助下,您可以轻松下载文件。

yum install lynx

将ID_OF_FILE替换为文件的id

lynx https://drive.google.com/u/0/uc?id=ID_OF_FILE&export=download

然后选择“下载”或“随便下载”

就是这样

从2022年开始,你可以使用这个解决方案:

https://drive.google.com/uc?export=download&id=FILE_ID&confirm=t


“病毒扫描警告页面”的来源:

“下载无论如何”的表单张贴到相同的URL,但有额外的三个参数:

t 确认 uuid

如果你改变你原来的URL并添加其中一个:confirm=t,它将下载文件而没有警告页面。

把URL改成

https://drive.google.com/uc?export=download&id=FILE_ID&confirm=t 

例如:

$ curl -L 'https://drive.google.com/uc?export=download&id=FILE_ID' > large_video.mp4
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                             Dload  Upload   Total   Spent    Left  Speed
100  2263    0  2263    0     0   5426      0 --:--:-- --:--:-- --:--:--  5453

添加confirm=t后,结果为:

$ curl -L 'https://drive.google.com/uc?export=download&id=FILE_ID&confirm=t' > large_video.mp4
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                             Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
100  128M  100  128M    0     0  10.2M      0  0:00:12  0:00:12 --:--:-- 10.9M

无脚本方法获得直接链接

我知道一些没有bash脚本编写经验的人正在从其他网站来到这篇文章。这是一个在浏览器中完成的解决方案。

步骤1:通常使用现有工具生成直接链接

首先,您使用所有其他现有的解决方案从您的共享链接生成一个直接链接。您可以使用https://sites.google.com/site/gdocs2direct/, https://www.wonderplugin.com/online-tools/google-drive-direct-link-generator/或https://chrome.google.com/webstore/detail/drive-direct-download/mpfdlhhpbhgghplbambikplcfpbjiail。 我将忽略这部分。

生成的直接链接如下所示:https://drive.google.com/u/0/uc?id=1Gjvcfj-8xxxxxxx8G8_jpgjcyorQ7BX5&export=download

直接链接适用于大多数小文件,但不适用于大文件。它将显示病毒警告,而不是简单地下载文件。现在我们来解决这个问题。

步骤2:修复断开的直接链接以解决病毒警告

在浏览器中打开断开的“直接”链接,您将看到“谷歌驱动器无法扫描此文件的病毒”。现在右键单击并查看页面源代码,您将看到以下文本:

<form id="downloadForm" action="https://drive.google.com/u/0/uc?id=1Gjvcfj-8xxxxxxx8G8_jpgjcyorQ7BX5&amp;export=download&amp;confirm=t&amp;uuid=5a0dd46b-521e-4ae7-8b41-0912e88b7782" method="post">

你已经找到了最后的链接!替换所有&去&并享受:

https://drive.google.com/uc?id=1Gjvcfj-8xxxxxxx8G8_jpgjcyorQ7BX5&export=download&confirm=t&uuid=c953a94e-b844-479f-8386-1ec83770fffb

大文件的其他解决方案:谷歌驱动器API

这个解决方案已经有了一个很好的答案!

你可以从谷歌得到url下载链接…/file/d/FILEID/view?usp=share_link并提取FILEID部分。然后在下面替换它(它在那里两次)。

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

将FILENAME替换为上面一行中应该调用的文件并享受。