123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616 |
- from distutils.log import error
- from encodings import utf_8
- from multiprocessing import Value
- from app import create_app
- from flask import render_template, request, session
- import paramiko
- import git
- import shutil
- from time import sleep as sl
- from threading import Lock
- import threading
- from concurrent.futures import ThreadPoolExecutor
- import csv
- import os
- import stat
- import time
- app, db, mqtt = create_app()
- thread = None
- thread_lock = Lock()
- D = {"item_name":0, "command":0}
- def remove_readonly(func, path, _):
- os.chmod(path, stat.S_IWRITE)
- func(path)
-
-
-
-
-
- Automatic_Build_System = {
- 'python3.8': '0',
- 'python3-pip': '0',
- 'cryptography': '0',
- 'upgrade': '0',
- 'grep': '0',
- 'git': '0',
- 'gitpython': '0',
- 'python3-tk': '0',
- 'wget': '0',
- 'python3-dev': '0',
- 'default-libmysqlclient-dev': '0',
- 'build-essential': '0',
- 'tasksel': '0',
- 'lamp-server': '0',
- 'phpMyAdmin-5.1.0-all-languages.tar.gz': '0',
- 'openssl': '0',
- 'php-common': '0',
- 'php-curl': '0',
- 'php-json': '0',
- 'php-mbstring': '0',
- 'php-mysql': '0',
- 'php-xml': '0',
- 'php-zip': '0',
- 'php7.2-mbstring': '0',
- 'php7.2-xml': '0',
- 'php7.2-mysql': '0',
- 'php7.2-common': '0',
- 'php7.2-curl': '0',
- 'php7.2-json': '0',
- 'php7.2-zip': '0',
- 'apache2': '0',
- 'paho-mqtt': '0',
- 'mosquitto': '0',
- 'mqtt_server_setting': '0',
- 'rclocal/rc.local': '0',
- 'golang': '0',
- 'gogsfile': '0',
- 'requirements': '0',
- 'CoffeeProject': '0',
- 'BBend-Test-JWT': '0',
- 'Coffee_MySQL': '0',
- 'chrony': '0',
- 'ntpdate': '0',
- '--keyserver': '0',
- 'update': '0',
- 'ros-melodic-desktop-full': '0',
- 'ros-melodic-rqt*': '0',
- 'python-rosdep': '0',
- 'python-rosinstall': '0',
- 'python-rosinstall-generator': '0',
- 'python-wstool': '0',
- 'catkin_make': '0'
- }
- @app.route('/ABS_update', methods=['POST', 'GET'])
- def ABS_update():
- return Automatic_Build_System
- @app.route('/add_server', methods=['POST', 'GET'])
- def add_server_views():
- username = session['uname']
- L = []
- CURRENT_PATH = os.path.dirname(__file__)
- print("CURRENT_PATH: ", CURRENT_PATH)
-
- if request.method == 'GET':
- with open(CURRENT_PATH + '/Item.txt') as f:
- D['item_name'] = f.read().split('\n')
- for item in D['item_name']:
-
- L.append(item)
-
- return render_template('add_server.html', params=locals())
- else:
- item_install_fail = 0
- d = request.form.to_dict()
- ip = d['ip']
- loginname = d['loginname']
- username = d['username']
- password = d['password']
- item1 = d['item1_checked']
- item2 = d['item2_checked']
- item3 = d['item3_checked']
- item4 = d['item4_checked']
- item5 = d['item5_checked']
- item6 = d['item6_checked']
- item7 = d['item7_checked']
- item8 = d['item8_checked']
- print(d)
- try:
-
-
- ssh = paramiko.SSHClient()
-
- ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
-
-
-
-
- ssh.connect(hostname=ip,
- port=22,
- username=loginname,
- password=password)
-
-
- with open(CURRENT_PATH + '/ItemFile.csv', 'w', newline='') as csvFile:
- csvWriter = csv.writer(csvFile)
- csvWriter.writerow(['Command', 'Install Content', 'Time', 'Status'])
-
- for item_num in range(1, 9):
-
- if eval("item" + str(item_num)) == 'true':
- print('========== item ' + str(item_num) + ' install ====================================')
-
- os.system('git clone -b item' + str(item_num) + ' --single-branch http://60.250.156.230:3000/Automatic_build_system/Automatically_install_files.git ' + CURRENT_PATH + '/item' + str(item_num) + '')
- with open( CURRENT_PATH + '/item' + str(item_num) + '/item' + str(item_num) + '.sh', encoding='utf-8') as f:
- D['command'] = f.read().split('\n')
- sl(1)
-
- shutil.rmtree( CURRENT_PATH + '/item' + str(item_num) + '', onerror=remove_readonly)
-
-
- sl(1)
- L2= []
- for i in range(0, len(D['command'])):
- if D['command'][i] == "'" or D['command'][i] == '' or "#" in D['command'][i] or D['command'][i] == ' ':
- continue
- L2.append(D['command'][i])
- D['command'] = L2
-
- for command in D['command']:
- if '使用者' in command :
- command = command.replace('使用者', username)
- if 'sudo apt-get install' in command :
- command = command.replace('sudo apt-get install', "sudo DEBIAN_FRONTEND=noninteractive apt-get install")
- print(command)
-
- for key, value in Automatic_Build_System.items():
- if key in command and value == '0':
-
- Automatic_Build_System[key] = "Install"
- sl(1)
- command_start_time = time.time()
-
- stdin, stdout, stderr = ssh.exec_command(command)
- error = stderr.read().decode()
- success = stdout.read().decode()
-
- print('error: ', error)
- print('success: ', success)
- if len(success) > 200000:
- success = success[0:20000] + '... etc'
-
- execution_time = round(time.time() - command_start_time, 3)
- if error:
-
- Warning_list = [
- "WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager.",
- "Cloning into",
- "Warning: apt-key output should not be parsed (stdout is not a terminal)",
- "gpg",
- "Warning: running 'rosdep update' as root is not recommended.",
- "You should run",
- "[Warning] Using a password on the command line interface can be insecure."
- ]
- error_command_list = error.split('\n')
- for_error_command_list = error_command_list.copy()
- for cl in range(0, len(error_command_list)):
- for W in range(len(Warning_list)):
- try:
- if Warning_list[W] in error_command_list[cl]:
- for_error_command_list.remove(error_command_list[cl])
- except IndexError:
- pass
- if for_error_command_list == [''] or for_error_command_list == []:
- print('=== Warning ===')
- with open(CURRENT_PATH + '/ItemFile.csv', 'a', newline='') as csvFile:
- csvWriter = csv.writer(csvFile)
- csvWriter.writerow([command.replace(';', ';\n'),
- 'success: \n' + success + '\n' + 'error: \n' + error,
- execution_time,
- 'warning'])
-
- for key, value in Automatic_Build_System.items():
- if key in command:
- Automatic_Build_System[key] = execution_time
- else:
- print('for_error_command_list: ', for_error_command_list)
- print('=== error ===')
- if item_install_fail == 0:
- item_install_fail = 1
- with open(CURRENT_PATH + '/ItemFile.csv', 'a', newline='') as csvFile:
- csvWriter = csv.writer(csvFile)
- csvWriter.writerow([command.replace(';', ';\n'),
- 'success: \n' + success + '\n' + 'error: \n' + error,
- execution_time,
- 'error'])
-
- for key, value in Automatic_Build_System.items():
- if key in command:
- Automatic_Build_System[key] = "Error"
- else:
- print('=== success ===')
- with open(CURRENT_PATH + '/ItemFile.csv', 'a', newline='') as csvFile:
- csvWriter = csv.writer(csvFile)
- csvWriter.writerow([command.replace(';', ';\n'),
- 'success: \n' + success + '\nerror: \n' + error,
- execution_time,
- 'success'])
-
- for key, value in Automatic_Build_System.items():
- if key in command:
- Automatic_Build_System[key] = execution_time
-
- sl(5)
- print('-----------------------------------------------------------------------------')
-
-
- sl(5)
-
- with open( CURRENT_PATH + '/ItemFile.csv', 'a', newline='') as csvFile:
- csvWriter = csv.writer(csvFile)
- csvWriter.writerow(['',
- 'Automatic_Build_System: \n' + str(Automatic_Build_System),
- '',
- ''])
-
- ssh.close()
- if item_install_fail:
- res = '有套件未安裝完成!'
- else:
- res = '建置完成!'
- return res
- except Exception as e:
- print(e)
- return str(e)
- @app.route('/mqtt', methods=['GET','POST'])
- def mqtt_views():
- import json
- dict = request.args.to_dict()
- json = json.dumps(dict)
- print(json)
- mqtt.publish('AISKY/AppleFarm/MK-G/b8:27:eb:f8:24:92', json)
- return "Publish done"
- @mqtt.on_connect()
- def handle_connect(client, userdata, flags, rc):
- mqtt.subscribe('AISKY/AppleFarm/MK-G/b8:27:eb:f8:24:92/Log')
- @mqtt.on_message()
- def handle_mqtt_message(client, userdata, message):
- payload = message.payload.decode()
-
-
-
-
- print(payload)
- @mqtt.on_log()
- def handle_logging(client, userdata, level, buf):
- print(level, buf)
- @app.teardown_appcontext
- def shutdown_session(exception=None):
- db.session.remove()
- if __name__ == '__main__':
-
-
-
-
- app.run(debug=True, host='0.0.0.0', port=5014)
|