上传文件到Seafile

需求场景

业务系统需要每天巡检,之前的方案是巡检系统生成word格式的巡检报告,并发送到邮箱。
但是随着各地业务节点服务器增多,邮件也增多,每天接收很多邮件很困扰,而且邮件收到后,也需要将附件(即生成的巡检报告)上传至Seafile,所以简化化成,将巡检报告直接上传至Seafile。

具体实现

生成巡检报告参考:Python系统巡检脚本
如何将文件上传至Seafile,参考Seafiel api文档
首先确定Seafile上目标目录的最上层目录的repo-id,可以通过网页端在地址栏查看。
本次需要上传到运维巡检目录下,repo-id为8599d561-f818-4e86-93b3-1da91d920145
查看目录的所有者,使用目录所有者账号获取Token,也可以使用自己账户新建目录,并上传。

获取Token

1
2
# curl --data-urlencode username=****** -d password=****** https://seafile.******.com/api2/auth-token/
{"token":"e2acc3630c05c88a9546073ae5bac6ed8aa7e980"}

验证

1
2
# curl -H 'Authorization: Token e2acc3630c05c88a9546073ae5bac6ed8aa7e980' https://seafile.******.com/api2/auth/ping/
"pong"

出现pong,表示使用curl方式登录验证通过。
每个账户的token是不变的。
示例中账号密码及seafile地址隐藏了,在使用中根据实际情况填写。

获取上传链接

1
2
# curl -H 'Authorization: Token e2acc3630c05c88a9546073ae5bac6ed8aa7e980' https://seafile.******.com/api2/repos/8599d561-f818-4e86-93b3-1da91d920145/upload-link/
"https://seafile.******.com/seafhttp/upload-api/d6d70117-2124-484e-8fde-316cb6a7c30a"

此处8599d561-f818-4e86-93b3-1da91d920145即为上面提到的目标目录的repo-id。
需要主要的是:

返回的url并非是不变的,在不同的服务器上返回的url不同;
并且具有时效性,即过了一段时间之后,这个url就不能用了,但是具体多少时间没有测试出来。

上传脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/usr/bin/python
# coding:utf-8
#Author:Francis

import os
import subprocess
import time
import re
import requests


def main():

filename = "gbj_ls_checkos_" + session000 + ".docx"
cmd = " curl -s -H 'Authorization: Token e2acc3630c05c88a9546073ae5bac6ed8aa7e980' https://seafile.******.com/api2/repos/8599d561-f818-4e86-93b3-1da91d920145/upload-link/ "
getuploadlink = subprocess.Popen(cmd, shell=True, stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
uploadlinktmp = getuploadlink.stdout.read()
uploadlink = eval(uploadlinktmp)
output = os.popen(" curl -s -H 'Authorization: Token e2acc3630c05c88a9546073ae5bac6ed8aa7e980' -F file=@%s -F parent_dir=/test01/ls/ -F replace=1 %s " % (filename,uploadlink))
print(output.read())
print(datetime.datetime.now())


if __name__ == '__main__':
main()

脚本中获取系统指标的代码已经省略,其中变量filename代表生成的具有日期标识的巡检报告,uploadlink是脚本执行时获取的上传链接,- s表示curl以静默方式运行,不显示进度条。

本文标题:上传文件到Seafile

文章作者:Francis

原始链接:http://www.cnops.com/posts/fe431f56.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。