forked from Ccapton/brook-web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
brook-web.py
990 lines (836 loc) · 32.4 KB
/
brook-web.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
# coding=utf-8
# 。——————————————————————————————————————————
# 。
# 。 brook-web.py
# 。
# 。 @Time : 18-10-27 下午4:09
# 。 @Author : capton
# 。 @Software: PyCharm
# 。 @Blog : http://ccapton.cn
# 。 @Github : https://github.com/ccapton
# 。 @Email : [email protected]
# 。__________________________________________
from __future__ import print_function # 同时兼容python2、Python3
from __future__ import division # 同时兼容python2、Python3
from flask import Flask, render_template, send_from_directory, request
from flask_apscheduler import APScheduler
from flask_restful import Api
from flask_restful import Resource, reqparse
import json, os, re, sys
from qr import *
from iptables import release_port, refuse_port
# 判断当前Python执行大版本
python_version = sys.version
if python_version.startswith('2.'):
python_version = '2'
elif python_version.startswith('3.'):
python_version = '3'
# 服务进程号
brook_pid = ''
ss_pid = ''
socks5_pid = ''
# 主机ip
host_ip = None
# 模拟同步的标志 当进行配置信息的保存操作(文件写入)时必须对busy进行赋值为True,保存后赋值为False
busy = False
# 服务类型
SERVICE_TYPE_BROOK = 0
SERVICE_TYPE_SS = 1
SERVICE_TYPE_SOCKS5 = 2
salt = 'brook-web'
split_word = '---YnJvb2std2Vi---'
# Resource封装类,简化数据参数的配置
class BaseResource(Resource):
def __init__(self):
Resource.__init__(self)
self.parser = reqparse.RequestParser()
self.add_args()
self.create_args()
# 等待子类重写
def add_args(self):
pass
def add_argument(self, *args, **kwargs):
self.parser.add_argument(*args, **kwargs)
def create_args(self):
self.args = self.parser.parse_args()
def get_arg(self, key):
return self.args[key]
app = Flask(__name__)
api = Api(app)
default_port = 5000
from conf import config
app.config.from_object(config)
from models import db
db.init_app(app)
from models.system_user import SystemUser
# 默认服务信息(随机端口)
def default_config_json():
import random
random_port = random.randint(10000, 30000)
random_port2 = random.randint(10000, 30000)
random_port3 = random.randint(10000, 30000)
while random_port == random_port2:
random_port2 = random.randint(10000, 30000)
while random_port3 == random_port2 or random_port == random_port2:
random_port3 = random.randint(10000, 30000)
init_config_json = {
'brook': [{'port': 6666, 'psw': '6666', 'state': 0, 'info': '若无法开启,删除后再添加'}],
'shadowsocks': [],
'socks5': [],
}
return init_config_json
# 默认用户信息
def default_user(username="admin", password="admin", email=''):
return {"username": username, "password": password, 'email': email}
# 当前服务实时状态对象
current_brook_state = {}
import sys
from flask import jsonify
# # 用户信息保存路径
# default_userjson_path = os.path.join(sys.path[0], "static/json/user.json")
# 服务信息配置保存路径
config_json_path = os.path.join(sys.path[0], "static/json/brook_state.json")
# 基类json对象格式输出函数
def base_result(msg="", data=None, code=0):
return jsonify({"msg": msg, "data": data, "code": code})
# 读取json文件,若没有对应文件则创建一个json文件、写入myjson的内容
def load_json(path, myjson):
if not os.path.exists(path):
os.system("touch %s" % path)
f = open(path, 'r')
json_str = f.read()
f.close()
if json_str == '':
with open(path, 'w') as f2:
f2.write(json.dumps(myjson, ensure_ascii=False))
f = open(path, 'r')
json_str = f.read()
config_json = json.loads(json_str)
f.close()
return config_json
# 读取服务配置信息
def load_config_json():
return load_json(config_json_path, default_config_json())
# 读取用户信息
def load_default_userjson():
user = None
try:
user = SystemUser.query.first()
except Exception as e:
print(e)
if user:
return {'username': user.username, 'password': user.password, 'email': user.email}
else:
return {'username': 'admin', 'password': 'admin', 'email': ''}
# 保存当前用户信息
def save_userjson(userjson):
try:
user = SystemUser.query.first()
if user:
user.username = userjson.get('username')
user.password = userjson.get('password')
user.email = userjson.get('email')
else:
user = SystemUser(username=userjson.get('username'), password=userjson.get('password'), email=userjson.get('email'))
db.session.add(user)
db.session.commit()
except Exception as e:
print(e)
db.session.rollback()
# 保存当前服务配置
def save_config_json(config_json):
with open(config_json_path, 'w') as f:
f.write(json.dumps(config_json, ensure_ascii=False))
# 输出ico文件
class Favicon(BaseResource):
def get(self):
return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico',
mimetype='image/vnd.microsoft.icon')
def check_base64_data(is_get_service_state=False, is_post=True):
client_data = request.json.get('data') if request.json and request.json.get('data') else (request.form.get('data') if is_post else request.args.get('data'))
data = base64decode(client_data, python_version)
client_salt, raw_data = str(data).split(split_word)
return (base64decode(client_salt, python_version) == salt and base64decode(raw_data, python_version) == salt)\
if is_get_service_state else base64decode(client_salt, python_version) == salt
def get_base64_data(key, is_post=True):
client_data = request.json.get(key) if request.json and request.json.get(key) else (
request.form.get(key) if is_post else request.args.get(key))
data = base64decode(client_data, python_version)
client_salt, raw_data = str(data).split(split_word)
if base64decode(client_salt, python_version) == salt:
return base64decode(raw_data, python_version) if raw_data and len(raw_data) > 0 else ''
# 登录api
class Login(BaseResource):
def add_args(self):
self.add_argument('username', type=str, help='Username')
self.add_argument('password', type=str, help='Password')
def login(self, is_post):
username = get_base64_data('username', is_post)
password = get_base64_data('password', is_post)
user = load_default_userjson()
name = user['username']
psw = user['password']
if name == username and psw == password:
return base_result(msg="Login Successful!", code=0)
return base_result(msg="Login failed!", code=-1)
def post(self):
return self.login(True)
def get(self):
return self.login(False)
# 重置用户信息api
class ResetPsw(BaseResource):
def add_args(self):
self.add_argument('old_username', type=str, help='Old Username')
self.add_argument('old_password', type=str, help='Old Password')
self.add_argument('username', type=str, help='New Username')
self.add_argument('password', type=str, help='New Password')
#
# code : 1 新用户名为空
# code : 2 新密码名为空
# code : -1 旧用户信息不正确
#
def reset_psw(self, is_post):
username = get_base64_data('username', is_post)
password = get_base64_data('password', is_post)
old_username = base64decode(base64decode(get_base64_data('old_username', is_post), python_version).split(split_word)[1], python_version)
old_password = base64decode(base64decode(get_base64_data('old_password', is_post), python_version).split(split_word)[1], python_version)
code = 0
user = load_default_userjson()
if old_username == user['username'] and old_password == user['password']:
if len(username) <= 0:
code = 1
return base_result(msg='Reset User Failed!', code=code)
if len(password) <= 0:
code = 2
return base_result(msg='Reset User Failed!', code=code)
save_userjson(default_user(username=username, password=password))
return base_result(msg='Reset User Successful!', code=code)
return base_result(msg='Reset User Failed!')
def post(self):
return self.reset_psw(True)
def get(self):
return self.reset_psw(False)
# 开启服务api
# code : 3 服务开启失败
# code : 4 操作繁忙
# code : -1 用户信息不正确
#
class StartService(BaseResource):
def add_args(self):
pass
def start_service(self, is_post):
username = get_base64_data('username', is_post)
password = get_base64_data('password', is_post)
user = load_default_userjson()
if username != user['username'] or password != user['password']:
return base_result(msg='Loin Failed')
type = int(get_base64_data('type', is_post))
port = int(get_base64_data('port', is_post))
if busy:
return base_result(msg='Server Busy!,Try Again Later.', code=4)
if type == -1:
stop_service(SERVICE_TYPE_BROOK)
result1 = start_service(SERVICE_TYPE_BROOK)
stop_service(SERVICE_TYPE_SS)
result2 = start_service(SERVICE_TYPE_SS)
stop_service(SERVICE_TYPE_SOCKS5)
result3 = start_service(SERVICE_TYPE_SOCKS5)
if result1 * result2 * result3 == 0:
return base_result(msg='Start All Services Successful!', code=0)
else:
if port == -1:
if type == SERVICE_TYPE_BROOK:
stop_service(SERVICE_TYPE_BROOK)
result = start_service(SERVICE_TYPE_BROOK)
elif type == SERVICE_TYPE_SS:
stop_service(SERVICE_TYPE_SS)
result = start_service(SERVICE_TYPE_SS)
elif type == SERVICE_TYPE_SOCKS5:
stop_service(SERVICE_TYPE_SOCKS5)
result = start_service(SERVICE_TYPE_SOCKS5)
else:
result = -1
if result == 0:
return base_result(msg='Start Service Successful!', code=0)
else:
if type == SERVICE_TYPE_BROOK:
stop_service(SERVICE_TYPE_BROOK, port)
result = start_service(SERVICE_TYPE_BROOK, port)
elif type == SERVICE_TYPE_SS:
stop_service(SERVICE_TYPE_SS, port)
result = start_service(SERVICE_TYPE_SS, port)
elif type == SERVICE_TYPE_SOCKS5:
stop_service(SERVICE_TYPE_SOCKS5, port)
result = start_service(SERVICE_TYPE_SOCKS5, port)
else:
result = -1
if result == 0:
return base_result(msg='Start Service Successful!', code=0)
return base_result(msg='Failed to Start Service', code=3)
def get(self):
return self.start_service(False)
def post(self):
return self.start_service(True)
# 停止服务api
class StopService(BaseResource):
def add_args(self):
pass
def stop_service(self, is_post):
username = get_base64_data('username', is_post)
password = get_base64_data('password', is_post)
if username != load_default_userjson()['username'] or password != load_default_userjson()['password']:
return base_result(msg='Loin Failed')
type = int(get_base64_data('type', is_post))
port = int(get_base64_data('port', is_post))
if type == -1:
stop_service(SERVICE_TYPE_BROOK)
stop_service(SERVICE_TYPE_SS)
stop_service(SERVICE_TYPE_SOCKS5)
else:
if port == -1:
if type == SERVICE_TYPE_BROOK:
stop_service(SERVICE_TYPE_BROOK, force=True)
elif type == SERVICE_TYPE_SS:
stop_service(SERVICE_TYPE_SS, force=True)
elif type == SERVICE_TYPE_SOCKS5:
stop_service(SERVICE_TYPE_SOCKS5, force=True)
else:
if type == SERVICE_TYPE_BROOK:
stop_service(SERVICE_TYPE_BROOK, port)
start_service(SERVICE_TYPE_BROOK, port=-1)
elif type == SERVICE_TYPE_SS:
stop_service(SERVICE_TYPE_SS, port)
start_service(SERVICE_TYPE_SS, port=-1)
elif type == SERVICE_TYPE_SOCKS5:
stop_service(SERVICE_TYPE_SOCKS5, port)
start_service(SERVICE_TYPE_SOCKS5, port=-1)
return base_result(msg='Stop Service Successful!', code=0)
def get(self):
return self.stop_service(False)
def post(self):
return self.stop_service(True)
# 获取服务状态api
class ServiceState(BaseResource):
def add_args(self):
pass
def service_state(self):
return current_brook_state
def get(self):
if check_base64_data(is_get_service_state=False):
return base_result(msg='', code=0, data=base64encode(json.dumps(self.service_state()), python_version))
else:
return base_result(msg='解密失败', code=1)
def post(self):
if check_base64_data(is_get_service_state=True):
return base_result(msg='', code=0, data=base64encode(json.dumps(self.service_state()), python_version))
else:
return base_result(msg='解密失败', code=1)
# 增加端口api
class AddPort(BaseResource):
def add_args(self):
pass
def add(self, is_post):
type = int(get_base64_data('type', is_post))
port = int(get_base64_data('port', is_post))
password = get_base64_data('password', is_post)
username = get_base64_data('username', is_post)
info = get_base64_data('info', is_post)
if busy:
return base_result(msg='Server Busy!,Try Again Later.', code=4)
if is_port_used(port, current_brook_state):
return base_result(msg='Port has been used!', code=-2)
if add_port(service_type=type, port=port, psw=password, username=username, info=info):
return base_result(msg='Add Port Successful!', code=0)
return base_result(msg='Add Port Failed!', code=-1)
def get(self):
return self.add(False)
def post(self):
return self.add(True)
# 删除端口api
class DelPort(BaseResource):
def add_args(self):
pass
def del_port(self, is_post):
type = int(get_base64_data('type', is_post))
port = int(get_base64_data('port', is_post))
if busy:
return base_result(msg='Server Busy!,Try Again Later.', code=4)
if del_port(service_type=type, port=port):
return base_result(msg='Delete Port Successful!', code=0)
return base_result(msg='Delete Port Failed!', code=-1)
def get(self):
return self.del_port(False)
def post(self):
return self.del_port(True)
# 生成二维码api
class GenerateQrImg(BaseResource):
def add_args(self):
pass
def generate_qr_image(self, is_post):
type = int(get_base64_data('type', is_post))
port = int(get_base64_data('port', is_post))
password = get_base64_data('password', is_post)
ip = get_base64_data('ip', is_post)
if type == SERVICE_TYPE_SS:
if port <= 0:
return base_result(msg='Port must > 0', code=-2)
if generate_qr_image(format_ss_link(ip, password, port, python_version), port):
return base_result('GenerateQrImg successful!', code=0)
return base_result('GenerateQrImg failed')
def get(self):
return self.generate_qr_image(False)
def post(self):
return self.generate_qr_image(True)
# 检查目标端口是否被占用、根据配置信息判断端口是否已被记录
def is_port_used(port, config_json):
if port > 0:
brook_list = config_json['brook']
ss_list = config_json['shadowsocks']
socks5_list = config_json['socks5']
for brook in brook_list:
if port == brook['port']:
return True
for ss in ss_list:
if port == ss['port']:
return True
for socks5 in socks5_list:
if port == socks5['port']:
return True
pi = os.popen('lsof -i:' + str(port))
res = pi.read()
pi.close()
if res != '':
return True
return False
# 增加端口
def add_port(username, service_type=SERVICE_TYPE_BROOK, port=-1, psw='', info=''):
print(service_type, port, psw, username)
if port == -1:
return False
if username != '' and username != None:
if psw == '' or psw == None:
return False
config_json = load_config_json()
new_config_json = config_json
if service_type == SERVICE_TYPE_BROOK:
config_json['brook'].append({'port': port, 'psw': str(psw), 'info': info})
elif service_type == SERVICE_TYPE_SS:
config_json['shadowsocks'].append({'port': port, 'psw': str(psw), 'info': info})
elif service_type == SERVICE_TYPE_SOCKS5:
config_json['socks5'].append({'port': port, 'psw': str(psw), 'username': str(username), 'info': info})
global busy
busy = True
save_config_json(new_config_json)
busy = False
if is_linux():
refuse_port([port])
release_port([port])
stop_service(service_type=service_type)
start_service(service_type=service_type, port=port)
return True
# 删除端口
def del_port(service_type=SERVICE_TYPE_BROOK, port=-1):
if port == -1:
return False
config_json = load_config_json()
service_list = [config_json['brook'], config_json['shadowsocks'], config_json['socks5']]
def get_index(service):
index = -1
for i in range(len(service)):
if service[i]['port'] == port:
index = i
break
return index
try:
if service_type == SERVICE_TYPE_BROOK:
index = get_index(service_list[0])
if index == -1: return False
config_json['brook'].remove(config_json['brook'][index])
global busy
busy = True
save_config_json(config_json)
busy = False
elif service_type == SERVICE_TYPE_SS:
index = get_index(service_list[1])
if index == -1: return False
config_json['shadowsocks'].remove(config_json['shadowsocks'][index])
busy = True
save_config_json(config_json)
busy = False
elif service_type == SERVICE_TYPE_SOCKS5:
index = get_index(service_list[2])
if index == -1: return False
config_json['socks5'].remove(config_json['socks5'][index])
busy = True
save_config_json(config_json)
busy = False
stop_service(service_type=service_type, port=port)
start_service(service_type=service_type)
return True
except IndexError:
pass
return False
# 获取本机实际对外通信的地址
def get_host_ip():
import socket
s = None
ip = '0.0.0.0'
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
ip = s.getsockname()[0]
except:
pass
finally:
if s: s.close()
return ip
# 记录所有服务的状态
def record_all_state():
record_state(SERVICE_TYPE_BROOK)
record_state(SERVICE_TYPE_SS)
record_state(SERVICE_TYPE_SOCKS5)
# 记录服务状态
def record_state(service_type=-1):
if service_type == SERVICE_TYPE_BROOK:
service_name = 'brook'
service_cmomand_name = 'servers'
elif service_type == SERVICE_TYPE_SS:
service_name = 'shadowsocks'
service_cmomand_name = 'ssservers'
elif service_type == SERVICE_TYPE_SOCKS5:
service_name = 'socks5'
service_cmomand_name = 'socks5'
else:
return
pi = os.popen('ps aux|grep brook\ %s' % service_cmomand_name)
result = pi.read()
pi.close()
# 正则匹配查找出当前服务的所有端口
all_results = re.findall("-l :\d+", result)
final_results = []
for node in all_results:
final_results.append(int(node[4:]))
# print(final_results)
config_json = load_config_json()
global current_brook_state
current_brook_state[service_name] = []
# 判断当前服务所有端口的状态,并保存到全局变量current_brook_state中去
for server in config_json[service_name]:
current_server = {}
if service_type == SERVICE_TYPE_BROOK:
current_server['link'] = format_brook_link(host_ip, server['psw'], server['port'])
current_server['qr_img_path'] = os.path.join('static/img/qr', str(server['port']) + '.png')
elif service_type == SERVICE_TYPE_SS:
current_server['link'] = format_ss_link(host_ip, server['psw'], server['port'], pv=python_version)
current_server['qr_img_path'] = os.path.join('static/img/qr', str(server['port']) + '.png')
if is_linux():
current_server['linked_num'] = port_linked_num(server['port'])
else:
current_server['linked_num'] = 0
current_server['port'] = server['port']
current_server['psw'] = server['psw']
if server['port'] in final_results:
current_server['state'] = 1
else:
current_server['state'] = 0
if service_type == SERVICE_TYPE_SOCKS5:
current_server['username'] = server['username']
elif service_type == SERVICE_TYPE_SS:
current_server['encode_method'] = 'aes-256-cfb'
current_server['ip'] = host_ip
if server.get('info'):
current_server['info'] = server['info']
else:
current_server['info'] = ''
current_brook_state[service_name].append(current_server)
# 开启服务
def start_service(service_type, port=-1, force=False):
service_name = 'brook'
if service_type == SERVICE_TYPE_BROOK:
service_name = 'brook'
elif service_type == SERVICE_TYPE_SS:
service_name = 'shadowsocks'
elif service_type == SERVICE_TYPE_SOCKS5:
service_name = 'socks5'
config_json = load_config_json()
server_list = config_json[service_name]
server_list_str = ''
for server in server_list:
if service_type != SERVICE_TYPE_SOCKS5:
server_str = '-l ":%d %s" ' % (server['port'], server['psw'])
else:
server_str = '-l :%d ' % (server['port'])
if port != -1:
if port == server['port']:
server['state'] = 1
else:
if force:
server['state'] = 1
if server['state'] != 0:
server_list_str += server_str
if has_service_start(service_type):
print(' %s服务已经开启,不要重复操作' % service_name)
global busy
busy = True
save_config_json(config_json)
busy = False
return 0
else:
code1 = -2
if len(server_list_str) != 0:
# 采用brook程序一次开启多个服务端口的命令
if service_type == SERVICE_TYPE_BROOK:
code1 = os.system('nohup ./brook servers ' + server_list_str + '>/dev/null 2>log &')
elif service_type == SERVICE_TYPE_SS:
code1 = os.system('nohup ./brook ssservers ' + server_list_str + '>/dev/null 2>log &')
elif service_type == SERVICE_TYPE_SOCKS5:
if server_list[0]['username'] != '':
user_mode = ' --username ' + server_list[0]['username'] + ' --password ' + server_list[0]['psw']
else:
# 当socks5服务没有设置用户名时,认为这个socks5服务是无账号、无密码服务
user_mode = ''
code1 = os.system(
'nohup ./brook socks5 ' + server_list_str + '-i ' + host_ip + user_mode + ' >/dev/null 2>log &')
if code1 == 0:
# 这时 brook_pid,ss_pid,socks5_pid未被记录
has_service_start(service_type) # 为了记录brook_pid,ss_pid,socks5_pid
print('%s Service Start Successful' % service_name)
busy = True
save_config_json(config_json)
busy = False
return 0
else:
has_service_start(service_type)
if code1 == -2:
pass
else:
print(' %s Service Start Failed' % service_name)
# 停止服务
def stop_service(service_type=SERVICE_TYPE_BROOK, port=-1, force=False):
has_service_start(service_type)
service_name = 'brook'
if service_type == SERVICE_TYPE_BROOK:
service_name = 'brook'
elif service_type == SERVICE_TYPE_SS:
service_name = 'shadowsocks'
elif service_type == SERVICE_TYPE_SOCKS5:
service_name = 'socks5'
config_json = load_config_json()
server_list = config_json[service_name]
for server in server_list:
if port != -1:
if port == server['port']:
server['state'] = 0
else:
if force:
server['state'] = 0
global busy
busy = True
save_config_json(config_json)
busy = False
try:
global brook_pid, ss_pid
if service_type == SERVICE_TYPE_BROOK:
if brook_pid != '':
os.system('kill ' + brook_pid)
elif service_type == SERVICE_TYPE_SS:
if ss_pid != '':
os.system('kill ' + ss_pid)
elif service_type == SERVICE_TYPE_SOCKS5:
if socks5_pid != '':
os.system('kill ' + socks5_pid)
finally:
pass
# 获取端口已连接的ip数量
def port_linked_num(port):
num = 0
c = "ss state connected sport = :%d -tn|sed '1d'|awk '{print $NF}'|awk -F ':' '{print $(NF-1)}'|sort -u|wc -l" % port
try:
pi = os.popen(c)
num = int(pi.read())
pi.close()
except:
pass
return num
# 检查服务是否开启(记录对应的服务进程号)
def has_service_start(service_type=SERVICE_TYPE_BROOK):
pi = os.popen('ps aux | grep brook')
result = pi.read()
pi.close()
try:
global brook_pid, ss_pid, socks5_pid
if service_type == SERVICE_TYPE_BROOK:
brook_pid = match_pid(result, service_type)
elif service_type == SERVICE_TYPE_SS:
ss_pid = match_pid(result, service_type)
elif service_type == SERVICE_TYPE_SOCKS5:
socks5_pid = match_pid(result, service_type)
except Exception:
if service_type == SERVICE_TYPE_BROOK:
brook_pid = ''
elif service_type == SERVICE_TYPE_SS:
ss_pid = ''
elif service_type == SERVICE_TYPE_SOCKS5:
socks5_pid = ''
started = False
if service_type == SERVICE_TYPE_BROOK:
if str(result).find(' servers -l') != -1:
started = True
elif service_type == SERVICE_TYPE_SS:
if str(result).find(' ssservers -l') != -1:
started = True
elif service_type == SERVICE_TYPE_SOCKS5:
if str(result).find(' socks5 -l') != -1:
started = True
return started
# 正则匹配查找对应服务的进程号
def match_pid(text, service_type=SERVICE_TYPE_BROOK):
import re
if service_type == SERVICE_TYPE_BROOK:
re_result = re.search('.+\s{1}servers -l.+', str(text))
elif service_type == SERVICE_TYPE_SS:
re_result = re.search('.+\s{1}ssservers -l.+', str(text))
else:
re_result = re.search('.+\s{1}socks5 -l.+', str(text))
target_line = re_result.group()
re_result2 = re.search("\S+\s+[\d]+[\s]{0,1}[\d]+\s+\d\.\d", target_line)
target_line2 = re_result2.group()
final_result = re.search("[\d]+[\s]{0,1}[\d]+", target_line2)
return final_result.group()
# 清理后台模式的日志
def clear_log():
if os.path.exists('nohup.out'):
with open('nohup.out', 'w') as f:
f.write('')
print('Clear Log')
class Config(object):
JOBS = [
{
'id': 'job1',
'func': record_all_state,
# 'args': (1, 2),
'trigger': 'interval',
'seconds': 2
},
{
'id': 'job2',
'func': clear_log,
# 'args': (1, 2),
'trigger': 'interval',
'seconds': 300
}
]
SCHEDULER_API_ENABLED = True
#
# flask-restful的api对象添加路由信息
#
api.add_resource(Favicon, '/favicon.ico')
api.add_resource(Login, '/api/login')
api.add_resource(ResetPsw, '/api/resetpsw')
api.add_resource(StartService, '/api/startservice')
api.add_resource(StopService, '/api/stopservice')
api.add_resource(ServiceState, '/api/servicestate')
api.add_resource(AddPort, '/api/addport')
api.add_resource(DelPort, '/api/delport')
api.add_resource(GenerateQrImg, '/api/generateqrimg')
@app.route("/")
def brook_web():
title = 'Brook后台管理'
return render_template('index.html', title=title)
@app.route("/login")
def user_login():
title = 'Brook管理登录'
return render_template('login.html', title=title)
@app.route("/user")
def user_edit():
title = 'Brook后台管理'
return render_template('user.html', title=title)
@app.route("/test")
def test_html():
return render_template('test.html')
# @app.route('/create_models', methods=['PUT'])
# def create_models():
# try:
# db.create_all()
# from models.system_user import SystemUser
# if SystemUser.query.count() == 0:
# user = SystemUser(username='admin', password='admin')
# db.session.add(user)
# db.session.commit()
# return base_result(msg='创建Models成功!')
# except Exception as e:
# print(e)
# db.session.rollback()
# return base_result(msg='创建Models失败' + str(e), code=-1)
#
#
# @app.route('/get_user')
# def get_user_default():
# try:
# db.create_all()
# from models.system_user import SystemUser
# users = SystemUser.query.all()
# user_list = []
# for user in users:
# user_list.append({'username': user.username, 'password': user.password})
# return base_result(msg='获取用户成功', data={'users': user_list})
# except Exception as e:
# print(e)
# return base_result(msg='获取用户失败 ' + str(e), code=-1)
# 修改默认web端口是否错误的标志
port_error = False
def config_param(port=5000, email='', domain=''):
global default_port, port_error
if isinstance(port, int):
if port > 0:
default_port = port
else:
port_error = True
print('端口必须大于0')
else:
port_error = True
print('端口号必须为正整数')
if email == '':
return
if domain == '':
return
# 定时器服务,用于心跳记录当前服务信息
app.config.from_object(Config())
scheduler = APScheduler()
# it is also possible to enable the API directly
# scheduler.api_enabled = True
scheduler.init_app(app)
scheduler.start()
def is_linux():
import platform
sys_name = platform.system()
# machine_name = platform.machine().lower()
if 'Darwin' == sys_name:
return False
elif 'Linux' == sys_name:
return True
return False
if __name__ == '__main__':
if python_version == '2':
reload(sys) # python3解释器下可能会提示错误,没关系,因为只有python2运行本程序才会走到这步
sys.setdefaultencoding("utf-8") # 同上
try:
larger_ram = 'ulimit -n 51200'
os.popen(larger_ram).close()
except:
pass
host_ip = get_host_ip()
import fire
fire.Fire(config_param)
if not port_error:
# 记录当前运行中的服务,并停止该服务
if has_service_start(SERVICE_TYPE_BROOK): stop_service(SERVICE_TYPE_BROOK, port=-1)
if has_service_start(SERVICE_TYPE_SS): stop_service(SERVICE_TYPE_SS, port=-1)
if has_service_start(SERVICE_TYPE_SOCKS5): stop_service(SERVICE_TYPE_SOCKS5, port=-1)
if not os.path.exists('brook'):
print('当前目录下不存在brook程序!请执行 python install-brook.py 后重试')
else:
start_service(SERVICE_TYPE_BROOK)
start_service(SERVICE_TYPE_SS)
start_service(SERVICE_TYPE_SOCKS5)
app.run(host=host_ip, port=default_port)