#啟動和管理項目 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 app, db, mqtt, socketio = create_app() thread = None thread_lock = Lock() @socketio.on('connect_event', namespace='/test_conn') def connected_msg(msg): print("connect success") print(msg) socketio.emit('stdout', 'success', namespace='/test_conn') print(socketio) D = {"item_name":0, "command":0} #建置伺服器的訪問路徑 @app.route('/add_server', methods=['POST', 'GET']) def add_server_views(): username = session['uname'] L = [] if request.method == 'GET': repo = git.Repo.init(path='.') new_repo = git.Repo.clone_from(url='http://60.250.156.230:3000/benson/TestSSH.git', to_path='../new') with open('/home/benson/Project/new/All_installv3.2.sh') as f: # content = f.read().split('-Dividing line-') # D['item_name'] = content[0].split('\n')[1:] # D['command'] = content[1].split('\n') D['command'] = f.read().split('\n') with open('/home/benson/Project/new/Item.txt') as f: D['item_name'] = f.read().split('\n') for item in D['item_name']: L.append('.'.join(item.split('.')[1:])) #刪除非空資料夾 try: shutil.rmtree('/home/benson/Project/new') except OSError as e: print(f"Error:{e.strerror}") # for i in range(0, len(D['item_name'])): # item = D['item_name'][i].split('=')[-1].replace('"','') # L.append(item) # L = L[:-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 print(D['item_name']) print(D['command']) # content = D['item_name'] + D['command'] # for i in content: # print(i) return render_template('add_server.html', params=locals()) else: item_install_fail = 0 d = request.form.to_dict() ip = d['ip'] username = d['username'] password = d['password'] print(ip) print(username) print(password) try: # 建立一個sshclient物件 ssh = paramiko.SSHClient() # 允許將信任的主機自動加入到host_allow 列表,此方法必須放在connect方法的前面 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 指定本地的RSA私鑰檔案,如果建立金鑰對時設定的有密碼,password為設定的密碼,如無不用指定password引數 # pkey = paramiko.RSAKey.from_private_key_file('/home/super/.ssh/id_rsa', password='12345') # pkey = paramiko.RSAKey.from_private_key_file('/home/ptop/topicjie/scripts/keys/id_rsa') # 建立連線 # ssh.connect(hostname=ip, # port=22, # username='gs1801', # pkey=pkey) # with open('/home/benson/test11.sh') as f: # content = f.read().split('\n')[0:-1] # print(content) # L = [] # for i in range(0, len(D['ssh_content'])): # if "#" in D['ssh_content'][i] or D['ssh_content'][i] == '' or D['ssh_content'][i] == ' ': # continue # L.append(D['ssh_content'][i]) # for i in L: # print(i) ssh.connect(hostname=ip, port=22, username=username, password=password) # 假如帳號密碼正確沒有被捕捉到異常,傳送訊息給前端 socketio.emit('user-confirm', 'pass', namespace='/test_conn') # os.system("scp /home/benson/test10.sh gs1801@" + ip + ":/home/gs1801/") # 執行命令 # stdin, stdout, stderr = ssh.exec_command("ls -l /home/gs1801;touch test7.py") # stdin, stdout, stderr = ssh.exec_command("touch test10.sh;echo '" + content + "' >> test10.sh;bash test10.sh") # print('test1') # print(stdout.read().decode()) # print('test2') # print(stderr.read().decode()) # content = D['item_name'] + D['command'] with open('ItemFile.csv', 'w', newline='') as csvFile: csvWriter = csv.writer(csvFile) csvWriter.writerow(['Command','Install Content','Status']) for command in D['command']: if '使用者' in command : command = command.replace('使用者', username) print(command) sl(6) stdin, stdout, stderr = ssh.exec_command(command) # # # print(stdout.read().decode()) # # print('----------------------------------------') # # print(stderr.read().decode()) # error = stderr.read().decode() if error: print('error') print(error) if item_install_fail == 0: item_install_fail = 1 with open('ItemFile.csv', 'a', newline='') as csvFile: csvWriter = csv.writer(csvFile) csvWriter.writerow([command, error, 'error']) socketio.emit('stderr', error, namespace='/test_conn') else: print('success') success = stdout.read().decode() print(success) with open('ItemFile.csv', 'a', newline='') as csvFile: csvWriter = csv.writer(csvFile) csvWriter.writerow([command, success, 'success']) socketio.emit('stdout', success, namespace='/test_conn') print('-----------------------------------------------------------------------------') # def sshJob(): # for command in content: # stdin, stdout, stderr = ssh.exec_command(command) # # # # # print(stdout.read().decode()) # # # print('----------------------------------------') # # # print(stderr.read().decode()) # # # print(stdin) # if stderr.read().decode(): # L.append(0) # print('error') # socketio.emit('stderr', stderr.read().decode()) # else: # L.append(1) # print('success') # socketio.emit('stdout', stdout.read().decode()) # sl(5) # ssh.close() # def sshJob(): # sl(5) # i = 0 # total = len(content) # while True: # stdin, stdout, stderr = ssh.exec_command(content[i]) # # # # # print(stdout.read().decode()) # # # print('----------------------------------------') # # # print(stderr.read().decode()) # # # if stderr.read().decode(): # L.append(0) # print('error') # socketio.emit('stderr', stderr.read().decode()) # else: # L.append(1) # print('success') # socketio.emit('stdout', stdout.read().decode()) # sl(5) # i += 1 # if i == total: # break # ssh.close() # ssh_thread = threading.Thread(target=sshJob) # ssh_thread.daemon = True # ssh_thread.start() # global thread # with thread_lock: # if thread is None: # thread = socketio.start_background_task(target=sshJob) # print(L) # # item_list = ItemList() # item_list.ip = ip # item_list.pymysql = L[0] # item_list.eventlet = L[1] # datetime = dt.now() # item_list.datetime = datetime # db.session.add(item_list) # db.session.commit() # 關閉連線 ssh.close() if item_install_fail: res = '有套件未安裝完成!' else: res = '建置完成!' return res except Exception as e: print(e) return str(e) #mqtt發布 @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訂閱 @mqtt.on_connect() def handle_connect(client, userdata, flags, rc): mqtt.subscribe('AISKY/AppleFarm/MK-G/b8:27:eb:f8:24:92/Log') #處理mqtt訂閱的信息 @mqtt.on_message() def handle_mqtt_message(client, userdata, message): payload = message.payload.decode() # p = json.loads(payload) # print("-------msg-------") # print('name :', p['name']) # print('email :', p['email']) 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__': socketio.run(app, debug=True, host='0.0.0.0', port=5000)