python 下载/上载文件到Synology群晖

可以使用现成的库(Synology Wrapper),:

pip install synology-api

也可以使用api,比较麻烦点。

#!/usr/bin/env python
# coding: utf-8

# In[50]:



from datetime import datetime, timedelta
from shutil import copyfile
from datetime import datetime, timedelta
import time
import openpyxl
import os
import requests
import json


# In[2]:


server='http://10.101.1.249:5000'


# In[3]:


dt=datetime.now()+timedelta(days=-1)
file_ex='%02d.%02d' % (dt.month, dt.day)


# In[47]:


nas_dir='/生产部/1.공통╱共同/生产部每日速报汇总!!!/%d.%02d/' % (dt.year,dt.month)
local_dir='E:/12-速报/'
nas_file='生产速报-%02d.%02d.xlsx' % (dt.month, dt.day)

nas_dir_u = '/工务部/生产管理共享/%d月' % dt.month
local_file_u = '工务速报%02d.%02d.xlsx' % (dt.month, dt.day)


# In[5]:


# 登录
def login():
    print('登录...')
    uri=server+'/webapi/auth.cgi?api=SYNO.API.Auth&version=3&method=login&account=gw01&passwd=123456&session=FileStation&format=cookie'
    req=requests.request('GET',uri) 
    if req.json()['success']:
        return req.json()['data']['sid']
    else:
        print('登录失败')
        return ''


# In[61]:


def logout():
    print('注销...')
    uri=server+'/webapi/auth.cgi?api=SYNO.API.Auth&version=3&method=logout&session=FileStation&_sid=' + sid
    req=requests.request('GET',uri) 
    print(req.text)
    


# In[9]:


# 下载文件
def download():
    print('下载...')
    uri=server + r'/webapi/entry.cgi?api=SYNO.FileStation.Download&version=2&method=download&path={path}&mode=open&sid={sid}&&_sid={sid}'
    uri=uri.format(path=nas_dir+nas_file, sid=sid)
    headers = {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36',
            'Content-Type': 'application/octet-stream',
            'Content-Disposition': 'attachment'
        }
    req=requests.request('GET',uri, headers=headers)
    if not req.content.startswith(b'<!DOCTYPE html>'):
        with open(local_dir+nas_file, 'wb') as f:
            f.write(req.content)
    else:
        print('文件:%s 下载失败' % nas_file)


# In[45]:


# 上传文件

def upload():
    print('上传...')
    try:
        with open(os.path.join(local_dir,local_file_u), 'rb') as payload:
            args = {
                'path': nas_dir_u,
                'create_parents': 'true',
                'overwrite': 'true'
            } 
            files = {'file': (local_file_u, payload, 'application/octet-stream')}      
            uri=server + r'/webapi/entry.cgi?api=SYNO.FileStation.Upload&version=2&method=upload&_sid=' + sid
            req=requests.post(uri, data=args, files=files, verify=True)
            print(req.json())
    except Exception as e:
        print('上传%s出错:%s' % (local_file_u,e))


# In[52]:


# 模板文件生成
def mycopy():
    print('拷贝...')
    file_dir='E:/12-速报/'
    dt=datetime.now()+timedelta(days=-1)
    file_ex='%02d.%02d' % (dt.month, dt.day)
    file_name=file_dir+'工务速报'+file_ex+'.xlsx'
    try:
        copyfile(file_dir + '工务速报_template.xlsx', file_name)
    except IOError as e:
        print('不能拷贝文件:', e)
        exit(1)
    except:
        print("未预期的错误:", sys.exc_info())
        exit(1)
    print('拷贝成功')
    # 修改数据
    book=openpyxl.load_workbook(file_name)
    sheet=book['模板']
    sheet.title=file_ex

    cell_j='%d년  %02d 월 %02d 일' % (dt.year, dt.month, dt.day)
    sheet['J1']=cell_j

    book.save(file_name)


# In[ ]:


sid=login()


# In[63]:


# menu
if __name__ == '__main__':
    menu= '''
    选择操作:
    1、生成新速报文件
    2、下载生产的速报
    3、上传工务的速报
    4、退出
    '''
    print(menu)
    cmd = input('请输入1-4,m打印菜单:')
    while cmd != '4':
        if cmd == '1':
            mycopy()
        if cmd == '2':
            download()
        if cmd == '3':
            upload()
        if cmd == 'm':
            print(menu)
        if cmd == '4':
            break
        cmd = input('请输入1-4,m打印菜单:')
    logout()
            
    


# In[ ]:





评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

容沁风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值