forked from aaPanel/BaoTa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjobs.py
691 lines (598 loc) · 27.4 KB
/
jobs.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
#coding: utf-8
# +-------------------------------------------------------------------
# | 宝塔Linux面板
# +-------------------------------------------------------------------
# | Copyright (c) 2015-2099 宝塔软件(http://bt.cn) All rights reserved.
# +-------------------------------------------------------------------
# | Author: hwliang <[email protected]>
# +-------------------------------------------------------------------
import time,public,db,os,sys,json,re,shutil
os.chdir('/www/server/panel')
def control_init():
dirPath = '/www/server/phpmyadmin/pma'
if os.path.exists(dirPath):
public.ExecShell("rm -rf {}".format(dirPath))
dirPath = '/www/server/adminer'
if os.path.exists(dirPath):
public.ExecShell("rm -rf {}".format(dirPath))
dirPath = '/www/server/panel/adminer'
if os.path.exists(dirPath):
public.ExecShell("rm -rf {}".format(dirPath))
time.sleep(1)
sql = db.Sql().dbfile('system')
if not sql.table('sqlite_master').where('type=? AND name=?', ('table', 'load_average')).count():
csql = '''CREATE TABLE IF NOT EXISTS `load_average` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`pro` REAL,
`one` REAL,
`five` REAL,
`fifteen` REAL,
`addtime` INTEGER
)'''
sql.execute(csql,())
if not public.M('sqlite_master').where('type=? AND name=? AND sql LIKE ?', ('table', 'sites','%type_id%')).count():
public.M('sites').execute("alter TABLE sites add type_id integer DEFAULT 0",())
if not public.M('sqlite_master').where('type=? AND name=? AND sql LIKE ?', ('table', 'sites','%edate%')).count():
public.M('sites').execute("alter TABLE sites add edate integer DEFAULT '0000-00-00'",())
if not public.M('sqlite_master').where('type=? AND name=? AND sql LIKE ?', ('table', 'sites','%project_type%')).count():
public.M('sites').execute("alter TABLE sites add project_type STRING DEFAULT 'PHP'",())
if not public.M('sqlite_master').where('type=? AND name=? AND sql LIKE ?', ('table', 'sites','%project_config%')).count():
public.M('sites').execute("alter TABLE sites add project_config STRING DEFAULT '{}'",())
if not public.M('sqlite_master').where('type=? AND name=? AND sql LIKE ?', ('table', 'backup','%ps%')).count():
public.M('backup').execute("alter TABLE backup add ps STRING DEFAULT '无'",())
if not public.M('sqlite_master').where('type=? AND name=? AND sql LIKE ?', ('table', 'databases','%db_type%')).count():
public.M('databases').execute("alter TABLE databases add db_type integer DEFAULT '0'",())
if not public.M('sqlite_master').where('type=? AND name=? AND sql LIKE ?', ('table', 'databases','%conn_config%')).count():
public.M('databases').execute("alter TABLE databases add conn_config STRING DEFAULT '{}'",())
if not public.M('sqlite_master').where('type=? AND name=? AND sql LIKE ?', ('table', 'databases','%sid%')).count():
public.M('databases').execute("alter TABLE databases add sid integer DEFAULT 0",())
sql = db.Sql()
if not sql.table('sqlite_master').where('type=? AND name=?', ('table', 'site_types')).count():
csql = '''CREATE TABLE IF NOT EXISTS `site_types` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`name` REAL,
`ps` REAL
)'''
sql.execute(csql,())
if not sql.table('sqlite_master').where('type=? AND name=?', ('table', 'download_token')).count():
csql = '''CREATE TABLE IF NOT EXISTS `download_token` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`token` REAL,
`filename` REAL,
`total` INTEGER DEFAULT 0,
`expire` INTEGER,
`password` REAL,
`ps` REAL,
`addtime` INTEGER
)'''
sql.execute(csql,())
if not sql.table('sqlite_master').where('type=? AND name=?', ('table', 'messages')).count():
csql = '''CREATE TABLE IF NOT EXISTS `messages` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`level` TEXT,
`msg` TEXT,
`state` INTEGER DEFAULT 0,
`expire` INTEGER,
`addtime` INTEGER
)'''
sql.execute(csql,())
if not sql.table('sqlite_master').where('type=? AND name=?', ('table', 'temp_login')).count():
csql = '''CREATE TABLE IF NOT EXISTS `temp_login` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`token` REAL,
`salt` REAL,
`state` INTEGER,
`login_time` INTEGER,
`login_addr` REAL,
`logout_time` INTEGER,
`expire` INTEGER,
`addtime` INTEGER
)'''
sql.execute(csql,())
if not sql.table('sqlite_master').where('type=? AND name=?', ('table', 'database_servers')).count():
csql = '''CREATE TABLE IF NOT EXISTS `database_servers` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`db_host` REAL,
`db_port` REAL,
`db_user` INTEGER,
`db_password` INTEGER,
`ps` REAL,
`addtime` INTEGER
)'''
sql.execute(csql,())
if not public.M('sqlite_master').where('type=? AND name=? AND sql LIKE ?', ('table', 'logs','%username%')).count():
public.M('logs').execute("alter TABLE logs add uid integer DEFAULT '1'",())
public.M('logs').execute("alter TABLE logs add username TEXT DEFAULT 'system'",())
if not public.M('sqlite_master').where('type=? AND name=? AND sql LIKE ?', ('table', 'crontab','%status%')).count():
public.M('crontab').execute("ALTER TABLE 'crontab' ADD 'status' INTEGER DEFAULT 1",())
public.M('crontab').execute("ALTER TABLE 'crontab' ADD 'save' INTEGER DEFAULT 3",())
public.M('crontab').execute("ALTER TABLE 'crontab' ADD 'backupTo' TEXT DEFAULT off",())
public.M('crontab').execute("ALTER TABLE 'crontab' ADD 'sName' TEXT",())
public.M('crontab').execute("ALTER TABLE 'crontab' ADD 'sBody' TEXT",())
public.M('crontab').execute("ALTER TABLE 'crontab' ADD 'sType' TEXT",())
public.M('crontab').execute("ALTER TABLE 'crontab' ADD 'urladdress' TEXT",())
public.M('users').where('email=? or email=?',('[email protected]','[email protected]')).setField('email','[email protected]')
if not public.M('sqlite_master').where('type=? AND name=? AND sql LIKE ?', ('table', 'users','%salt%')).count():
public.M('users').execute("ALTER TABLE 'users' ADD 'salt' TEXT",())
public.chdck_salt()
filename = '/www/server/nginx/off'
if os.path.exists(filename): os.remove(filename)
c = public.to_string([99, 104, 97, 116, 116, 114, 32, 45, 105, 32, 47, 119, 119, 119, 47,
115, 101, 114, 118, 101, 114, 47, 112, 97, 110, 101, 108, 47, 99,
108, 97, 115, 115, 47, 42])
try:
init_file = '/etc/init.d/bt'
src_file = '/www/server/panel/init.sh'
md51 = public.md5(init_file)
md52 = public.md5(src_file)
if md51 != md52:
import shutil
shutil.copyfile(src_file,init_file)
if os.path.getsize(init_file) < 10:
public.ExecShell("chattr -i " + init_file)
public.ExecShell("\cp -arf %s %s" % (src_file,init_file))
public.ExecShell("chmod +x %s" % init_file)
except:pass
public.writeFile('/var/bt_setupPath.conf','/www')
public.ExecShell(c)
p_file = 'class/plugin2.so'
if os.path.exists(p_file): public.ExecShell("rm -f class/*.so")
public.ExecShell("chmod -R 600 /www/server/panel/data;chmod -R 600 /www/server/panel/config;chmod -R 700 /www/server/cron;chmod -R 600 /www/server/cron/*.log;chown -R root:root /www/server/panel/data;chown -R root:root /www/server/panel/config;chown -R root:root /www/server/phpmyadmin;chmod -R 755 /www/server/phpmyadmin")
if os.path.exists("/www/server/mysql"):
public.ExecShell("chown mysql:mysql /etc/my.cnf;chmod 600 /etc/my.cnf")
public.ExecShell("rm -rf /www/server/panel/temp/*")
if not public.is_debug():
public.ExecShell("rm -f /www/server/panel/class/pluginAuth.py")
stop_path = '/www/server/stop'
if not os.path.exists(stop_path):
os.makedirs(stop_path)
public.ExecShell("chown -R root:root {path};chmod -R 755 {path}".format(path=stop_path))
public.ExecShell('chmod 755 /www;chmod 755 /www/server')
if os.path.exists('/www/server/phpmyadmin/pma'):
public.ExecShell("rm -rf /www/server/phpmyadmin/pma")
if os.path.exists("/www/server/adminer"):
public.ExecShell("rm -rf /www/server/adminer")
if os.path.exists("/www/server/panel/adminer"):
public.ExecShell("rm -rf /www/server/panel/adminer")
if os.path.exists('/dev/shm/session.db'):
os.remove('/dev/shm/session.db')
node_service_bin = '/usr/bin/nodejs-service'
node_service_src = '/www/server/panel/script/nodejs-service.py'
if os.path.exists(node_service_src): public.ExecShell("chmod 700 " + node_service_src)
if not os.path.exists(node_service_bin):
if os.path.exists(node_service_src):
public.ExecShell("ln -sf {} {}".format(node_service_src,node_service_bin))
#disable_putenv('putenv')
#clean_session()
#set_crond()
test_ping()
clean_max_log('/www/server/panel/plugin/rsync/lsyncd.log')
clean_max_log('/var/log/rsyncd.log',1024*1024*10)
clean_max_log('/root/.pm2/pm2.log',1024*1024*20)
remove_tty1()
clean_hook_log()
run_new()
clean_max_log('/www/server/cron',1024*1024*5,20)
#check_firewall()
check_dnsapi()
clean_php_log()
files_set_mode()
set_pma_access()
# public.set_open_basedir()
clear_fastcgi_safe()
update_py37()
run_script()
set_php_cli_env()
check_enable_php()
sync_node_list()
def sync_node_list():
import config
config.config().sync_cloud_node_list()
def set_php_cli_env():
'''
@name 设置php-cli环境变量
@author hwliang<2021-09-07>
@return void
'''
php_path = '/www/server/php'
bashrc = '/root/.bashrc'
if not os.path.exists(php_path): return
if not os.path.exists(bashrc): return
# 清理所有别名
public.ExecShell('sed -i "/alias php/d" {}'.format(bashrc))
bashrc_body = public.readFile(bashrc)
if not bashrc_body: return
# 设置默认环境变量版本别名
env_php_bin = '/usr/bin/php'
if os.path.exists(env_php_bin):
if os.path.islink(env_php_bin):
env_bin_version = os.readlink(env_php_bin).split('/')[-3]
php_cli_ini = "{}/{}/etc/php-cli.ini".format(php_path,env_bin_version)
bashrc_body += "alias php='php -c {}'\n".format(php_cli_ini)
# 设置所有已安装的PHP版本环境变量和别名
php_versions_list = public.get_php_versions()
for php_version in php_versions_list:
php_ini = "{}/{}/etc/php.ini".format(php_path,php_version)
php_cli_ini = "{}/{}/etc/php-cli.ini".format(php_path,php_version)
env_php_bin = "/usr/bin/php{}".format(php_version)
php_bin = "{}/{}/bin/php".format(php_path,php_version)
php_ize = '/usr/bin/php{}-phpize'.format(php_version)
php_ize_src = "{}/{}/bin/phpize".format(php_path,php_version)
php_fpm = '/usr/bin/php{}-php-fpm'.format(php_version)
php_fpm_src = "{}/{}/sbin/php-fpm".format(php_path,php_version)
php_pecl = '/usr/bin/php{}-pecl'.format(php_version)
php_pecl_src = "{}/{}/bin/pecl".format(php_path,php_version)
php_pear = '/usr/bin/php{}-pear'.format(php_version)
php_pear_src = "{}/{}/bin/pear".format(php_path,php_version)
if os.path.exists(php_bin):
# 设置每个版本的环境变量
if not os.path.exists(env_php_bin): os.symlink(php_bin,env_php_bin)
if not os.path.exists(php_ize) and os.path.exists(php_ize_src): os.symlink(php_ize_src,php_ize)
if not os.path.exists(php_fpm) and os.path.exists(php_fpm_src): os.symlink(php_fpm_src,php_fpm)
if not os.path.exists(php_pecl) and os.path.exists(php_pecl_src): os.symlink(php_pecl_src,php_pecl)
if not os.path.exists(php_pear) and os.path.exists(php_pear_src): os.symlink(php_pear_src,php_pear)
public.ExecShell("\cp -f {} {}".format(php_ini,php_cli_ini)) # 每次复制新的php.ini到php-cli.ini
public.ExecShell('sed -i "/disable_functions/d" {}'.format(php_cli_ini)) # 清理禁用函数
bashrc_body += "alias php{}='php{} -c {}'\n".format(php_version,php_version,php_cli_ini) # 设置别名
else:
# 清理已卸载的环境变量
if os.path.exists(env_php_bin): os.remove(env_php_bin)
if os.path.exists(php_ize): os.remove(php_ize)
if os.path.exists(php_fpm): os.remove(php_fpm)
if os.path.exists(php_pecl): os.remove(php_pecl)
if os.path.exists(php_pear): os.remove(php_pear)
public.writeFile(bashrc,bashrc_body)
def check_enable_php():
'''
@name 检查nginx下的php配置文件
'''
php_versions = public.get_php_versions()
ngx_php_conf = public.get_setup_path() + '/nginx/conf/enable-php-00.conf'
public.writeFile(ngx_php_conf,'')
for php_v in php_versions:
ngx_php_conf = public.get_setup_path() + '/nginx/conf/enable-php-{}.conf'.format(php_v)
if os.path.exists(ngx_php_conf): continue
enable_conf = '''
location ~ [^/]\.php(/|$)
{{
try_files $uri =404;
fastcgi_pass unix:/tmp/php-cgi-{}.sock;
fastcgi_index index.php;
include fastcgi.conf;
include pathinfo.conf;
}}
'''.format(php_v)
public.writeFile(ngx_php_conf,enable_conf)
def write_run_script_log(_log,rn='\n'):
_log_file = '/www/server/panel/logs/run_script.log'
public.writeFile(_log_file,_log + rn,'a+')
def run_script():
os.system("{} {}/script/run_script.py".format(public.get_python_bin(),public.get_panel_path()))
run_tip = '/dev/shm/bt.pl'
if os.path.exists(run_tip): return
public.writeFile(run_tip,str(time.time()))
uptime = int(public.readFile('/proc/uptime').split()[0])
if uptime > 1800: return
run_config ='/www/server/panel/data/run_config'
script_logs = '/www/server/panel/logs/script_logs'
if not os.path.exists(run_config):
os.makedirs(run_config,384)
if not os.path.exists(script_logs):
os.makedirs(script_logs,384)
for sname in os.listdir(run_config):
script_conf_file = '{}/{}'.format(run_config,sname)
if not os.path.exists(script_conf_file): continue
script_info = json.loads(public.readFile(script_conf_file))
exec_log_file = '{}/{}'.format(script_logs,sname)
if not os.path.exists(script_info['script_file']) \
or script_info['script_file'].find('/www/server/panel/plugin/') != 0 \
or not re.match('^\w+$',script_info['script_file']):
os.remove(script_conf_file)
if os.path.exists(exec_log_file): os.remove(exec_log_file)
continue
if script_info['script_type'] == 'python':
_bin = public.get_python_bin()
elif script_info['script_type'] == 'bash':
_bin = '/usr/bin/bash'
if not os.path.exists(_bin): _bin = 'bash'
exec_script = 'nohup {} {} &> {} &'.format(_bin,script_info['script_file'],exec_log_file)
public.ExecShell(exec_script)
script_info['last_time'] = time.time()
public.writeFile(script_conf_file,json.dumps(script_info))
def clear_fastcgi_safe():
try:
fastcgifile = '/www/server/nginx/conf/fastcgi.conf'
if os.path.exists(fastcgifile):
conf = public.readFile(fastcgifile)
if conf.find('bt_safe_open') != -1:
public.ExecShell('sed -i "/bt_safe_open/d" {}'.format(fastcgifile))
public.ExecShell('/etc/init.d/nginx reload')
except:
pass
#设置文件权限
def files_set_mode():
rr = {True:'-R',False:''}
m_paths = [
["/www/server/total","/*.lua","root",755,False],
["/www/server/total","/*.json","root",755,False],
["/www/server/total/logs","","www",755,True],
["/www/server/total/total","","www",755,True],
["/www/server/speed","/*.lua","root",755,False],
["/www/server/speed/total","","www",755,True],
["/www/server/btwaf","/*.lua","root",755,False],
["/www/backup","","root",600,True],
["/www/wwwlogs","","www",700,True],
["/www/enterprise_backup","","root",600,True],
["/www/server/cron","","root",700,True],
["/www/server/cron","/*.log","root",600,True],
["/www/server/stop","","root",755,True],
["/www/server/redis","","redis",700,True],
["/www/server/redis/redis.conf","","redis",600,False],
["/www/server/panel/class","","root",600,True],
["/www/server/panel/data","","root",600,True],
["/www/server/panel/plugin","","root",600,False],
["/www/server/panel/BTPanel","","root",600,True],
["/www/server/panel/vhost","","root",600,True],
["/www/server/panel/rewrite","","root",600,True],
["/www/server/panel/config","","root",600,True],
["/www/server/panel/backup","","root",600,True],
["/www/server/panel/package","","root",600,True],
["/www/server/panel/script","","root",700,True],
["/www/server/panel/temp","","root",600,True],
["/www/server/panel/tmp","","root",600,True],
["/www/server/panel/ssl","","root",600,True],
["/www/server/panel/install","","root",600,True],
["/www/server/panel/logs","","root",600,True],
["/www/server/panel/BT-Panel","","root",700,False],
["/www/server/panel/BT-Task","","root",700,False],
["/www/server/panel","/*.py","root",600,False],
["/dev/shm/session.db","","root",600,False],
["/dev/shm/session_py3","","root",600,True],
["/dev/shm/session_py2","","root",600,True],
["/www/server/phpmyadmin","","root",755,True],
["/www/server/coll","","root",700,True]
]
recycle_list = public.get_recycle_bin_list()
for recycle_path in recycle_list:
m_paths.append([recycle_path,'','root',600,True])
for m in m_paths:
if not os.path.exists(m[0]): continue
path = m[0] + m[1]
public.ExecShell("chown {R} {U}:{U} {P}".format(P=path,U=m[2],R=rr[m[4]]))
public.ExecShell("chmod {R} {M} {P}".format(P=path,M=m[3],R=rr[m[4]]))
if m[1]:
public.ExecShell("chown {U}:{U} {P}".format(P=m[0],U=m[2],R=rr[m[4]]))
public.ExecShell("chmod {M} {P}".format(P=m[0],M=m[3],R=rr[m[4]]))
#获取PMA目录
def get_pma_path():
pma_path = '/www/server/phpmyadmin'
if not os.path.exists(pma_path): return False
for filename in os.listdir(pma_path):
filepath = pma_path + '/' + filename
if os.path.isdir(filepath):
if filename[0:10] == 'phpmyadmin':
return str(filepath)
return False
#处理phpmyadmin访问权限
def set_pma_access():
try:
pma_path = get_pma_path()
if not pma_path: return False
if not os.path.exists(pma_path): return False
pma_tmp = pma_path + '/tmp'
if not os.path.exists(pma_tmp):
os.makedirs(pma_tmp)
nginx_file = '/www/server/nginx/conf/nginx.conf'
if os.path.exists(nginx_file):
nginx_conf = public.readFile(nginx_file)
if nginx_conf.find('/tmp/') == -1:
r_conf = '''/www/server/phpmyadmin;
location ~ /tmp/ {
return 403;
}'''
nginx_conf = nginx_conf.replace('/www/server/phpmyadmin;',r_conf)
public.writeFile(nginx_file,nginx_conf)
public.serviceReload()
apa_pma_tmp = pma_tmp + '/.htaccess'
if not os.path.exists(apa_pma_tmp):
r_conf = '''order allow,deny
deny from all'''
public.writeFile(apa_pma_tmp,r_conf)
public.set_mode(apa_pma_tmp,755)
public.set_own(apa_pma_tmp,'root')
public.ExecShell("chmod -R 700 {}".format(pma_tmp))
public.ExecShell("chown -R www:www {}".format(pma_tmp))
return True
except:
return False
#尝试升级到独立环境
def update_py37():
pyenv='/www/server/panel/pyenv/bin/python3'
pyenv_exists='/www/server/panel/data/pyenv_exists.pl'
if os.path.exists(pyenv) or os.path.exists(pyenv_exists): return False
download_url = public.get_url()
public.ExecShell("nohup curl {}/install/update_panel.sh|bash &>/tmp/panelUpdate.pl &".format(download_url))
public.writeFile(pyenv_exists,'True')
return True
def test_ping():
_f = '/www/server/panel/data/ping_token.pl'
if os.path.exists(_f): os.remove(_f)
try:
import panelPing
panelPing.Test().create_token()
except:
pass
#检查dnsapi
def check_dnsapi():
dnsapi_file = 'config/dns_api.json'
tmp = public.readFile(dnsapi_file)
if not tmp: return False
dnsapi = json.loads(tmp)
if tmp.find('CloudFlare') == -1:
cloudflare = {
"ps": "使用CloudFlare的API接口自动解析申请SSL",
"title": "CloudFlare",
"data": [{
"value": "",
"key": "SAVED_CF_MAIL",
"name": "E-Mail"
}, {
"value": "",
"key": "SAVED_CF_KEY",
"name": "API Key"
}],
"help": "CloudFlare后台获取Global API Key",
"name": "CloudFlareDns"
}
dnsapi.insert(0,cloudflare)
check_names = {"dns_bt":"Dns_com","dns_dp":"DNSPodDns","dns_ali":"AliyunDns","dns_cx":"CloudxnsDns"}
for i in range(len(dnsapi)):
if dnsapi[i]['name'] in check_names:
dnsapi[i]['name'] = check_names[dnsapi[i]['name']]
public.writeFile(dnsapi_file,json.dumps(dnsapi))
return True
#检测端口放行是否同步(仅firewalld)
def check_firewall():
try:
if not os.path.exists('/usr/sbin/firewalld'): return False
data = public.M('firewall').field('port,ps').select()
import firewalld,firewalls
fs = firewalls.firewalls()
accept_ports = firewalld.firewalld().GetAcceptPortList()
port_list = []
for port_info in accept_ports:
if port_info['port'] in port_list:
continue
port_list.append(port_info['port'])
n = 0
for p in data:
if p['port'].find('.') != -1:
continue
if p['port'] in port_list:
continue
fs.AddAcceptPortAll(p['port'],p['ps'])
n+=1
#重载
if n: fs.FirewallReload()
except:
pass
#尝试启动新架构
def run_new():
try:
new_file = '/www/server/panel/data/new.pl'
port_file = '/www/server/panel/data/port.pl'
if os.path.exists(new_file): return False
if not os.path.exists(port_file): return False
port = public.readFile(port_file)
if not port: return False
cmd_line = public.ExecShell('lsof -P -i:{}|grep LISTEN|grep -v grep'.format(int(port)))[0]
if len(cmd_line) < 20: return False
if cmd_line.find('BT-Panel') != -1: return False
public.writeFile('/www/server/panel/data/restart.pl','True')
public.writeFile(new_file,'True')
return True
except:
return False
#清理webhook日志
def clean_hook_log():
path = '/www/server/panel/plugin/webhook/script'
if not os.path.exists(path): return False
for name in os.listdir(path):
if name[-4:] != ".log": continue
clean_max_log(path+'/' + name,524288)
#清理PHP日志
def clean_php_log():
path = '/www/server/php'
if not os.path.exists(path): return False
for name in os.listdir(path):
filename = path +'/'+name + '/var/log/php-fpm.log'
if os.path.exists(filename): clean_max_log(filename)
filename = path +'/'+name + '/var/log/php-fpm-test.log'
if os.path.exists(filename): clean_max_log(filename)
filename = path +'/'+name + '/var/log/slow.log'
if os.path.exists(filename): clean_max_log(filename)
#清理大日志
def clean_max_log(log_file,max_size = 104857600,old_line = 100):
if not os.path.exists(log_file): return False
if os.path.getsize(log_file) > max_size:
try:
old_body = public.GetNumLines(log_file,old_line)
public.writeFile(log_file,old_body)
except:
print(public.get_error_info())
#删除tty1
def remove_tty1():
file_path = '/etc/systemd/system/[email protected]'
if not os.path.exists(file_path): return False
if not os.path.islink(file_path): return False
if os.readlink(file_path) != '/dev/null': return False
try:
os.remove(file_path)
except:pass
#默认禁用指定PHP函数
def disable_putenv(fun_name):
try:
is_set_disable = '/www/server/panel/data/disable_%s' % fun_name
if os.path.exists(is_set_disable): return True
php_vs = public.get_php_versions()
php_ini = "/www/server/php/{0}/etc/php.ini"
rep = "disable_functions\s*=\s*.*"
for pv in php_vs:
php_ini_path = php_ini.format(pv)
if not os.path.exists(php_ini_path): continue
php_ini_body = public.readFile(php_ini_path)
tmp = re.search(rep,php_ini_body)
if not tmp: continue
disable_functions = tmp.group()
if disable_functions.find(fun_name) != -1: continue
print(disable_functions)
php_ini_body = php_ini_body.replace(disable_functions,disable_functions+',%s' % fun_name)
php_ini_body.find(fun_name)
public.writeFile(php_ini_path,php_ini_body)
public.phpReload(pv)
public.writeFile(is_set_disable,'True')
return True
except: return False
#创建计划任务
def set_crond():
try:
echo = public.md5(public.md5('renew_lets_ssl_bt'))
cron_id = public.M('crontab').where('echo=?',(echo,)).getField('id')
import crontab
args_obj = public.dict_obj()
if not cron_id:
cronPath = public.GetConfigValue('setup_path') + '/cron/' + echo
shell = public.get_python_bin() + ' /www/server/panel/class/panelLets.py renew_lets_ssl'
public.writeFile(cronPath,shell)
args_obj.id = public.M('crontab').add('name,type,where1,where_hour,where_minute,echo,addtime,status,save,backupTo,sType,sName,sBody,urladdress',("续签Let's Encrypt证书",'day','','0','10',echo,time.strftime('%Y-%m-%d %X',time.localtime()),0,'','localhost','toShell','',shell,''))
crontab.crontab().set_cron_status(args_obj)
else:
cron_path = public.get_cron_path()
if os.path.exists(cron_path):
cron_s = public.readFile(cron_path)
if cron_s.find(echo) == -1:
public.M('crontab').where('echo=?',(echo,)).setField('status',0)
args_obj.id = cron_id
crontab.crontab().set_cron_status(args_obj)
except:
print(public.get_error_info())
#清理多余的session文件
def clean_session():
try:
session_path = r'/dev/shm/session_py' + str(sys.version_info[0])
if not os.path.exists(session_path): return False
now_time = time.time()
p_time = 86400
old_state = False
for fname in os.listdir(session_path):
filename = os.path.join(session_path,fname)
if not os.path.exists(filename): continue
modify_time = os.path.getmtime(filename)
if (now_time - modify_time) > p_time:
old_state = True
break
if old_state: public.ExecShell("rm -f " + session_path + '/*')
return True
except:return False
if __name__ == '__main__':
control_init()