manage.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. #啟動和管理項目
  2. from app import create_app
  3. from flask import render_template, request, session
  4. import paramiko
  5. import git
  6. import shutil
  7. from time import sleep as sl
  8. from threading import Lock
  9. import threading
  10. from concurrent.futures import ThreadPoolExecutor
  11. import csv
  12. app, db, mqtt, socketio = create_app()
  13. thread = None
  14. thread_lock = Lock()
  15. @socketio.on('connect_event', namespace='/test_conn')
  16. def connected_msg(msg):
  17. print("connect success")
  18. print(msg)
  19. socketio.emit('stdout', 'success', namespace='/test_conn')
  20. print(socketio)
  21. D = {"item_name":0, "command":0}
  22. #建置伺服器的訪問路徑
  23. @app.route('/add_server', methods=['POST', 'GET'])
  24. def add_server_views():
  25. username = session['uname']
  26. L = []
  27. if request.method == 'GET':
  28. repo = git.Repo.init(path='.')
  29. new_repo = git.Repo.clone_from(url='http://60.250.156.230:3000/benson/TestSSH.git', to_path='../new')
  30. with open('/home/benson/Project/new/All_installv3.2.sh') as f:
  31. # content = f.read().split('-Dividing line-')
  32. # D['item_name'] = content[0].split('\n')[1:]
  33. # D['command'] = content[1].split('\n')
  34. D['command'] = f.read().split('\n')
  35. with open('/home/benson/Project/new/Item.txt') as f:
  36. D['item_name'] = f.read().split('\n')
  37. for item in D['item_name']:
  38. L.append('.'.join(item.split('.')[1:]))
  39. #刪除非空資料夾
  40. try:
  41. shutil.rmtree('/home/benson/Project/new')
  42. except OSError as e:
  43. print(f"Error:{e.strerror}")
  44. # for i in range(0, len(D['item_name'])):
  45. # item = D['item_name'][i].split('=')[-1].replace('"','')
  46. # L.append(item)
  47. # L = L[:-1]
  48. L2= []
  49. for i in range(0, len(D['command'])):
  50. if D['command'][i] == "'" or D['command'][i] == '' or "#" in D['command'][i] or D['command'][i] == ' ':
  51. continue
  52. L2.append(D['command'][i])
  53. D['command'] = L2
  54. print(D['item_name'])
  55. print(D['command'])
  56. # content = D['item_name'] + D['command']
  57. # for i in content:
  58. # print(i)
  59. return render_template('add_server.html', params=locals())
  60. else:
  61. item_install_fail = 0
  62. d = request.form.to_dict()
  63. ip = d['ip']
  64. username = d['username']
  65. password = d['password']
  66. print(ip)
  67. print(username)
  68. print(password)
  69. try:
  70. # 建立一個sshclient物件
  71. ssh = paramiko.SSHClient()
  72. # 允許將信任的主機自動加入到host_allow 列表,此方法必須放在connect方法的前面
  73. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  74. # 指定本地的RSA私鑰檔案,如果建立金鑰對時設定的有密碼,password為設定的密碼,如無不用指定password引數
  75. # pkey = paramiko.RSAKey.from_private_key_file('/home/super/.ssh/id_rsa', password='12345')
  76. # pkey = paramiko.RSAKey.from_private_key_file('/home/ptop/topicjie/scripts/keys/id_rsa')
  77. # 建立連線
  78. # ssh.connect(hostname=ip,
  79. # port=22,
  80. # username='gs1801',
  81. # pkey=pkey)
  82. # with open('/home/benson/test11.sh') as f:
  83. # content = f.read().split('\n')[0:-1]
  84. # print(content)
  85. # L = []
  86. # for i in range(0, len(D['ssh_content'])):
  87. # if "#" in D['ssh_content'][i] or D['ssh_content'][i] == '' or D['ssh_content'][i] == ' ':
  88. # continue
  89. # L.append(D['ssh_content'][i])
  90. # for i in L:
  91. # print(i)
  92. ssh.connect(hostname=ip,
  93. port=22,
  94. username=username,
  95. password=password)
  96. # 假如帳號密碼正確沒有被捕捉到異常,傳送訊息給前端
  97. socketio.emit('user-confirm', 'pass', namespace='/test_conn')
  98. # os.system("scp /home/benson/test10.sh gs1801@" + ip + ":/home/gs1801/")
  99. # 執行命令
  100. # stdin, stdout, stderr = ssh.exec_command("ls -l /home/gs1801;touch test7.py")
  101. # stdin, stdout, stderr = ssh.exec_command("touch test10.sh;echo '" + content + "' >> test10.sh;bash test10.sh")
  102. # print('test1')
  103. # print(stdout.read().decode())
  104. # print('test2')
  105. # print(stderr.read().decode())
  106. # content = D['item_name'] + D['command']
  107. with open('ItemFile.csv', 'w', newline='') as csvFile:
  108. csvWriter = csv.writer(csvFile)
  109. csvWriter.writerow(['Command','Install Content','Status'])
  110. for command in D['command']:
  111. if '使用者' in command :
  112. command = command.replace('使用者', username)
  113. print(command)
  114. sl(6)
  115. stdin, stdout, stderr = ssh.exec_command(command)
  116. #
  117. # # print(stdout.read().decode())
  118. # # print('----------------------------------------')
  119. # # print(stderr.read().decode())
  120. #
  121. error = stderr.read().decode()
  122. if error:
  123. print('error')
  124. print(error)
  125. if item_install_fail == 0:
  126. item_install_fail = 1
  127. with open('ItemFile.csv', 'a', newline='') as csvFile:
  128. csvWriter = csv.writer(csvFile)
  129. csvWriter.writerow([command, error, 'error'])
  130. socketio.emit('stderr', error, namespace='/test_conn')
  131. else:
  132. print('success')
  133. success = stdout.read().decode()
  134. print(success)
  135. with open('ItemFile.csv', 'a', newline='') as csvFile:
  136. csvWriter = csv.writer(csvFile)
  137. csvWriter.writerow([command, success, 'success'])
  138. socketio.emit('stdout', success, namespace='/test_conn')
  139. print('-----------------------------------------------------------------------------')
  140. # def sshJob():
  141. # for command in content:
  142. # stdin, stdout, stderr = ssh.exec_command(command)
  143. # #
  144. # # # print(stdout.read().decode())
  145. # # # print('----------------------------------------')
  146. # # # print(stderr.read().decode())
  147. # #
  148. # print(stdin)
  149. # if stderr.read().decode():
  150. # L.append(0)
  151. # print('error')
  152. # socketio.emit('stderr', stderr.read().decode())
  153. # else:
  154. # L.append(1)
  155. # print('success')
  156. # socketio.emit('stdout', stdout.read().decode())
  157. # sl(5)
  158. # ssh.close()
  159. # def sshJob():
  160. # sl(5)
  161. # i = 0
  162. # total = len(content)
  163. # while True:
  164. # stdin, stdout, stderr = ssh.exec_command(content[i])
  165. # #
  166. # # # print(stdout.read().decode())
  167. # # # print('----------------------------------------')
  168. # # # print(stderr.read().decode())
  169. # #
  170. # if stderr.read().decode():
  171. # L.append(0)
  172. # print('error')
  173. # socketio.emit('stderr', stderr.read().decode())
  174. # else:
  175. # L.append(1)
  176. # print('success')
  177. # socketio.emit('stdout', stdout.read().decode())
  178. # sl(5)
  179. # i += 1
  180. # if i == total:
  181. # break
  182. # ssh.close()
  183. # ssh_thread = threading.Thread(target=sshJob)
  184. # ssh_thread.daemon = True
  185. # ssh_thread.start()
  186. # global thread
  187. # with thread_lock:
  188. # if thread is None:
  189. # thread = socketio.start_background_task(target=sshJob)
  190. # print(L)
  191. #
  192. # item_list = ItemList()
  193. # item_list.ip = ip
  194. # item_list.pymysql = L[0]
  195. # item_list.eventlet = L[1]
  196. # datetime = dt.now()
  197. # item_list.datetime = datetime
  198. # db.session.add(item_list)
  199. # db.session.commit()
  200. # 關閉連線
  201. ssh.close()
  202. if item_install_fail:
  203. res = '有套件未安裝完成!'
  204. else:
  205. res = '建置完成!'
  206. return res
  207. except Exception as e:
  208. print(e)
  209. return str(e)
  210. #mqtt發布
  211. @app.route('/mqtt', methods=['GET','POST'])
  212. def mqtt_views():
  213. import json
  214. dict = request.args.to_dict()
  215. json = json.dumps(dict)
  216. print(json)
  217. mqtt.publish('AISKY/AppleFarm/MK-G/b8:27:eb:f8:24:92', json)
  218. return "Publish done"
  219. #mqtt訂閱
  220. @mqtt.on_connect()
  221. def handle_connect(client, userdata, flags, rc):
  222. mqtt.subscribe('AISKY/AppleFarm/MK-G/b8:27:eb:f8:24:92/Log')
  223. #處理mqtt訂閱的信息
  224. @mqtt.on_message()
  225. def handle_mqtt_message(client, userdata, message):
  226. payload = message.payload.decode()
  227. # p = json.loads(payload)
  228. # print("-------msg-------")
  229. # print('name :', p['name'])
  230. # print('email :', p['email'])
  231. print(payload)
  232. #調用日誌訊息
  233. @mqtt.on_log()
  234. def handle_logging(client, userdata, level, buf):
  235. print(level, buf)
  236. #自動關閉所有未使用、掛著的連接
  237. @app.teardown_appcontext
  238. def shutdown_session(exception=None):
  239. db.session.remove()
  240. if __name__ == '__main__':
  241. socketio.run(app, debug=True, host='0.0.0.0', port=5000)