某网盘上传文件脚本,使用方法 pcs -f file_name -p target_path
这里只展示了代码,如有疑问,欢迎到我的博客互相交流 http://www.factj.com/archives/508.html
#!/usr/bin/env python
# encoding: utf-8
import os
import json
import click
import requests as r
import ConfigParser
sess = r.Session()
C = {}
def load_config(sec="default"):
"""
从配置文件读取账号信息, 需要 appid, bduss
@sec : 读取的 ini 文件的 section, 预留的多账号功能
ini 文件格式举例
[default]
appid=266719 ; 应用id
bduss=xxxxx ;cookie,此cookie 过期时间非常久,貌似有八九年
"""
sc = ConfigParser.SafeConfigParser()
cname = ".pcscredentials"
f_ = None
if os.path.isfile(cname):
f_ = cname
elif os.path.isfile(os.path.join(os.getenv("HOME"), cname)):
f_ = os.path.join(os.getenv("HOME"), cname)
elif os.path.isfile(os.path.join("/etc/", cname)):
f_ = os.path.join("/etc/", cname)
sc.read(f_)
C.update(dict(sc.items(sec)))
def get_cookie():
"""
为请求准备的 cookie
"""
return dict(BDUSS=C['bduss'])
def upload_file(name):
url = "https://pcs.baidu.com/rest/2.0/pcs/file?method=upload&app_id=%s&type=tmpfile" % C['appid']
with open(name) as uploaded:
res = sess.post(url, cookies=get_cookie(), files=[(name, uploaded), ])
d = res.json()
return d
def create_file(path, data, name=None):
url = "https://pcs.baidu.com/rest/2.0/pcs/file?method=createsuperfile&app_id=%s" % C['appid']
if name:
path = os.path.join(path, name)
str_p = json.dumps(dict(block_list=[data['md5'], ]))
res = sess.post(url, params=dict(path=path), data=dict(param=str_p), cookies=get_cookie())
print json.dumps(res.json(), indent=4, ensure_ascii=False)
@click.command()
@click.option("-f", help=u"文件路径")
@click.option("-p", help=u"保存路径")
@click.option("-c", "--config", default="default", help=u"配置文件名字")
def cli(f, p, config):
load_config(config)
d = upload_file(f)
file_name = f.split(os.seq)[-1]
if p.endswith("/"):
p += file_name
create_file(p, d)
if __name__ == "__main__":
cli()