autoback.py 5.0 KB
# codinf:utf-8
import os
import time
from flask import render_template, Response, request,redirect,url_for
from werkzeug.utils import secure_filename
from app import app
import logging
import pexpect
import json
import zipfile
import shutil
import csv
import requests
import re
from config import Config

basepath = os.path.dirname(__file__)

def backup():
    try:
        source_dir = '/prog/backup/'
        today = source_dir + time.strftime('%Y%m%d')
        if not os.path.exists(today):
            os.mkdir(today)
        cmd = "cp -rf /prog/smartshelf/* /prog/backup/{}/".format(time.strftime('%Y%m%d'))
        run = pexpect.spawn('su -c "%s" root' %cmd)
        time.sleep(2)
        run.sendline('xxx')
        logging.warning("备份成功")
    except Exception as e:
        logging.warning("备份失败:{}".format(e))

def read_ip():
    uploads_path = basepath + Config.STATE_PATH
    with open(uploads_path + 'ipconfig.csv','r') as f:
        reader = csv.reader(f)
        current = [row for row in reader]
        ip = current[0][0]
    return ip

from app.utils.g import ver
def read_version():
    return ver()


@app.route('/upgrade',methods=['POST'])
def upgrade():
    ip = read_ip()
    ip = ip.replace('/myproject', '')
    # ip = 'http://192.168.1.99'
    download_url = '{}/download/version.txt'.format(ip)
    logging.warning("服务器最新版本信息:{}".format(download_url))
    try:
        response = requests.get(download_url)
        if response.status_code == 200:
            version = response.json()
            s_version = read_version()
            logging.warning("当前版本:{},最新版本:{}".format(s_version,version))
            if str(s_version) == str(version):
                info = {'operation':'当前版本已是最新版本!'}
            else:
                download_zip(ip,version)
                backup()
                time.sleep(2)
                process_file()
                time.sleep(2)
                reboot()
                info = {'operation':'已升级到最新版本'}
        else:
            info = {'operation':'服务器地址错误'}
    except Exception as e:
        logging.warning("发生错误:{}".format(e))
        info = {'operation':'Error'}
    return json.dumps(info)

def download_zip(ip,version):
    zip_url = '{}/download/{}.zip'.format(ip,version)
    logging.warning("服务器最新文件:{}".format(zip_url))
    target_path = '/prog/upgrade_cach/smartshelf.zip'
    File=requests.get(zip_url, stream=True)
    with open(target_path,'wb+') as f:
        for chunk in File.iter_content(chunk_size=1024):
            if chunk:
                f.write(chunk)
    f.close()



def process_file():
    zfile = zipfile.ZipFile('/prog/upgrade_cach/smartshelf.zip','r')
    path2 = '/prog/update/smartshelf/'
    n_train = 0
    for filename in zfile.namelist():
        if filename.endswith('/'):
            n_train += 1
            os.makedirs(os.path.join(path2, filename))
        else:
            data = zfile.read(filename)
            file = open(os.path.join(path2, filename), 'w+b')
            file.write(data)
            file.close()
    time.sleep(5)
    py_source = '/prog/update/smartshelf/app/'
    templates_source = '/prog/update/smartshelf/app/templates/'
    py_target = '/prog/smartshelf/app/'
    template_target = '/prog/smartshelf/app/templates/'
    templates_lis = os.listdir(path=templates_source)
    py_lis = os.listdir(path=py_source)
    logging.warning("待更新文件:{},{}".format(py_lis,templates_lis))
    for t_file in templates_lis:
        t_filename = os.path.join(templates_source,t_file)
        if os.path.isfile(t_filename):
            try:
               shutil.copy(t_filename, template_target)
            except IOError as e:
                logging.warning("Unable to copy file. %s" % e)
               # print("Unable to copy file. %s" % e)
            except Exception as e:
                logging.warning("Unexpected error: %s" % e)
    for p_file in py_lis:
        p_filename = os.path.join(py_source,p_file)
        if os.path.isfile(p_filename):
            try:
               shutil.copy(p_filename, py_target)
            except IOError as e:
               logging.warning("Unable to copy file. %s" % e)
            except Exception as e:
               logging.warning("Unexpected error: %s" % e)
    shutil.rmtree(path2)
    os.remove('/prog/upgrade_cach/smartshelf.zip')
    # shutil.rmtree('/prog/upgrade_cach/')
    logging.warning("templates upgrade success")

def reboot():
    os.system('/prog/./restart.sh')

def openteam():
    # os.system('/usr/bin/./teamviwer')
    cmd = "nohub /opt/teamviewer/tv_bin/TeamViewer"
    run = pexpect.spawn('su -c "%s" root' %cmd)
    time.sleep(0.5)
    run.sendline('xxx')
    # cmd1 = "./teamviwer"
    # run1 = pexpect.spawn('su -c "%s" root' %cmd1)
    # time.sleep(0.5)
    # run1.sendline('xxx')
    logging.warning("teamview open")

@app.route('/openteamview',methods=['POST'])
def openteamview():
    openteam()
    info = {'operation':'已打开teamview'}
    return json.dumps(info)