manage.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. #啟動和管理項目
  2. from distutils.log import error
  3. from encodings import utf_8
  4. from multiprocessing import Value
  5. from app import create_app
  6. from flask import render_template, request, session
  7. import paramiko
  8. import git
  9. import shutil
  10. from time import sleep as sl
  11. from threading import Lock
  12. import threading
  13. from concurrent.futures import ThreadPoolExecutor
  14. import csv
  15. import os
  16. import stat
  17. import time
  18. # app, db, mqtt, socketio = create_app() # Rita 0428
  19. app, db, mqtt = create_app()
  20. thread = None
  21. thread_lock = Lock()
  22. # Rita 0428
  23. # @socketio.on('connect_event', namespace='/test_conn')
  24. # def connected_msg(msg):
  25. # print("connect success")
  26. # print(msg)
  27. # socketio.emit('stdout', 'success', namespace='/test_conn')
  28. # print(socketio)
  29. D = {"item_name":0, "command":0}
  30. # 0411 shutil-rmtree 刪除 .get 唯讀檔
  31. # https://stackoverflow.com/questions/21261132/shutil-rmtree-to-remove-readonly-files
  32. def remove_readonly(func, path, _):
  33. os.chmod(path, stat.S_IWRITE)
  34. func(path)
  35. # # 建置伺服器的訪問路徑 -- 舊 保留 0413 測試
  36. # @app.route('/add_server', methods=['POST', 'GET'])
  37. # def add_server_views():
  38. # username = session['uname']
  39. # L = []
  40. # if request.method == 'GET':
  41. # # 0407 測試註解一下
  42. # # repo = git.Repo.init(path='.')
  43. # # new_repo = git.Repo.clone_from(url='http://60.250.156.230:3000/benson/TestSSH.git', to_path='../new')
  44. # # new_repo = git.Repo.clone_from(url='http://60.250.156.230:3000/rita/CoffeeProject.git', to_path='../new')
  45. # os.system('git clone -b sh --single-branch http://60.250.156.230:3000/Automatic_build_system/Automatically_install_files.git C:\\Users\\USER\\Rita\\operating\\sixthproject\\new')
  46. # # with open('/home/benson/Project/new/All_installv3.2.sh') as f:
  47. # with open('../new/coffeesystem.sh', encoding='utf-8') as f:
  48. # # content = f.read().split('-Dividing line-')
  49. # # D['item_name'] = content[0].split('\n')[1:]
  50. # # D['command'] = content[1].split('\n')
  51. # D['command'] = f.read().split('\n')
  52. # # print("D['command']: ", D['command'])
  53. # # # 0407 測試中暫時註解
  54. # # # with open('/home/benson/Project/new/Item.txt') as f:
  55. # # with open('../new/Item.txt') as f:
  56. # # D['item_name'] = f.read().split('\n')
  57. # # for item in D['item_name']:
  58. # # L.append('.'.join(item.split('.')[1:])) # 拿掉 '.'.join 的話會變成 [['python3', '8'], ['python3-pip'],
  59. # # os.remove('C:/Users/USER/Rita/operating/sixthproject/new/.git')
  60. # # os.system('rm -rf ../new/.git')
  61. # # os.chmod('../new/.git', stat.S_IWRITE)
  62. # # os.unlink('../new/.git')
  63. # # sl(6)
  64. # # shutil.rmtree('../new', ignore_errors=True, onerror=del_rw)
  65. # sl(3)
  66. # shutil.rmtree('../new', onerror=remove_readonly)
  67. # sl(3)
  68. # # os.rmdir('../new')
  69. # # sl(6)
  70. # # #刪除非空資料夾
  71. # # try:
  72. # # shutil.rmtree('../new', ignore_errors=True, onerror=del_rw)
  73. # # # os.remove('../new')
  74. # # print("=== DELETE ===")
  75. # # sl(1)
  76. # # except OSError as e:
  77. # # print(f"OSError:{e.strerror}") # Error:存取被拒。
  78. # # # print("L: ", L) # L: ['python3.8', 'python3-pip', 'git', ... , 'ROS-ubuntu-18.04-melodic']
  79. # # 0407 測試註解一下
  80. # # for i in range(0, len(D['item_name'])):
  81. # # item = D['item_name'][i].split('=')[-1].replace('"','')
  82. # # L.append(item)
  83. # # L = L[:-1]
  84. # # # 0411 測試
  85. # # D['command'] = [
  86. # # # 'cd /tmp/; pwd; sudo wget https://files.phpmyadmin.net/phpMyAdmin/5.1.0/phpMyAdmin-5.1.0-all-languages.tar.gz;tar -zxvf phpMyAdmin-5.1.0-all-languages.tar.gz;sudo rm phpMyAdmin-5.1.0-all-languages.tar.gz; sudo mv phpMyAdmin-5.1.0-all-languages /var/www/html/phpmyadmin;',
  87. # # 'cd /var/www/html/phpmyadmin; pwd; mkdir tmp;',
  88. # # 'cd /var/www/html/phpmyadmin; pwd; mkdir tmp;',
  89. # # 'cd; pwd;',
  90. # # 'pwd']
  91. # L2= []
  92. # for i in range(0, len(D['command'])):
  93. # if D['command'][i] == "'" or D['command'][i] == '' or "#" in D['command'][i] or D['command'][i] == ' ':
  94. # continue
  95. # L2.append(D['command'][i])
  96. # D['command'] = L2
  97. # # print("D['command'] = L2: ", D['command'])
  98. # # print("=============== D['item_name'] ===============")
  99. # # print(D['item_name'])
  100. # # print("=============== D['command'] ===============")
  101. # # print(D['command'])
  102. # # print("=============== CODE CHECK 3 ===============")
  103. # # content = D['item_name'] + D['command']
  104. # # for i in content:
  105. # # print(i)
  106. # return render_template('add_server.html', params=locals())
  107. # else:
  108. # item_install_fail = 0
  109. # d = request.form.to_dict()
  110. # ip = d['ip']
  111. # loginname = d['loginname']
  112. # username = d['username']
  113. # password = d['password']
  114. # print(ip)
  115. # print(loginname)
  116. # print(username)
  117. # print(password)
  118. # try:
  119. # # 建立一個sshclient物件
  120. # ssh = paramiko.SSHClient()
  121. # # 允許將信任的主機自動加入到host_allow 列表,此方法必須放在connect方法的前面
  122. # ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  123. # # 指定本地的RSA私鑰檔案,如果建立金鑰對時設定的有密碼,password為設定的密碼,如無不用指定password引數
  124. # # pkey = paramiko.RSAKey.from_private_key_file('/home/super/.ssh/id_rsa', password='12345')
  125. # # pkey = paramiko.RSAKey.from_private_key_file('/home/ptop/topicjie/scripts/keys/id_rsa')
  126. # # 建立連線
  127. # # ssh.connect(hostname=ip,
  128. # # port=22,
  129. # # username='gs1801',
  130. # # pkey=pkey)
  131. # # with open('/home/benson/test11.sh') as f:
  132. # # content = f.read().split('\n')[0:-1]
  133. # # print(content)
  134. # # L = []
  135. # # for i in range(0, len(D['ssh_content'])):
  136. # # if "#" in D['ssh_content'][i] or D['ssh_content'][i] == '' or D['ssh_content'][i] == ' ':
  137. # # continue
  138. # # L.append(D['ssh_content'][i])
  139. # # for i in L:
  140. # # print(i)
  141. # ssh.connect(hostname=ip,
  142. # port=22,
  143. # username=loginname,
  144. # password=password)
  145. # # 假如帳號密碼正確沒有被捕捉到異常,傳送訊息給前端
  146. # socketio.emit('user-confirm', 'pass', namespace='/test_conn')
  147. # # os.system("scp /home/benson/test10.sh gs1801@" + ip + ":/home/gs1801/")
  148. # # 執行命令
  149. # # stdin, stdout, stderr = ssh.exec_command("ls -l /home/gs1801;touch test7.py")
  150. # # stdin, stdout, stderr = ssh.exec_command("touch test10.sh;echo '" + content + "' >> test10.sh;bash test10.sh")
  151. # # print('test1')
  152. # # print(stdout.read().decode())
  153. # # print('test2')
  154. # # print(stderr.read().decode())
  155. # # content = D['item_name'] + D['command']
  156. # with open('ItemFile.csv', 'w', newline='') as csvFile:
  157. # csvWriter = csv.writer(csvFile)
  158. # csvWriter.writerow(['Command', 'Install Content', 'Time', 'Status'])
  159. # # # Rita 0406 TEST
  160. # D['command'] = [
  161. # # 'sudo pip3 install cryptography==3.3.2
  162. # ]
  163. # for command in D['command']:
  164. # if '使用者' in command :
  165. # command = command.replace('使用者', username)
  166. # print(command)
  167. # stdin, stdout, stderr = ssh.exec_command(command)
  168. # command_start_time = time.time()
  169. # # sl(6) # Rita 原本為 sl(6) 增加後觀察是否 clone 輸出會改變
  170. # # Rita 0406 stdout(success)、stderr(error) 每次只會輸出其中一個, 以此做為判斷, 例如:
  171. # # print('=========================================')
  172. # # print('stdout: ', stdout.read().decode())
  173. # # print('stderr: ', stderr.read().decode())
  174. # # print('=========================================')
  175. # # 輸出為:
  176. # # =========================================
  177. # # stdout: 正在讀取套件清單...
  178. # # 正在重建相依關係...
  179. # # 正在讀取狀態資料...
  180. # # python3.8 is already the newest version (3.8.0-3ubuntu1~18.04.2).
  181. # # 升級 0 個,新安裝 0 個,移除 0 個,有 208 個未被升級。
  182. # # stderr:
  183. # # =========================================
  184. # error = stderr.read().decode()
  185. # success = stdout.read().decode()
  186. # # print('error: ', error, '\nlen(error): ', len(error))
  187. # print('error: ', error, '\nlen(error): ')
  188. # print('success: ', success, '\nlen(success): ')
  189. # if len(success) > 200000:
  190. # success = success[0:20000] + '... etc'
  191. # execution_time = round(time.time() - command_start_time, 3)
  192. # if error:
  193. # print('error')
  194. # print(error)
  195. # if item_install_fail == 0:
  196. # item_install_fail = 1
  197. # with open('ItemFile.csv', 'a', newline='') as csvFile:
  198. # csvWriter = csv.writer(csvFile)
  199. # csvWriter.writerow([command.replace(';', ';\n'),
  200. # 'success: \n' + success + '\n' + 'error: \n' + error,
  201. # # 'success: \n' + success,
  202. # # 'error: \n' + error,
  203. # execution_time,
  204. # 'error'])
  205. # socketio.emit('stderr', error, namespace='/test_conn')
  206. # else:
  207. # print('success')
  208. # print(success)
  209. # with open('ItemFile.csv', 'a', newline='') as csvFile:
  210. # csvWriter = csv.writer(csvFile)
  211. # csvWriter.writerow([command.replace(';', ';\n'),
  212. # 'success: \n' + success + '\nerror: \n' + error,
  213. # execution_time,
  214. # 'success'])
  215. # socketio.emit('stdout', success, namespace='/test_conn')
  216. # sl(1)
  217. # print('-----------------------------------------------------------------------------')
  218. # # Rita 0406 本來就註解
  219. # # def sshJob():
  220. # # for command in content:
  221. # # stdin, stdout, stderr = ssh.exec_command(command)
  222. # # #
  223. # # # # print(stdout.read().decode())
  224. # # # # print('----------------------------------------')
  225. # # # # print(stderr.read().decode())
  226. # # #
  227. # # print(stdin)
  228. # # if stderr.read().decode():
  229. # # L.append(0)
  230. # # print('error')
  231. # # socketio.emit('stderr', stderr.read().decode())
  232. # # else:
  233. # # L.append(1)
  234. # # print('success')
  235. # # socketio.emit('stdout', stdout.read().decode())
  236. # # sl(5)
  237. # # ssh.close()
  238. # # Rita 0406 本來就註解
  239. # # def sshJob():
  240. # # sl(5)
  241. # # i = 0
  242. # # total = len(content)
  243. # # while True:
  244. # # stdin, stdout, stderr = ssh.exec_command(content[i])
  245. # # #
  246. # # # # print(stdout.read().decode())
  247. # # # # print('----------------------------------------')
  248. # # # # print(stderr.read().decode())
  249. # # #
  250. # # if stderr.read().decode():
  251. # # L.append(0)
  252. # # print('error')
  253. # # socketio.emit('stderr', stderr.read().decode())
  254. # # else:
  255. # # L.append(1)
  256. # # print('success')
  257. # # socketio.emit('stdout', stdout.read().decode())
  258. # # sl(5)
  259. # # i += 1
  260. # # if i == total:
  261. # # break
  262. # # ssh.close()
  263. # # ssh_thread = threading.Thread(target=sshJob)
  264. # # ssh_thread.daemon = True
  265. # # ssh_thread.start()
  266. # # global thread
  267. # # with thread_lock:
  268. # # if thread is None:
  269. # # thread = socketio.start_background_task(target=sshJob)
  270. # # print(L)
  271. # #
  272. # # item_list = ItemList()
  273. # # item_list.ip = ip
  274. # # item_list.pymysql = L[0]
  275. # # item_list.eventlet = L[1]
  276. # # datetime = dt.now()
  277. # # item_list.datetime = datetime
  278. # # db.session.add(item_list)
  279. # # db.session.commit()
  280. # # 關閉寫入的 CSV 檔案
  281. # csvFile.close()
  282. # # 關閉連線
  283. # ssh.close()
  284. # if item_install_fail:
  285. # res = '有套件未安裝完成!'
  286. # else:
  287. # res = '建置完成!'
  288. # return res
  289. # except Exception as e:
  290. # print(e)
  291. # return str(e)
  292. Automatic_Build_System = {
  293. 'python3.8': '0',
  294. 'python3-pip': '0',
  295. 'cryptography': '0',
  296. 'upgrade': '0',
  297. 'grep': '0',
  298. 'git': '0',
  299. 'gitpython': '0',
  300. 'python3-tk': '0',
  301. 'wget': '0',
  302. 'python3-dev': '0',
  303. 'default-libmysqlclient-dev': '0',
  304. 'build-essential': '0',
  305. 'tasksel': '0',
  306. 'lamp-server': '0',
  307. 'phpMyAdmin-5.1.0-all-languages.tar.gz': '0',
  308. 'openssl': '0',
  309. 'php-common': '0',
  310. 'php-curl': '0',
  311. 'php-json': '0',
  312. 'php-mbstring': '0',
  313. 'php-mysql': '0',
  314. 'php-xml': '0',
  315. 'php-zip': '0',
  316. 'php7.2-mbstring': '0',
  317. 'php7.2-xml': '0',
  318. 'php7.2-mysql': '0',
  319. 'php7.2-common': '0',
  320. 'php7.2-curl': '0',
  321. 'php7.2-json': '0',
  322. 'php7.2-zip': '0',
  323. 'apache2': '0',
  324. 'paho-mqtt': '0',
  325. 'mosquitto': '0',
  326. 'mqtt_server_setting': '0',
  327. 'rclocal/rc.local': '0',
  328. 'golang': '0',
  329. 'gogsfile': '0',
  330. 'requirements': '0',
  331. 'CoffeeProject': '0',
  332. 'BBend-Test-JWT': '0',
  333. 'Coffee_MySQL': '0',
  334. 'chrony': '0',
  335. 'ntpdate': '0',
  336. '--keyserver': '0',
  337. 'update': '0',
  338. 'ros-melodic-desktop-full': '0',
  339. 'ros-melodic-rqt*': '0',
  340. 'python-rosdep': '0',
  341. 'python-rosinstall': '0',
  342. 'python-rosinstall-generator': '0',
  343. 'python-wstool': '0',
  344. 'catkin_make': '0'
  345. }
  346. @app.route('/ABS_update', methods=['POST', 'GET'])
  347. def ABS_update():
  348. return Automatic_Build_System
  349. # 0413 測試中, 原版在上方
  350. @app.route('/add_server', methods=['POST', 'GET'])
  351. def add_server_views():
  352. username = session['uname']
  353. L = []
  354. CURRENT_PATH = os.path.dirname(__file__)
  355. # C:\Users\USER\Rita\operating\sixthproject\BBend-Test-JWT 同 manage.py 路徑
  356. print("CURRENT_PATH: ", CURRENT_PATH)
  357. if request.method == 'GET':
  358. with open(CURRENT_PATH + '/Item.txt') as f:
  359. D['item_name'] = f.read().split('\n')
  360. for item in D['item_name']:
  361. # L.append('.'.join(item.split('.')[1:])) # 拿掉 '.'.join 的話會變成 [['python3', '8'], ['python3-pip'],
  362. L.append(item)
  363. # STATUS = session['status']
  364. return render_template('add_server.html', params=locals())
  365. else:
  366. item_install_fail = 0
  367. d = request.form.to_dict()
  368. ip = d['ip']
  369. loginname = d['loginname']
  370. username = d['username']
  371. password = d['password']
  372. item1 = d['item1_checked']
  373. item2 = d['item2_checked']
  374. item3 = d['item3_checked']
  375. item4 = d['item4_checked']
  376. item5 = d['item5_checked']
  377. item6 = d['item6_checked']
  378. item7 = d['item7_checked']
  379. item8 = d['item8_checked']
  380. print(d)
  381. try:
  382. # Rita 0428 測試
  383. # 建立一個sshclient物件
  384. ssh = paramiko.SSHClient()
  385. # 允許將信任的主機自動加入到host_allow 列表,此方法必須放在connect方法的前面
  386. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  387. # 指定本地的RSA私鑰檔案,如果建立金鑰對時設定的有密碼,password為設定的密碼,如無不用指定password引數
  388. # pkey = paramiko.RSAKey.from_private_key_file('/home/super/.ssh/id_rsa', password='12345')
  389. # pkey = paramiko.RSAKey.from_private_key_file('/home/ptop/topicjie/scripts/keys/id_rsa')
  390. # 建立連線
  391. ssh.connect(hostname=ip,
  392. port=22,
  393. username=loginname,
  394. password=password)
  395. # 假如帳號密碼正確沒有被捕捉到異常,傳送訊息給前端
  396. # socketio.emit('user-confirm', 'pass', namespace='/test_conn')
  397. with open(CURRENT_PATH + '/ItemFile.csv', 'w', newline='') as csvFile:
  398. csvWriter = csv.writer(csvFile)
  399. csvWriter.writerow(['Command', 'Install Content', 'Time', 'Status'])
  400. for item_num in range(1, 9):
  401. # if item1 == 'true':
  402. if eval("item" + str(item_num)) == 'true':
  403. print('========== item ' + str(item_num) + ' install ====================================')
  404. # 下載資料夾
  405. 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) + '')
  406. with open( CURRENT_PATH + '/item' + str(item_num) + '/item' + str(item_num) + '.sh', encoding='utf-8') as f:
  407. D['command'] = f.read().split('\n')
  408. sl(1)
  409. # 刪除下載資料夾
  410. shutil.rmtree( CURRENT_PATH + '/item' + str(item_num) + '', onerror=remove_readonly)
  411. # 移除不需要執行之指令
  412. sl(1)
  413. L2= []
  414. for i in range(0, len(D['command'])):
  415. if D['command'][i] == "'" or D['command'][i] == '' or "#" in D['command'][i] or D['command'][i] == ' ':
  416. continue
  417. L2.append(D['command'][i])
  418. D['command'] = L2
  419. # 0510 Rita 測試
  420. for command in D['command']:
  421. if '使用者' in command :
  422. command = command.replace('使用者', username)
  423. if 'sudo apt-get install' in command :
  424. command = command.replace('sudo apt-get install', "sudo DEBIAN_FRONTEND=noninteractive apt-get install")
  425. print(command)
  426. # 判斷若此 command 符合 Automatic_Build_System 的 Key, 則改變狀態
  427. for key, value in Automatic_Build_System.items():
  428. if key in command and value == '0':
  429. # print('key: ', key, ' / command: ', command)
  430. Automatic_Build_System[key] = "Install"
  431. sl(1)
  432. command_start_time = time.time()
  433. # 0504 Rita 測試
  434. stdin, stdout, stderr = ssh.exec_command(command)
  435. error = stderr.read().decode()
  436. success = stdout.read().decode()
  437. # print('error: ', error, '\nlen(error): ', len(error))
  438. print('error: ', error)
  439. print('success: ', success)
  440. if len(success) > 200000:
  441. success = success[0:20000] + '... etc'
  442. execution_time = round(time.time() - command_start_time, 3)
  443. if error:
  444. # 排除 錯誤訊息中的 警告訊息
  445. Warning_list = [
  446. "WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager.",
  447. "Cloning into",
  448. "Warning: apt-key output should not be parsed (stdout is not a terminal)",
  449. "gpg",
  450. "Warning: running 'rosdep update' as root is not recommended.",
  451. "You should run",
  452. "[Warning] Using a password on the command line interface can be insecure."
  453. ]
  454. error_command_list = error.split('\n')
  455. for_error_command_list = error_command_list.copy()
  456. for cl in range(0, len(error_command_list)):
  457. for W in range(len(Warning_list)):
  458. try:
  459. if Warning_list[W] in error_command_list[cl]:
  460. for_error_command_list.remove(error_command_list[cl])
  461. except IndexError:
  462. pass
  463. if for_error_command_list == [''] or for_error_command_list == []:
  464. print('=== Warning ===')
  465. with open(CURRENT_PATH + '/ItemFile.csv', 'a', newline='') as csvFile:
  466. csvWriter = csv.writer(csvFile)
  467. csvWriter.writerow([command.replace(';', ';\n'),
  468. 'success: \n' + success + '\n' + 'error: \n' + error,
  469. execution_time,
  470. 'warning'])
  471. # 判斷若此 command 符合 Automatic_Build_System 的 Key, 則改變狀態
  472. for key, value in Automatic_Build_System.items():
  473. if key in command:
  474. Automatic_Build_System[key] = execution_time
  475. else:
  476. print('for_error_command_list: ', for_error_command_list)
  477. print('=== error ===')
  478. if item_install_fail == 0:
  479. item_install_fail = 1
  480. with open(CURRENT_PATH + '/ItemFile.csv', 'a', newline='') as csvFile:
  481. csvWriter = csv.writer(csvFile)
  482. csvWriter.writerow([command.replace(';', ';\n'),
  483. 'success: \n' + success + '\n' + 'error: \n' + error,
  484. execution_time,
  485. 'error'])
  486. # 判斷若此 command 符合 Automatic_Build_System 的 Key, 則改變狀態
  487. for key, value in Automatic_Build_System.items():
  488. if key in command:
  489. Automatic_Build_System[key] = "Error"
  490. else:
  491. print('=== success ===')
  492. with open(CURRENT_PATH + '/ItemFile.csv', 'a', newline='') as csvFile:
  493. csvWriter = csv.writer(csvFile)
  494. csvWriter.writerow([command.replace(';', ';\n'),
  495. 'success: \n' + success + '\nerror: \n' + error,
  496. execution_time,
  497. 'success'])
  498. # 判斷若此 command 符合 Automatic_Build_System 的 Key, 則改變狀態
  499. for key, value in Automatic_Build_System.items():
  500. if key in command:
  501. Automatic_Build_System[key] = execution_time
  502. sl(5) # Rita 原本為 sl(6) 增加後觀察是否 clone 輸出會改變
  503. print('-----------------------------------------------------------------------------')
  504. # stdin, stdout, stderr = ssh.exec_command("sudo systemctl restart rc-local.service")
  505. sl(5)
  506. # stdin, stdout, stderr = ssh.exec_command("sudo reboot")
  507. with open( CURRENT_PATH + '/ItemFile.csv', 'a', newline='') as csvFile:
  508. csvWriter = csv.writer(csvFile)
  509. csvWriter.writerow(['',
  510. 'Automatic_Build_System: \n' + str(Automatic_Build_System),
  511. '',
  512. ''])
  513. # 關閉連線
  514. ssh.close()
  515. if item_install_fail:
  516. res = '有套件未安裝完成!'
  517. else:
  518. res = '建置完成!'
  519. return res
  520. except Exception as e:
  521. print(e)
  522. return str(e)
  523. #mqtt發布
  524. @app.route('/mqtt', methods=['GET','POST'])
  525. def mqtt_views():
  526. import json
  527. dict = request.args.to_dict()
  528. json = json.dumps(dict)
  529. print(json)
  530. mqtt.publish('AISKY/AppleFarm/MK-G/b8:27:eb:f8:24:92', json)
  531. return "Publish done"
  532. #mqtt訂閱
  533. @mqtt.on_connect()
  534. def handle_connect(client, userdata, flags, rc):
  535. mqtt.subscribe('AISKY/AppleFarm/MK-G/b8:27:eb:f8:24:92/Log')
  536. #處理mqtt訂閱的信息
  537. @mqtt.on_message()
  538. def handle_mqtt_message(client, userdata, message):
  539. payload = message.payload.decode()
  540. # p = json.loads(payload)
  541. # print("-------msg-------")
  542. # print('name :', p['name'])
  543. # print('email :', p['email'])
  544. print(payload)
  545. #調用日誌訊息
  546. @mqtt.on_log()
  547. def handle_logging(client, userdata, level, buf):
  548. print(level, buf)
  549. #自動關閉所有未使用、掛著的連接
  550. @app.teardown_appcontext
  551. def shutdown_session(exception=None):
  552. db.session.remove()
  553. if __name__ == '__main__':
  554. # Rita 0406 socketio.run(app, debug=True, host='0.0.0.0', port=5014)
  555. # Rita 0406 app.run(debug=True, host='0.0.0.0', port=5014)
  556. # print("===== BBend =====")
  557. # socketio.run(app, debug=True, host='0.0.0.0', port=5014)
  558. app.run(debug=True, host='0.0.0.0', port=5014)