mirror of
https://github.com/midoks/mdserver-web.git
synced 2026-10-10 06:09:25 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
714acd20e5 | ||
|
|
bf58cd8acc | ||
|
|
059053d27c | ||
|
|
185e73c26a | ||
|
|
569511d321 | ||
|
|
f88bf5059f | ||
|
|
05b63b8d2b | ||
|
|
3a197b273d | ||
|
|
f4fdbab41c | ||
|
|
f6b2940657 | ||
|
|
78b9ac5df0 | ||
|
|
3ea4272307 | ||
|
|
efc7cee9ad | ||
|
|
5c4805453d | ||
|
|
f6da241c85 | ||
|
|
d5b6eb2325 | ||
|
|
6ed2cddf71 | ||
|
|
9c31d76442 | ||
|
|
7aecbaf7df | ||
|
|
ee81a86d24 | ||
|
|
0a60d66732 | ||
|
|
c3e3cff472 | ||
|
|
194d46eb6a | ||
|
|
d66bc94edc | ||
|
|
fb4ffcd343 | ||
|
|
10c235e317 | ||
|
|
9c156928d8 | ||
|
|
771905d7f6 | ||
|
|
cd21b3f3e7 | ||
|
|
982026db24 | ||
|
|
f9b91d9989 | ||
|
|
f7b1159bd7 | ||
|
|
6aa49ddbcf | ||
|
|
866eddac1d | ||
|
|
af0cce4216 | ||
|
|
3951322d86 | ||
|
|
dfdd16b444 | ||
|
|
aa8fec2b7e | ||
|
|
2a8958ab84 | ||
|
|
f5125670ee | ||
|
|
2a8d4fb7a9 | ||
|
|
59f7fe2290 | ||
|
|
928db6e7e7 | ||
|
|
f3927bd6cf | ||
|
|
bb92727b56 | ||
|
|
21b80b1fce | ||
|
|
637da92834 | ||
|
|
f5859626a9 | ||
|
|
003449eb0a | ||
|
|
d27f926191 | ||
|
|
7483247d4d | ||
|
|
1ad841d3af | ||
|
|
27376d879c | ||
|
|
8b824447c1 | ||
|
|
a1d26dcd45 | ||
|
|
5e68c7bf0a | ||
|
|
481ae16713 | ||
|
|
2d2bd39f9e | ||
|
|
7246a878a5 | ||
|
|
542ee3cdb0 | ||
|
|
69503b223b | ||
|
|
78d8fa7ebf | ||
|
|
21e9d8f2d8 | ||
|
|
3c6adfbd44 | ||
|
|
c0e70abe6d | ||
|
|
f174e71228 | ||
|
|
7a9a811ea6 | ||
|
|
c7e3d9d9a3 | ||
|
|
161f7a1bc0 | ||
|
|
175cce0131 | ||
|
|
3735897ed2 | ||
|
|
30bfa5a630 | ||
|
|
594fdb4712 | ||
|
|
31a441ea02 | ||
|
|
06f7087fad | ||
|
|
e7b8f5afdc | ||
|
|
6b57addfa7 | ||
|
|
aea435fbaf | ||
|
|
9cd6656946 | ||
|
|
4f7df4b3c3 | ||
|
|
70d12b7b8d | ||
|
|
fe576c820a | ||
|
|
b48a53e0d7 | ||
|
|
4701839c33 | ||
|
|
916bc67c4d | ||
|
|
d7bba830cc | ||
|
|
7a28f8f57a | ||
|
|
41ee25aa7b | ||
|
|
c8aa91cfa3 | ||
|
|
98f27498b0 | ||
|
|
5444fe6455 | ||
|
|
9627c6e47b | ||
|
|
13597d6282 | ||
|
|
d09494e3aa | ||
|
|
d35439d286 | ||
|
|
ced48bab47 | ||
|
|
fe2df6cc8d | ||
|
|
8bdfe15101 | ||
|
|
42e9983b88 | ||
|
|
9b7c0b6f99 | ||
|
|
e421292c9e | ||
|
|
7b4d31779a | ||
|
|
f3b09056f3 | ||
|
|
a92ccea6c5 | ||
|
|
9da77a0a9b | ||
|
|
c233ecaaa7 | ||
|
|
5828b8b8cb | ||
|
|
a4a1a2c83c | ||
|
|
0e20bc182c | ||
|
|
99c0b0a81a | ||
|
|
3fa199fec4 | ||
|
|
194c36c6d8 | ||
|
|
2fb542f6b4 | ||
|
|
60af43ed31 | ||
|
|
9f02cf9744 | ||
|
|
846bd270df | ||
|
|
d910d4f462 | ||
|
|
13f5b1bf02 | ||
|
|
1fc3fd6247 | ||
|
|
36e3feb886 | ||
|
|
0ca34afacd | ||
|
|
ffb3288f3d | ||
|
|
e2f68a73ed | ||
|
|
92fa8da2f6 | ||
|
|
7c96ddd63e | ||
|
|
c4e7872179 | ||
|
|
d399cb2bb4 | ||
|
|
985cbc7eca | ||
|
|
27ed21a17d | ||
|
|
972165ba1a | ||
|
|
e76eb4d0e8 | ||
|
|
fd05c40dbb | ||
|
|
a1a7fa5c82 | ||
|
|
531de1407f | ||
|
|
ca455f13e8 | ||
|
|
ab5342b01f | ||
|
|
a5a57c5718 | ||
|
|
27999b21e6 | ||
|
|
d2c6caeef2 | ||
|
|
de30d8a41f | ||
|
|
d3abc8e7b2 | ||
|
|
b7aad65eb5 | ||
|
|
240b1dec27 | ||
|
|
4756e0f68b | ||
|
|
59f62b948a | ||
|
|
0ab0741031 | ||
|
|
2fd2f6e844 | ||
|
|
e534c6177a | ||
|
|
897c6322fc | ||
|
|
201e93f946 | ||
|
|
a78fd957ec | ||
|
|
3ce037b0a1 | ||
|
|
f3176340f8 | ||
|
|
7bfe096e8d | ||
|
|
066428fca8 | ||
|
|
a1313846c8 | ||
|
|
0433123abd | ||
|
|
72e99844dd | ||
|
|
3a7882e7fa | ||
|
|
bec2a9a12c | ||
|
|
8f02363782 | ||
|
|
939c847f3e | ||
|
|
a623039db7 | ||
|
|
b7f49a1839 | ||
|
|
f1f60870f6 | ||
|
|
3b04739fd4 | ||
|
|
fdf1e0b0be | ||
|
|
d3385f526f | ||
|
|
20f9095b93 | ||
|
|
757cf483a2 | ||
|
|
1712cfd024 | ||
|
|
2b524cbe75 | ||
|
|
607d384000 | ||
|
|
14cdc7b82e | ||
|
|
c3219bcba2 | ||
|
|
a12c4dd78e | ||
|
|
39c6f19592 | ||
|
|
f18c05a097 | ||
|
|
80f296ea19 | ||
|
|
b3e9283a58 | ||
|
|
2e140a3ae1 | ||
|
|
4d733c8886 | ||
|
|
62a7320baf | ||
|
|
3dc7c2f5c1 | ||
|
|
fe62bbee06 | ||
|
|
f7c0cd82a0 | ||
|
|
13a2014558 | ||
|
|
5981f94376 | ||
|
|
005e0f1513 | ||
|
|
63a0f0fbdc | ||
|
|
edc0be11a1 | ||
|
|
908b6e67c6 | ||
|
|
dfe46332db | ||
|
|
fcdf2e18b2 | ||
|
|
3c8f9bcf96 | ||
|
|
ebadd6d80d | ||
|
|
6062699074 | ||
|
|
df9d57ba70 | ||
|
|
ffca953539 | ||
|
|
bd4946124f | ||
|
|
8e18c63cee | ||
|
|
d201ca2574 | ||
|
|
b644f91090 | ||
|
|
931f51cf59 | ||
|
|
0909a11fd9 | ||
|
|
2ba2833699 | ||
|
|
20389263fb | ||
|
|
86141ccf3a | ||
|
|
b2fdf84ca0 | ||
|
|
8fbc456e1a | ||
|
|
4e43382496 | ||
|
|
0326d4f112 | ||
|
|
a87c13c5e0 | ||
|
|
5f3720c855 | ||
|
|
f548e020c4 | ||
|
|
7f21781c0b | ||
|
|
680b0f09f2 | ||
|
|
482943a63c | ||
|
|
2871aee18e | ||
|
|
ff46d9b36e | ||
|
|
fd5fcba543 | ||
|
|
fe04e02e88 | ||
|
|
93554332a7 | ||
|
|
b541c7e1b7 | ||
|
|
1dec1a286a | ||
|
|
b17510104d | ||
|
|
c2c8ea0ce6 | ||
|
|
acbdb013ae | ||
|
|
b025f21765 | ||
|
|
1afc8a69e5 | ||
|
|
743fc9e8d3 | ||
|
|
8d692d2b3b | ||
|
|
a0b362e691 | ||
|
|
98e1c2ae8f | ||
|
|
c0e5915285 | ||
|
|
667a0fd0fd | ||
|
|
8ed5f283b0 | ||
|
|
643c370d30 | ||
|
|
4601303065 | ||
|
|
14940d6734 | ||
|
|
fdc2b0f5c4 | ||
|
|
cf0b233f63 | ||
|
|
b3a7ef2206 | ||
|
|
9a3ca3e833 | ||
|
|
9afff8df3f | ||
|
|
ccd0b06223 | ||
|
|
7b495fe9bf | ||
|
|
2c3fb75e8f | ||
|
|
53b606602f | ||
|
|
ecef0cf994 | ||
|
|
3691d41b23 | ||
|
|
1f66457a3e | ||
|
|
8e05beccfd | ||
|
|
35424eae1f | ||
|
|
ed6df6d527 | ||
|
|
4366c4afde | ||
|
|
4bb059f62f | ||
|
|
aa8f618d9c | ||
|
|
dfd753e4c1 | ||
|
|
e38daf3c89 | ||
|
|
535838fc5e | ||
|
|
797853bd61 | ||
|
|
0de3aff045 | ||
|
|
0b7b48ab23 | ||
|
|
5ff0a0bfbc | ||
|
|
9131f44d67 | ||
|
|
6b86bb9d2b | ||
|
|
dc06d6beda | ||
|
|
2c8ea2498e | ||
|
|
6b01173b61 | ||
|
|
883c554850 | ||
|
|
d267da351c | ||
|
|
13a39f4d6a | ||
|
|
cff1d5ee89 | ||
|
|
bf5274c313 | ||
|
|
5623e3efac | ||
|
|
b93bb6c64c | ||
|
|
c9962f169e | ||
|
|
080f343ee2 | ||
|
|
5aeaf13f16 | ||
|
|
528094cfa7 | ||
|
|
ed3e3336b2 | ||
|
|
a75a49c2ae | ||
|
|
1204e72f41 | ||
|
|
13ca5544a5 | ||
|
|
e53fe26d52 | ||
|
|
13772399f6 | ||
|
|
98f11e2662 | ||
|
|
f0b0302f75 | ||
|
|
5b9b466cb9 | ||
|
|
5588a11ea5 | ||
|
|
da05a4ef19 | ||
|
|
34cf899529 | ||
|
|
0d7d67b012 | ||
|
|
5b778bfc0d | ||
|
|
6ce414cecf | ||
|
|
c8160b63e7 | ||
|
|
68d957fd6e | ||
|
|
f09c438500 | ||
|
|
9bc9944a3e | ||
|
|
9e4c2b13d5 | ||
|
|
cd7143047f | ||
|
|
d608ac4d94 | ||
|
|
9fedf9d10d | ||
|
|
9936191da2 | ||
|
|
538eba3acf | ||
|
|
e39ee9a6f7 |
+2
-3
@@ -161,11 +161,8 @@ plugins/own_*
|
||||
plugins/my_*
|
||||
plugins/l2tp
|
||||
plugins/openlitespeed
|
||||
plugins/system_safe
|
||||
plugins/tamper_proof
|
||||
plugins/tamper_proof_*
|
||||
plugins/cryptocurrency_trade
|
||||
plugins/op_load_balance
|
||||
plugins/gdrive
|
||||
plugins/mtproxy
|
||||
plugins/zimg
|
||||
@@ -180,3 +177,5 @@ debug.out
|
||||
|
||||
|
||||
|
||||
mdioks.session-journal
|
||||
*.session
|
||||
|
||||
@@ -99,10 +99,15 @@ docker run -itd --name mw-server --privileged=true -p 7200:7200 -p 80:80 -p 443:
|
||||
```
|
||||
|
||||
|
||||
### 版本更新 0.13.5
|
||||
### 版本更新 0.15.0
|
||||
|
||||
* 添加邮件通知功能。
|
||||
* 修复初始安装脚本。
|
||||
* debian12适配。
|
||||
* 添加nezha插件。
|
||||
* 优化域名ssl保存功能。
|
||||
* 修复PHP扩展intl不加载问题(debian/ubuntu)。
|
||||
* 修复redhat安装openresty缺少openssl-devel。
|
||||
* docker插件-将就能用。
|
||||
* tgbot接收和push任务分离。
|
||||
|
||||
### JSDelivr安装地址
|
||||
|
||||
@@ -129,14 +134,14 @@ wget --no-check-certificate -O uninstall.sh https://cdn.jsdelivr.net/gh/midoks/m
|
||||
- 初始安装
|
||||
|
||||
```
|
||||
curl --insecure -fsSL https://raw.githubusercontent.com/midoks/mdserver-web/master/scripts/install.sh | bash
|
||||
curl --insecure -fsSL https://gitee.com/midoks/mdserver-web/raw/master/scripts/install.sh | bash
|
||||
curl --insecure -fsSL https://raw.githubusercontent.com/midoks/mdserver-web/master/scripts/install.sh | bash
|
||||
curl --insecure -fsSL https://code.midoks.me/midoks/mdserver-web/raw/branch/master/scripts/install.sh | bash
|
||||
```
|
||||
|
||||
- 直接更新
|
||||
|
||||
```
|
||||
curl --insecure -fsSL https://raw.githubusercontent.com/midoks/mdserver-web/master/scripts/update.sh | bash
|
||||
curl --insecure -fsSL https://raw.githubusercontent.com/midoks/mdserver-web/master/scripts/update.sh | bash
|
||||
```
|
||||
|
||||
- 卸载脚本
|
||||
|
||||
@@ -28,6 +28,7 @@ from route import app, socketio
|
||||
from gevent.pywsgi import WSGIServer
|
||||
from geventwebsocket.handler import WebSocketHandler
|
||||
|
||||
|
||||
from gevent import monkey
|
||||
monkey.patch_all()
|
||||
|
||||
|
||||
@@ -930,7 +930,8 @@ fi
|
||||
index).encode()
|
||||
)
|
||||
X509Req.set_pubkey(pk)
|
||||
X509Req.set_version(2)
|
||||
# X509Req.set_version(2)
|
||||
X509Req.set_version(0)
|
||||
X509Req.sign(pk, self.__digest)
|
||||
return OpenSSL.crypto.dump_certificate_request(OpenSSL.crypto.FILETYPE_ASN1, X509Req)
|
||||
|
||||
@@ -1006,7 +1007,7 @@ fi
|
||||
try:
|
||||
result = {}
|
||||
x509 = OpenSSL.crypto.load_certificate(
|
||||
OpenSSL.crypto.FILETYPE_PEM, public.readFile(pem_file))
|
||||
OpenSSL.crypto.FILETYPE_PEM, mw.readFile(pem_file))
|
||||
# 取产品名称
|
||||
issuer = x509.get_issuer()
|
||||
result['issuer'] = ''
|
||||
@@ -1280,16 +1281,16 @@ fullchain.pem 粘贴到证书输入框
|
||||
# 获取当前正在使用此证书的网站目录
|
||||
def getSslUsedSite(self, save_path):
|
||||
pkey_file = '{}/privkey.pem'.format(save_path)
|
||||
pkey = public.readFile(pkey_file)
|
||||
pkey = mw.readFile(pkey_file)
|
||||
if not pkey:
|
||||
return False
|
||||
cert_paths = 'vhost/cert'
|
||||
import panelSite
|
||||
args = public.dict_obj()
|
||||
args = mw.dict_obj()
|
||||
args.siteName = ''
|
||||
for c_name in os.listdir(cert_paths):
|
||||
skey_file = '{}/{}/privkey.pem'.format(cert_paths, c_name)
|
||||
skey = public.readFile(skey_file)
|
||||
skey = mw.readFile(skey_file)
|
||||
if not skey:
|
||||
continue
|
||||
if skey == pkey:
|
||||
@@ -1297,7 +1298,7 @@ fullchain.pem 粘贴到证书输入框
|
||||
run_path = panelSite.panelSite().GetRunPath(args)
|
||||
if not run_path:
|
||||
continue
|
||||
sitePath = public.M('sites').where(
|
||||
sitePath = mw.M('sites').where(
|
||||
'name=?', c_name).getField('path')
|
||||
if not sitePath:
|
||||
continue
|
||||
@@ -1315,7 +1316,7 @@ fullchain.pem 粘贴到证书输入框
|
||||
self.__config['orders'] = {}
|
||||
import panelSite
|
||||
siteObj = panelSite.panelSite()
|
||||
args = public.dict_obj()
|
||||
args = mw.dict_obj()
|
||||
for siteName in os.listdir(cert_path):
|
||||
try:
|
||||
cert_file = '{}/{}/fullchain.pem'.format(cert_path, siteName)
|
||||
|
||||
@@ -840,7 +840,8 @@ class cert_request:
|
||||
index).encode()
|
||||
)
|
||||
X509Req.set_pubkey(pk)
|
||||
X509Req.set_version(2)
|
||||
# X509Req.set_version(2)
|
||||
X509Req.set_version(0)
|
||||
X509Req.sign(pk, self.__digest)
|
||||
return OpenSSL.crypto.dump_certificate_request(OpenSSL.crypto.FILETYPE_ASN1, X509Req)
|
||||
|
||||
@@ -916,7 +917,7 @@ class cert_request:
|
||||
try:
|
||||
result = {}
|
||||
x509 = OpenSSL.crypto.load_certificate(
|
||||
OpenSSL.crypto.FILETYPE_PEM, public.readFile(pem_file))
|
||||
OpenSSL.crypto.FILETYPE_PEM, mw.readFile(pem_file))
|
||||
# 取产品名称
|
||||
issuer = x509.get_issuer()
|
||||
result['issuer'] = ''
|
||||
@@ -1186,16 +1187,16 @@ fullchain.pem 粘贴到证书输入框
|
||||
# 获取当前正在使用此证书的网站目录
|
||||
def getSslUsedSite(self, save_path):
|
||||
pkey_file = '{}/privkey.pem'.format(save_path)
|
||||
pkey = public.readFile(pkey_file)
|
||||
pkey = mw.readFile(pkey_file)
|
||||
if not pkey:
|
||||
return False
|
||||
cert_paths = 'vhost/cert'
|
||||
import panelSite
|
||||
args = public.dict_obj()
|
||||
args = mw.dict_obj()
|
||||
args.siteName = ''
|
||||
for c_name in os.listdir(cert_paths):
|
||||
skey_file = '{}/{}/privkey.pem'.format(cert_paths, c_name)
|
||||
skey = public.readFile(skey_file)
|
||||
skey = mw.readFile(skey_file)
|
||||
if not skey:
|
||||
continue
|
||||
if skey == pkey:
|
||||
@@ -1203,7 +1204,7 @@ fullchain.pem 粘贴到证书输入框
|
||||
run_path = panelSite.panelSite().GetRunPath(args)
|
||||
if not run_path:
|
||||
continue
|
||||
sitePath = public.M('sites').where(
|
||||
sitePath = mw.M('sites').where(
|
||||
'name=?', c_name).getField('path')
|
||||
if not sitePath:
|
||||
continue
|
||||
@@ -1221,7 +1222,7 @@ fullchain.pem 粘贴到证书输入框
|
||||
self.__config['orders'] = {}
|
||||
import panelSite
|
||||
siteObj = panelSite.panelSite()
|
||||
args = public.dict_obj()
|
||||
args = mw.dict_obj()
|
||||
for siteName in os.listdir(cert_path):
|
||||
try:
|
||||
cert_file = '{}/{}/fullchain.pem'.format(cert_path, siteName)
|
||||
|
||||
@@ -27,7 +27,7 @@ from flask import request
|
||||
|
||||
class config_api:
|
||||
|
||||
__version = '0.13.5'
|
||||
__version = '0.15.0'
|
||||
__api_addr = 'data/api.json'
|
||||
|
||||
def __init__(self):
|
||||
|
||||
+1
-1
@@ -65,7 +65,7 @@ class Sql():
|
||||
self.__DB_TABLE = table
|
||||
return self
|
||||
|
||||
def where(self, where, param):
|
||||
def where(self, where, param=()):
|
||||
# WHERE条件
|
||||
if where:
|
||||
self.__OPT_WHERE = " WHERE " + where
|
||||
|
||||
+133
-4
@@ -23,11 +23,13 @@ import shlex
|
||||
import datetime
|
||||
import subprocess
|
||||
import glob
|
||||
|
||||
import base64
|
||||
import re
|
||||
import db
|
||||
|
||||
from random import Random
|
||||
|
||||
import db
|
||||
|
||||
|
||||
def execShell(cmdstring, cwd=None, timeout=None, shell=True):
|
||||
|
||||
@@ -776,6 +778,133 @@ def deDoubleCrypt(key, strings):
|
||||
return strings
|
||||
|
||||
|
||||
def aesEncrypt(data, key='ABCDEFGHIJKLMNOP', vi='0102030405060708'):
|
||||
# aes加密
|
||||
# @param data 被加密的数据
|
||||
# @param key 加解密密匙 16位
|
||||
# @param vi 16位
|
||||
|
||||
from cryptography.hazmat.primitives import padding
|
||||
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
||||
from cryptography.hazmat.backends import default_backend
|
||||
|
||||
if not isinstance(data, bytes):
|
||||
data = data.encode()
|
||||
|
||||
# AES_CBC_KEY = os.urandom(32)
|
||||
# AES_CBC_IV = os.urandom(16)
|
||||
|
||||
AES_CBC_KEY = key.encode()
|
||||
AES_CBC_IV = vi.encode()
|
||||
|
||||
# print("AES_CBC_KEY:", AES_CBC_KEY)
|
||||
# print("AES_CBC_IV:", AES_CBC_IV)
|
||||
|
||||
padder = padding.PKCS7(algorithms.AES.block_size).padder()
|
||||
padded_data = padder.update(data) + padder.finalize()
|
||||
|
||||
cipher = Cipher(algorithms.AES(AES_CBC_KEY),
|
||||
modes.CBC(AES_CBC_IV),
|
||||
backend=default_backend())
|
||||
encryptor = cipher.encryptor()
|
||||
|
||||
edata = encryptor.update(padded_data)
|
||||
|
||||
# print(edata)
|
||||
# print(str(edata))
|
||||
# print(edata.decode())
|
||||
return edata
|
||||
|
||||
|
||||
def aesDecrypt(data, key='ABCDEFGHIJKLMNOP', vi='0102030405060708'):
|
||||
# aes加密
|
||||
# @param data 被解密的数据
|
||||
# @param key 加解密密匙 16位
|
||||
# @param vi 16位
|
||||
|
||||
from cryptography.hazmat.primitives import padding
|
||||
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
||||
from cryptography.hazmat.backends import default_backend
|
||||
|
||||
from cryptography.hazmat.primitives import padding
|
||||
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
||||
from cryptography.hazmat.backends import default_backend
|
||||
|
||||
if not isinstance(data, bytes):
|
||||
data = data.encode()
|
||||
|
||||
AES_CBC_KEY = key.encode()
|
||||
AES_CBC_IV = vi.encode()
|
||||
|
||||
cipher = Cipher(algorithms.AES(AES_CBC_KEY),
|
||||
modes.CBC(AES_CBC_IV),
|
||||
backend=default_backend())
|
||||
decryptor = cipher.decryptor()
|
||||
|
||||
ddata = decryptor.update(data)
|
||||
|
||||
unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
|
||||
data = unpadder.update(ddata)
|
||||
|
||||
try:
|
||||
uppadded_data = data + unpadder.finalize()
|
||||
except ValueError:
|
||||
raise Exception('无效的加密信息!')
|
||||
|
||||
return uppadded_data
|
||||
|
||||
|
||||
def aesEncrypt_Crypto(data, key, vi):
|
||||
# 该方法保留,暂时不使用
|
||||
# aes加密
|
||||
# @param data 被加密的数据
|
||||
# @param key 加解密密匙 16位
|
||||
# @param vi 16位
|
||||
|
||||
from Crypto.Cipher import AES
|
||||
cryptor = AES.new(key.encode('utf8'), AES.MODE_CBC, vi.encode('utf8'))
|
||||
# 判断是否含有中文
|
||||
zhmodel = re.compile(u'[\u4e00-\u9fff]')
|
||||
match = zhmodel.search(data)
|
||||
if match == None:
|
||||
# 无中文时
|
||||
add = 16 - len(data) % 16
|
||||
pad = lambda s: s + add * chr(add)
|
||||
data = pad(data)
|
||||
enctext = cryptor.encrypt(data.encode('utf8'))
|
||||
else:
|
||||
# 含有中文时
|
||||
data = data.encode()
|
||||
add = 16 - len(data) % 16
|
||||
data = data + add * (chr(add)).encode()
|
||||
enctext = cryptor.encrypt(data)
|
||||
encodestrs = base64.b64encode(enctext).decode('utf8')
|
||||
return encodestrs
|
||||
|
||||
|
||||
def aesDecrypt_Crypto(data, key, vi):
|
||||
# 该方法保留,暂时不使用
|
||||
# aes加密
|
||||
# @param data 被加密的数据
|
||||
# @param key 加解密密匙 16位
|
||||
# @param vi 16位
|
||||
|
||||
from crypto.Cipher import AES
|
||||
data = data.encode('utf8')
|
||||
encodebytes = base64.urlsafe_b64decode(data)
|
||||
cipher = AES.new(key.encode('utf8'), AES.MODE_CBC, vi.encode('utf8'))
|
||||
text_decrypted = cipher.decrypt(encodebytes)
|
||||
# 判断是否含有中文
|
||||
zhmodel = re.compile(u'[\u4e00-\u9fff]')
|
||||
match = zhmodel.search(text_decrypted)
|
||||
if match == False:
|
||||
# 无中文时补位
|
||||
unpad = lambda s: s[0:-s[-1]]
|
||||
text_decrypted = unpad(text_decrypted)
|
||||
text_decrypted = text_decrypted.decode('utf8').rstrip() # 去掉补位的右侧空格
|
||||
return text_decrypted
|
||||
|
||||
|
||||
def buildSoftLink(src, dst, force=False):
|
||||
'''
|
||||
建立软连接
|
||||
@@ -1276,7 +1405,7 @@ def makeConf():
|
||||
file = getRunDir() + '/data/json/config.json'
|
||||
if not os.path.exists(file):
|
||||
c = {}
|
||||
c['title'] = '金蝉面板'
|
||||
c['title'] = '金灵面板'
|
||||
c['home'] = 'http://github/midoks/mdserver-web'
|
||||
c['recycle_bin'] = True
|
||||
c['template'] = 'default'
|
||||
@@ -1781,7 +1910,7 @@ def emailNotifyMessage(data):
|
||||
|
||||
|
||||
def emailNotifyTest(data):
|
||||
print(data)
|
||||
# print(data)
|
||||
data['subject'] = 'MW通知测试'
|
||||
data['content'] = data['mail_test']
|
||||
return emailNotifyMessage(data)
|
||||
|
||||
@@ -71,8 +71,9 @@ class plugins_api:
|
||||
if not mw.isNumber(sType):
|
||||
sType = 0
|
||||
|
||||
# print sPage
|
||||
data = self.getPluginList(sType, int(sPage))
|
||||
# print(sPage, sType)
|
||||
search = request.args.get('search', '').lower()
|
||||
data = self.getPluginList(sType, search, int(sPage))
|
||||
return mw.getJson(data)
|
||||
|
||||
def menuGetAbsPath(self, tag, path):
|
||||
@@ -781,7 +782,18 @@ class plugins_api:
|
||||
print(e)
|
||||
return plugins_info
|
||||
|
||||
def getAllListPage(self, sType='0', page=1, pageSize=10):
|
||||
def searchKey(self, info, kw):
|
||||
try:
|
||||
if info['title'].lower().find(kw) > -1:
|
||||
return True
|
||||
if info['ps'].lower().find(kw) > -1:
|
||||
return True
|
||||
if info['name'].lower().find(kw) > -1:
|
||||
return True
|
||||
except Exception as e:
|
||||
return False
|
||||
|
||||
def getAllListPage(self, sType='0', kw='', page=1, pageSize=10):
|
||||
plugins_info = []
|
||||
for dirinfo in os.listdir(self.__plugin_dir):
|
||||
if dirinfo[0:1] == '.':
|
||||
@@ -792,11 +804,13 @@ class plugins_api:
|
||||
if os.path.exists(json_file):
|
||||
try:
|
||||
data = json.loads(mw.readFile(json_file))
|
||||
# 判断是否搜索
|
||||
if kw != '' and not self.searchKey(data, kw):
|
||||
continue
|
||||
tmp_data = self.makeList(data, sType)
|
||||
for index in range(len(tmp_data)):
|
||||
plugins_info.append(tmp_data[index])
|
||||
except Exception as e:
|
||||
print(json_file)
|
||||
print(mw.getTracebackInfo())
|
||||
|
||||
start = (page - 1) * pageSize
|
||||
@@ -927,14 +941,14 @@ class plugins_api:
|
||||
|
||||
return plugins_info
|
||||
|
||||
def getPluginList(self, sType, sPage=1, sPageSize=10):
|
||||
# print sType, sPage, sPageSize
|
||||
def getPluginList(self, sType, kw='', sPage=1, sPageSize=10):
|
||||
# print(sType, kw, sPage, sPageSize)
|
||||
|
||||
ret = {}
|
||||
ret['type'] = json.loads(mw.readFile(self.__type))
|
||||
# plugins_info = self.getAllListThread(sType)
|
||||
# plugins_info = self.getAllListProcess(sType)
|
||||
data = self.getAllListPage(sType, sPage, sPageSize)
|
||||
data = self.getAllListPage(sType, kw, sPage, sPageSize)
|
||||
ret['data'] = data[0]
|
||||
|
||||
args = {}
|
||||
@@ -1016,8 +1030,11 @@ class plugins_api:
|
||||
|
||||
# shell 调用
|
||||
def run(self, name, func, version='', args='', script='index'):
|
||||
path = self.__plugin_dir + \
|
||||
'/' + name + '/' + script + '.py'
|
||||
|
||||
path = self.__plugin_dir + '/' + name + '/' + script + '.py'
|
||||
if not os.path.exists(path):
|
||||
path = self.__plugin_dir + '/' + name + '/' + name + '.py'
|
||||
|
||||
py = 'python3 ' + path
|
||||
|
||||
if args == '':
|
||||
|
||||
+20
-5
@@ -101,19 +101,31 @@ class site_api:
|
||||
limit = request.form.get('limit', '10')
|
||||
p = request.form.get('p', '1')
|
||||
type_id = request.form.get('type_id', '0').strip()
|
||||
search = request.form.get('search', '').strip()
|
||||
|
||||
start = (int(p) - 1) * (int(limit))
|
||||
|
||||
siteM = mw.M('sites').field('id,name,path,status,ps,addtime,edate')
|
||||
if type_id != '' and int(type_id) >= 0:
|
||||
siteM.where('type_id=?', (type_id,))
|
||||
|
||||
sql_where = ''
|
||||
if search != '':
|
||||
sql_where = " name like '%" + search + "%' or ps like '%" + search + "%' "
|
||||
|
||||
if type_id != '' and int(type_id) >= 0 and search != '':
|
||||
sql_where = sql_where + " and type_id=" + type_id + ""
|
||||
elif type_id != '' and int(type_id) >= 0:
|
||||
sql_where = " type_id=" + type_id
|
||||
|
||||
if sql_where != '':
|
||||
siteM.where(sql_where)
|
||||
|
||||
_list = siteM.limit((str(start)) + ',' +
|
||||
limit).order('id desc').select()
|
||||
|
||||
for i in range(len(_list)):
|
||||
_list[i]['backup_count'] = mw.M('backup').where(
|
||||
"pid=? AND type=?", (_list[i]['id'], 0)).count()
|
||||
if _list != None:
|
||||
for i in range(len(_list)):
|
||||
_list[i]['backup_count'] = mw.M('backup').where(
|
||||
"pid=? AND type=?", (_list[i]['id'], 0)).count()
|
||||
|
||||
_ret = {}
|
||||
_ret['data'] = _list
|
||||
@@ -775,6 +787,9 @@ class site_api:
|
||||
mw.execShell('echo "lets" > "' + path + '/README"')
|
||||
elif ssl_type == 'acme':
|
||||
ssl_acme_dir = mw.getAcmeDir() + '/' + site_name
|
||||
if not os.path.exists(ssl_acme_dir):
|
||||
ssl_acme_dir = mw.getAcmeDir() + '/' + site_name + '_ecc'
|
||||
|
||||
acme_csrpath = ssl_acme_dir + '/fullchain.cer'
|
||||
acme_keypath = ssl_acme_dir + '/' + site_name + '.key'
|
||||
if mw.md5(mw.readFile(acme_csrpath)) == mw.md5(mw.readFile(csr_path)):
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
# coding:utf-8
|
||||
|
||||
# ---------------------------------------------------------------------------------
|
||||
# MW-Linux面板
|
||||
# ---------------------------------------------------------------------------------
|
||||
# copyright (c) 2018-∞(https://github.com/midoks/mdserver-web) All rights reserved.
|
||||
# ---------------------------------------------------------------------------------
|
||||
# Author: midoks <midoks@163.com>
|
||||
# ---------------------------------------------------------------------------------
|
||||
|
||||
# ---------------------------------------------------------------------------------
|
||||
# VIP用户管理
|
||||
# ---------------------------------------------------------------------------------
|
||||
|
||||
import mw
|
||||
|
||||
from flask import request
|
||||
import requests
|
||||
|
||||
|
||||
class vip_api:
|
||||
|
||||
api_url = 'https://wo.midoks.me/api/wp-json/vip'
|
||||
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
def loginApi(self):
|
||||
username = request.form.get('username', '')
|
||||
password = request.form.get('password', '')
|
||||
password = mw.aesEncrypt(password)
|
||||
|
||||
headers = {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
}
|
||||
|
||||
print("name:", str(username))
|
||||
print("pwd:", str(password))
|
||||
args = {
|
||||
'name': username,
|
||||
'pass': password
|
||||
}
|
||||
data = requests.post(self.api_url + '/v1/login',
|
||||
data=args, headers=headers)
|
||||
|
||||
print(data.text)
|
||||
|
||||
return mw.returnJson(False, "测试中!")
|
||||
+20
-17
@@ -16,6 +16,7 @@ cd /www/server/mdserver-web/plugins/php/versions && bash all_test.sh
|
||||
| CentOS 9 Stream |✅ |✅ |
|
||||
| Debian 10.3 |✅ |✅ |
|
||||
| Debian 11.3 |✅ |✅ |
|
||||
| Debian 12.0 |✅ |✅ |
|
||||
| Ubuntu 18.04 |✅ |✅ |
|
||||
| Ubuntu 20.04 |✅ |✅ |
|
||||
| Ubuntu 22.04 |✅ |✅ |
|
||||
@@ -28,23 +29,24 @@ cd /www/server/mdserver-web/plugins/php/versions && bash all_test.sh
|
||||
|
||||
|
||||
|
||||
| 系统名称 |PHP53 |PHP54 |PHP55 |PHP56 |PHP70 |PHP71 |PHP72 |PHP73 |PHP74 |PHP80 |PHP81 |
|
||||
| ----------------- |-------|-------|-------|-------|-------|-------|-------|-------|-------|-------|-------|
|
||||
| CentOS 7.9 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| CentOS 8.4 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| CentOS 8 Stream |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| CentOS 9 Stream |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Debian 10.3 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Debian 11.3 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Ubuntu 18.04 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Ubuntu 20.04 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Ubuntu 22.04 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Fedora 31 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Fedora 32 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| AlmaLinux 9 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| RockyLinux 8.6 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Arch Linux |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| openSUSE 15.4 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| 系统名称 |PHP53 |PHP54 |PHP55 |PHP56 |PHP70 |PHP71 |PHP72 |PHP73 |PHP74 |PHP80 |PHP81 |PHP82 |
|
||||
| ----------------- |-------|-------|-------|-------|-------|-------|-------|-------|-------|-------|-------|-------|
|
||||
| CentOS 7.9 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| CentOS 8.4 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| CentOS 8 Stream |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| CentOS 9 Stream |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Debian 10.3 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Debian 11.3 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Debian 12 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Ubuntu 18.04 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Ubuntu 20.04 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Ubuntu 22.04 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Fedora 31 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Fedora 32 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| AlmaLinux 9 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| RockyLinux 8.6 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Arch Linux |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| openSUSE 15.4 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
|
||||
|
||||
|
||||
@@ -56,6 +58,7 @@ cd /www/server/mdserver-web/plugins/php/versions && bash all_test.sh
|
||||
| CentOS 9 Stream |✅ |✅ |✅ |✅ |
|
||||
| Debian 10.3 |✅ |✅ |✅ |✅ |
|
||||
| Debian 11.3 |✅ |✅ |✅ |✅ |
|
||||
| Debian 12 |✅ |✅ |✅ |✅ |
|
||||
| Ubuntu 18.04 |✅ |✅ |✅ |✅ |
|
||||
| Ubuntu 20.04 |✅ |✅ |✅ |✅ |
|
||||
| Ubuntu 22.04 |✅ |✅ |✅ |✅ |
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
存放VIP关键数据
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.5 KiB |
Executable
+56
@@ -0,0 +1,56 @@
|
||||
<style type="text/css">
|
||||
|
||||
.docker-sub {
|
||||
border-bottom: 1px solid #ccc;
|
||||
height: 30px;
|
||||
line-height: 30px;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.docker-sub .on {
|
||||
border-bottom: 2px solid #20a53a;
|
||||
color: #20a53a;
|
||||
font-weight: bold;
|
||||
font-family: "宋体";
|
||||
}
|
||||
.docker-sub span {
|
||||
display: inline-block;
|
||||
font-size: 14px;
|
||||
height: 30px;
|
||||
padding: 0 25px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.docker-environments {
|
||||
resize: none;
|
||||
width: 330px;
|
||||
height: 80px;
|
||||
line-height: 20px;
|
||||
padding: 5px 8px;
|
||||
border: 1px solid #ddd;
|
||||
font-size: 12px;
|
||||
}
|
||||
</style>
|
||||
|
||||
<div class="bt-form">
|
||||
<div class='plugin_version'></div>
|
||||
<div class="bt-w-main">
|
||||
<div class="bt-w-menu">
|
||||
<p class="bgw" onclick="pluginService('docker');">服务</p>
|
||||
<p onclick="pluginInitD('docker');">自启动</p>
|
||||
<p onclick="dockerConList();">容器列表</p>
|
||||
<p onclick="dockerImageList();">镜像列表</p>
|
||||
<p onclick="repoList();">仓库</p>
|
||||
</div>
|
||||
<div class="bt-w-con pd15">
|
||||
<div class="soft-man-con"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script type="text/javascript">
|
||||
resetPluginWinWidth(800);
|
||||
resetPluginWinHeight(400);
|
||||
$.getScript( "/plugins/file?name=docker&f=js/docker.js", function(){
|
||||
pluginService('docker', $('.plugin_version').attr('version'));
|
||||
});
|
||||
</script>
|
||||
Executable
+669
@@ -0,0 +1,669 @@
|
||||
# coding:utf-8
|
||||
|
||||
import sys
|
||||
import io
|
||||
import os
|
||||
import time
|
||||
import re
|
||||
import json
|
||||
|
||||
sys.path.append(os.getcwd() + "/class/core")
|
||||
import mw
|
||||
|
||||
import docker
|
||||
|
||||
|
||||
app_debug = False
|
||||
if mw.isAppleSystem():
|
||||
app_debug = True
|
||||
|
||||
|
||||
def getDClient():
|
||||
try:
|
||||
client = docker.from_env()
|
||||
except Exception as e:
|
||||
client = docker.DockerClient(
|
||||
base_url='unix:///Users/midoks/.docker/run/docker.sock')
|
||||
return client
|
||||
|
||||
|
||||
def getPluginName():
|
||||
return 'docker'
|
||||
|
||||
|
||||
def getPluginDir():
|
||||
return mw.getPluginDir() + '/' + getPluginName()
|
||||
|
||||
|
||||
def getServerDir():
|
||||
return mw.getServerDir() + '/' + getPluginName()
|
||||
|
||||
|
||||
def getConf():
|
||||
path = getServerDir() + "/redis.conf"
|
||||
return path
|
||||
|
||||
|
||||
def getConfTpl():
|
||||
path = getPluginDir() + "/config/redis.conf"
|
||||
return path
|
||||
|
||||
|
||||
def getInitDTpl():
|
||||
path = getPluginDir() + "/init.d/" + getPluginName() + ".tpl"
|
||||
return path
|
||||
|
||||
|
||||
def getArgs():
|
||||
args = sys.argv[2:]
|
||||
tmp = {}
|
||||
args_len = len(args)
|
||||
|
||||
if args_len == 1:
|
||||
t = args[0].strip('{').strip('}')
|
||||
if t.strip() == '':
|
||||
tmp = []
|
||||
else:
|
||||
t = t.split(':', 1)
|
||||
tmp[t[0]] = t[1]
|
||||
tmp[t[0]] = t[1]
|
||||
elif args_len > 1:
|
||||
for i in range(len(args)):
|
||||
t = args[i].split(':', 1)
|
||||
tmp[t[0]] = t[1]
|
||||
return tmp
|
||||
|
||||
|
||||
def checkArgs(self, data, ck=[]):
|
||||
for i in range(len(ck)):
|
||||
print(data[i])
|
||||
if not ck[i] in data:
|
||||
return (False, mw.returnJson(False, '参数:(' + ck[i] + ')没有!'))
|
||||
return (True, mw.returnJson(True, 'ok'))
|
||||
|
||||
|
||||
def status():
|
||||
data = mw.execShell(
|
||||
"ps -ef|grep docker |grep -v grep | grep -v python | grep -v mdserver-web | awk '{print $2}'")
|
||||
|
||||
if data[0] == '':
|
||||
return 'stop'
|
||||
return 'start'
|
||||
|
||||
|
||||
def initDreplace():
|
||||
return ''
|
||||
|
||||
|
||||
def dockerOp(method):
|
||||
file = initDreplace()
|
||||
|
||||
if not mw.isAppleSystem():
|
||||
data = mw.execShell('systemctl ' + method + ' docker')
|
||||
if data[1] == '':
|
||||
return 'ok'
|
||||
return data[1]
|
||||
return 'fail'
|
||||
|
||||
|
||||
def start():
|
||||
return dockerOp('start')
|
||||
|
||||
|
||||
def stop():
|
||||
return dockerOp('stop')
|
||||
|
||||
|
||||
def restart():
|
||||
status = dockerOp('restart')
|
||||
|
||||
log_file = runLog()
|
||||
mw.execShell("echo '' > " + log_file)
|
||||
return status
|
||||
|
||||
|
||||
def reload():
|
||||
return dockerOp('reload')
|
||||
|
||||
|
||||
def initdStatus():
|
||||
if mw.isAppleSystem():
|
||||
return "Apple Computer does not support"
|
||||
|
||||
shell_cmd = 'systemctl status ' + \
|
||||
getPluginName() + ' | grep loaded | grep "enabled;"'
|
||||
data = mw.execShell(shell_cmd)
|
||||
if data[0] == '':
|
||||
return 'fail'
|
||||
return 'ok'
|
||||
|
||||
|
||||
def initdInstall():
|
||||
if mw.isAppleSystem():
|
||||
return "Apple Computer does not support"
|
||||
|
||||
mw.execShell('systemctl enable ' + getPluginName())
|
||||
return 'ok'
|
||||
|
||||
|
||||
def initdUinstall():
|
||||
if mw.isAppleSystem():
|
||||
return "Apple Computer does not support"
|
||||
|
||||
mw.execShell('systemctl disable ' + getPluginName())
|
||||
return 'ok'
|
||||
|
||||
# UTC时间转换为时间戳
|
||||
|
||||
|
||||
def utc_to_local(utc_time_str, utc_format='%Y-%m-%dT%H:%M:%S'):
|
||||
import pytz
|
||||
import datetime
|
||||
import time
|
||||
local_tz = pytz.timezone('Asia/Chongqing')
|
||||
local_format = "%Y-%m-%d %H:%M"
|
||||
utc_dt = datetime.datetime.strptime(utc_time_str, utc_format)
|
||||
local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz)
|
||||
time_str = local_dt.strftime(local_format)
|
||||
return int(time.mktime(time.strptime(time_str, local_format)))
|
||||
|
||||
|
||||
def conList():
|
||||
c = getDClient()
|
||||
clist = c.containers.list(all=True)
|
||||
conList = []
|
||||
for con in clist:
|
||||
tmp = con.attrs
|
||||
tmp['Created'] = utc_to_local(tmp['Created'].split('.')[0])
|
||||
conList.append(tmp)
|
||||
return conList
|
||||
|
||||
|
||||
def conListData():
|
||||
try:
|
||||
clist = conList()
|
||||
except Exception as e:
|
||||
return mw.returnJson(False, '未开启Docker')
|
||||
return mw.returnJson(True, 'ok', clist)
|
||||
|
||||
|
||||
def dockerRemoveCon():
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['Hostname'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
Hostname = args['Hostname']
|
||||
|
||||
c = getDClient()
|
||||
try:
|
||||
conFind = c.containers.get(Hostname)
|
||||
try:
|
||||
path_list = conFind.attrs['GraphDriver'][
|
||||
'Data']['LowerDir'].split(':')
|
||||
for i in path_list:
|
||||
mw.execShell('chattr -R -i %s' % i)
|
||||
except:
|
||||
pass
|
||||
conFind.remove(force=True)
|
||||
return mw.returnJson(True, '成功删除!')
|
||||
except docker.errors.APIError as ex:
|
||||
return mw.returnJson(False, '删除失败!' + str(ex))
|
||||
|
||||
|
||||
def dockerLogCon():
|
||||
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['Hostname'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
Hostname = args['Hostname']
|
||||
|
||||
c = getDClient()
|
||||
try:
|
||||
conFind = c.containers.get(Hostname)
|
||||
if not conFind:
|
||||
return mw.returnJson(False, 'The specified container does not exist!')
|
||||
log = conFind.logs()
|
||||
if not isinstance(log, str):
|
||||
log = log.decode()
|
||||
return mw.returnJson(True, log)
|
||||
except docker.errors.APIError as ex:
|
||||
return mw.returnJson(False, 'Get Logs failed')
|
||||
|
||||
|
||||
def dockerRunCon():
|
||||
# 启动容器
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['Hostname'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
Hostname = args['Hostname']
|
||||
c = getDClient()
|
||||
try:
|
||||
conFind = c.containers.get(Hostname)
|
||||
if not conFind:
|
||||
return mw.returnJson(False, 'The specified container does not exist!')
|
||||
conFind.start()
|
||||
return mw.returnJson(True, '启动成功!')
|
||||
except docker.errors.APIError as ex:
|
||||
return mw.returnJson(False, '启动失败!' + str(ex))
|
||||
|
||||
|
||||
def dockerStopCon():
|
||||
# 停止容器
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['Hostname'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
Hostname = args['Hostname']
|
||||
c = getDClient()
|
||||
try:
|
||||
conFind = c.containers.get(Hostname)
|
||||
if not conFind:
|
||||
return mw.returnJson(False, 'The specified container does not exist!')
|
||||
conFind.stop()
|
||||
return mw.returnJson(True, '停止成功!')
|
||||
except docker.errors.APIError as ex:
|
||||
return mw.returnJson(False, '停止失败!' + str(ex))
|
||||
|
||||
|
||||
def dockerExec():
|
||||
# 容器执行命令
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['Hostname'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
Hostname = args['Hostname']
|
||||
|
||||
debug_path = 'data/debug.pl'
|
||||
if os.path.exists(debug_path):
|
||||
return mw.returnJson(False, '开发模式不能进入!')
|
||||
|
||||
c = getDClient()
|
||||
try:
|
||||
conFind = c.containers.get(Hostname)
|
||||
cmd = 'docker container exec -it %s /bin/sh' % Hostname
|
||||
return mw.returnJson(True, cmd)
|
||||
except docker.errors.APIError as ex:
|
||||
return mw.returnJson(False, '连接失败!')
|
||||
|
||||
|
||||
def imageList():
|
||||
imageList = []
|
||||
c = getDClient()
|
||||
ilist = c.images.list()
|
||||
for image in ilist:
|
||||
tmp_attrs = image.attrs
|
||||
if len(tmp_attrs['RepoTags']) == 1:
|
||||
tmp_image = {}
|
||||
tmp_image['Id'] = tmp_attrs['Id'].split(':')[1][:12]
|
||||
tmp_image['RepoTags'] = tmp_attrs['RepoTags'][0]
|
||||
tmp_image['Size'] = tmp_attrs['Size']
|
||||
tmp_image['Labels'] = tmp_attrs['Config']['Labels']
|
||||
tmp_image['Comment'] = tmp_attrs['Comment']
|
||||
tmp_image['Created'] = utc_to_local(
|
||||
tmp_attrs['Created'].split('.')[0])
|
||||
imageList.append(tmp_image)
|
||||
else:
|
||||
for i in range(len(tmp_attrs['RepoTags'])):
|
||||
tmp_image = {}
|
||||
tmp_image['Id'] = tmp_attrs['Id'].split(':')[1][:12]
|
||||
tmp_image['RepoTags'] = tmp_attrs['RepoTags'][i]
|
||||
tmp_image['Size'] = tmp_attrs['Size']
|
||||
tmp_image['Labels'] = tmp_attrs['Config']['Labels']
|
||||
tmp_image['Comment'] = tmp_attrs['Comment']
|
||||
tmp_image['Created'] = utc_to_local(
|
||||
tmp_attrs['Created'].split('.')[0])
|
||||
imageList.append(tmp_image)
|
||||
imageList = sorted(imageList, key=lambda x: x['Created'], reverse=True)
|
||||
return imageList
|
||||
|
||||
|
||||
def dockerPull():
|
||||
# pull Dockr 官方镜像
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['images'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
images = args['images']
|
||||
if ':' in images:
|
||||
pass
|
||||
else:
|
||||
images = images + ':latest'
|
||||
|
||||
c = getDClient()
|
||||
try:
|
||||
ret = c.images.pull(images)
|
||||
if ret:
|
||||
return mw.returnJson(True, '拉取成功!')
|
||||
else:
|
||||
return mw.returnJson(False, '拉取失败,请检查镜像名称或是否需要登录docker进行下载')
|
||||
except:
|
||||
ret = mw.execShell('docker image pull %s' % images)
|
||||
if 'invalid' in ret[-1]:
|
||||
return mw.returnJson(False, '拉取失败,请检查镜像名称或是否需要登录docker进行下载')
|
||||
else:
|
||||
return mw.returnJson(True, '拉取成功!')
|
||||
|
||||
|
||||
def dockerPlulPath(path):
|
||||
if not path and path == '':
|
||||
return mw.returnJson(False, 'Invalid address')
|
||||
|
||||
ret = mw.execShell('docker image pull %s' % path)
|
||||
if 'invalid' in ret[-1]:
|
||||
return mw.returnJson(False, '拉取失败,请检查镜像名称或是否需要登录docker进行下载')
|
||||
else:
|
||||
return mw.returnJson(True, '拉取成功!')
|
||||
|
||||
|
||||
def dockerPullReg():
|
||||
# pull Dockr 官方镜像
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['path'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
path = args['path']
|
||||
return dockerPlulPath(path)
|
||||
|
||||
|
||||
# 判断镜像是否存在
|
||||
def checkImage(path):
|
||||
image_list = imageList()
|
||||
for i in image_list:
|
||||
if path == i["RepoTags"]:
|
||||
return mw.returnData(False, '镜像已存在!')
|
||||
|
||||
|
||||
def dockerPullPrivateNew():
|
||||
# pull Dockr 官方镜像
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['path'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
path = args['path']
|
||||
check = checkImage(path)
|
||||
if check:
|
||||
return mw.getJson(check)
|
||||
|
||||
my_repo = repoList()
|
||||
if not my_repo:
|
||||
return mw.returnJson(False, '未登录任何私人存储库,请登录然后拉取')
|
||||
return dockerPlulPath(path)
|
||||
|
||||
|
||||
def imageListData():
|
||||
try:
|
||||
ilist = imageList()
|
||||
except Exception as e:
|
||||
return mw.returnJson(False, '未开启Docker')
|
||||
return mw.returnJson(True, 'ok', ilist)
|
||||
|
||||
|
||||
def dockerRemoveImage():
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['imageId', 'repoTags'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
repoTags = args['repoTags']
|
||||
imageId = args['imageId']
|
||||
|
||||
c = getDClient()
|
||||
try:
|
||||
c.images.remove(repoTags)
|
||||
return mw.returnJson(True, '成功删除')
|
||||
except:
|
||||
try:
|
||||
c.images.remove(imageId)
|
||||
return mw.returnJson(True, '成功删除!')
|
||||
except docker.errors.APIError as ex:
|
||||
return mw.returnJson(False, '删除失败, 当前镜像正在使用!')
|
||||
|
||||
|
||||
def dockerLoginCheck(user_name, user_pass, registry):
|
||||
# 登陆验证
|
||||
cmd = 'docker login -u=%s -p %s %s' % (user_name, user_pass, registry)
|
||||
# print(cmd)
|
||||
login_test = mw.execShell(cmd)
|
||||
# print(login_test)
|
||||
ret = 'required$|Error'
|
||||
ret2 = re.findall(ret, login_test[-1])
|
||||
if len(ret2) == 0:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
def getDockerIpList():
|
||||
# 取IP列表
|
||||
path = getServerDir()
|
||||
ipConf = path + '/iplist.json'
|
||||
if not os.path.exists(ipConf):
|
||||
return []
|
||||
iplist = json.loads(mw.readFile(ipConf))
|
||||
return iplist
|
||||
|
||||
|
||||
def getDockerCreateInfo():
|
||||
# 取创建依赖
|
||||
import psutil
|
||||
data = {}
|
||||
data['images'] = imageList()
|
||||
data['memSize'] = int(psutil.virtual_memory().total / 1024 / 1024)
|
||||
data['iplist'] = getDockerIpList()
|
||||
return mw.returnJson(True, 'ok!', data)
|
||||
|
||||
|
||||
def __release_port(port):
|
||||
from collections import namedtuple
|
||||
try:
|
||||
import firewall_api
|
||||
firewall_api.firewall_api().addAcceptPortArgs(port, 'docker', 'port')
|
||||
return port
|
||||
except Exception as e:
|
||||
return "Release failed {}".format(e)
|
||||
|
||||
|
||||
def dockerCreateCon():
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['environments', 'command',
|
||||
'entrypoint', 'image', 'mem_limit', 'ports', 'volumes'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
environments = args['environments']
|
||||
environments = environments.strip().split()
|
||||
|
||||
command = args['command']
|
||||
entrypoint = args['entrypoint']
|
||||
image = args['image']
|
||||
mem_limit = args['mem_limit']
|
||||
ports = args['ports']
|
||||
ports = ports.replace('[', '(').replace(']', ')')
|
||||
volumes = args['volumes']
|
||||
|
||||
# if __name__ == "__main__":
|
||||
# print(args)
|
||||
try:
|
||||
|
||||
c = getDClient()
|
||||
conObject = c.containers.run(
|
||||
image=image,
|
||||
mem_limit=mem_limit + 'M',
|
||||
ports=eval(ports),
|
||||
auto_remove=False,
|
||||
command=command,
|
||||
detach=True,
|
||||
stdin_open=True,
|
||||
tty=True,
|
||||
entrypoint=entrypoint,
|
||||
privileged=True,
|
||||
volumes=json.loads(volumes),
|
||||
cpu_shares=10,
|
||||
environment=environments
|
||||
)
|
||||
if conObject:
|
||||
__release_port(ports)
|
||||
return mw.returnJson(True, '创建成功!')
|
||||
|
||||
return mw.returnJson(False, '创建失败!')
|
||||
except docker.errors.APIError as ex:
|
||||
return mw.returnJson(False, '创建失败!' + str(ex))
|
||||
|
||||
|
||||
def dockerLogin():
|
||||
args = getArgs()
|
||||
|
||||
# print(args)
|
||||
data = checkArgs(args, ['user', 'passwd', 'hub_name',
|
||||
'namespace', 'registry', 'repository_name'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
user_name = args['user']
|
||||
user_pass = args['passwd']
|
||||
registry = args['registry']
|
||||
hub_name = args['hub_name']
|
||||
namespace = args['namespace']
|
||||
repository_name = args['repository_name']
|
||||
|
||||
ret_status = dockerLoginCheck(user_name, user_pass, registry)
|
||||
path = getServerDir()
|
||||
if ret_status:
|
||||
user_file = path + '/user.json'
|
||||
user_info = mw.readFile(user_file)
|
||||
if not user_info:
|
||||
user_info = []
|
||||
else:
|
||||
user_info = json.loads(user_info)
|
||||
|
||||
ret = {}
|
||||
ret['user_name'] = user_name
|
||||
ret['user_pass'] = user_pass
|
||||
ret['registry'] = registry
|
||||
ret['hub_name'] = hub_name
|
||||
ret['namespace'] = namespace
|
||||
ret['repository_name'] = repository_name
|
||||
if not registry:
|
||||
ret['registry'] = "docker.io"
|
||||
user_info.append(ret)
|
||||
mw.writeFile(user_file, json.dumps(user_info))
|
||||
return mw.returnJson(True, '成功登录!')
|
||||
return mw.returnJson(False, '登录失败!')
|
||||
|
||||
|
||||
# 删除用户信息
|
||||
def delete_user_info(registry):
|
||||
path = getServerDir()
|
||||
user_file = path + '/user.json'
|
||||
user_info = mw.readFile(user_file)
|
||||
if user_info:
|
||||
user_info = json.loads(user_info)
|
||||
for i in range(len(user_info)):
|
||||
if registry in user_info[i].values():
|
||||
del(user_info[i])
|
||||
mw.writeFile(user_file, json.dumps(user_info))
|
||||
return True
|
||||
|
||||
|
||||
def dockerLogout():
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['registry'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
registry = args['registry']
|
||||
if registry == "docker.io":
|
||||
registry = ""
|
||||
login_test = mw.execShell('docker logout %s' % registry)
|
||||
if registry == "":
|
||||
registry = "docker.io"
|
||||
ret = 'required$|Error'
|
||||
ret2 = re.findall(ret, login_test[-1])
|
||||
delete_user_info(registry)
|
||||
if len(ret2) == 0:
|
||||
return mw.returnJson(True, '退出成功')
|
||||
else:
|
||||
return mw.returnJson(True, '退出失败')
|
||||
|
||||
|
||||
def repoList():
|
||||
path = getServerDir()
|
||||
repostory_info = []
|
||||
user_file = path + '/user.json'
|
||||
|
||||
if os.path.exists(user_file):
|
||||
user_info = mw.readFile(user_file)
|
||||
user_info = json.loads(user_info)
|
||||
for i in user_info:
|
||||
tmp = {}
|
||||
tmp["hub_name"] = i["hub_name"]
|
||||
tmp["registry"] = i["registry"]
|
||||
tmp["namespace"] = i["namespace"]
|
||||
tmp['repository_name'] = i["repository_name"]
|
||||
repostory_info.append(tmp)
|
||||
|
||||
return mw.returnJson(True, 'ok', repostory_info)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
func = sys.argv[1]
|
||||
if func == 'status':
|
||||
print(status())
|
||||
elif func == 'start':
|
||||
print(start())
|
||||
elif func == 'stop':
|
||||
print(stop())
|
||||
elif func == 'restart':
|
||||
print(restart())
|
||||
elif func == 'reload':
|
||||
print(reload())
|
||||
elif func == 'initd_status':
|
||||
print(initdStatus())
|
||||
elif func == 'initd_install':
|
||||
print(initdInstall())
|
||||
elif func == 'initd_uninstall':
|
||||
print(initdUinstall())
|
||||
elif func == 'conf':
|
||||
print(getConf())
|
||||
elif func == 'con_list':
|
||||
print(conListData())
|
||||
elif func == 'docker_con_log':
|
||||
print(dockerLogCon())
|
||||
elif func == 'docker_remove_con':
|
||||
print(dockerRemoveCon())
|
||||
elif func == 'docker_run_con':
|
||||
print(dockerRunCon())
|
||||
elif func == 'docker_stop_con':
|
||||
print(dockerStopCon())
|
||||
elif func == 'docker_exec':
|
||||
print(dockerExec())
|
||||
elif func == 'docker_pull':
|
||||
print(dockerPull())
|
||||
elif func == 'docker_pull_reg':
|
||||
print(dockerPullReg())
|
||||
elif func == 'image_list':
|
||||
print(imageListData())
|
||||
elif func == 'get_docker_create_info':
|
||||
print(getDockerCreateInfo())
|
||||
elif func == 'docker_create_con':
|
||||
print(dockerCreateCon())
|
||||
elif func == 'docker_remove_image':
|
||||
print(dockerRemoveImage())
|
||||
elif func == 'docker_login':
|
||||
print(dockerLogin())
|
||||
elif func == 'docker_logout':
|
||||
print(dockerLogout())
|
||||
elif func == 'repo_list':
|
||||
print(repoList())
|
||||
else:
|
||||
print('error')
|
||||
Executable
+19
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"sort": 7,
|
||||
"ps": "Docker 是一个开源的应用容器引擎(开发测试中)",
|
||||
"name": "docker",
|
||||
"title": "Docker",
|
||||
"shell": "install.sh",
|
||||
"versions":["1.0"],
|
||||
"updates":["1.0"],
|
||||
"tip": "soft",
|
||||
"checks": "server/docker",
|
||||
"path": "server/docker",
|
||||
"display": 1,
|
||||
"author": "Zend",
|
||||
"date": "2017-04-01",
|
||||
"home": "https://docker.io",
|
||||
"doc1":"https://docker-py.readthedocs.io/",
|
||||
"type": 0,
|
||||
"pid": "2"
|
||||
}
|
||||
Executable
+84
@@ -0,0 +1,84 @@
|
||||
#!/bin/bash
|
||||
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
|
||||
export PATH
|
||||
|
||||
curPath=`pwd`
|
||||
rootPath=$(dirname "$curPath")
|
||||
rootPath=$(dirname "$rootPath")
|
||||
serverPath=$(dirname "$rootPath")
|
||||
|
||||
# cd /www/server/mdserver-web/plugins/docker && /bin/bash install.sh uninstall 1.0
|
||||
# cd /www/server/mdserver-web/plugins/docker && /bin/bash install.sh install 1.0
|
||||
|
||||
install_tmp=${rootPath}/tmp/mw_install.pl
|
||||
VERSION=$2
|
||||
|
||||
if [ -f ${rootPath}/bin/activate ];then
|
||||
source ${rootPath}/bin/activate
|
||||
fi
|
||||
|
||||
Install_Docker()
|
||||
{
|
||||
# which docker
|
||||
# if [ "$?" == "0" ];then
|
||||
# echo '安装已经完成docker' > $install_tmp
|
||||
# exit 0
|
||||
# fi
|
||||
|
||||
echo '正在安装脚本文件...' > $install_tmp
|
||||
mkdir -p $serverPath/source
|
||||
|
||||
if [ ! -d $serverPath/docker ];then
|
||||
curl -fsSL https://get.docker.com | bash
|
||||
mkdir -p $serverPath/docker
|
||||
fi
|
||||
|
||||
pip install docker
|
||||
pip install pytz
|
||||
|
||||
if [ -d $serverPath/docker ];then
|
||||
echo "${VERSION}" > $serverPath/docker/version.pl
|
||||
echo '安装完成' > $install_tmp
|
||||
|
||||
cd ${rootPath} && python3 ${rootPath}/plugins/docker/index.py start
|
||||
cd ${rootPath} && python3 ${rootPath}/plugins/docker/index.py initd_install
|
||||
fi
|
||||
}
|
||||
|
||||
Uninstall_Docker()
|
||||
{
|
||||
CMD=yum
|
||||
which apt
|
||||
if [ "$?" == "0" ];then
|
||||
CMD=apt
|
||||
fi
|
||||
|
||||
if [ -f /usr/lib/systemd/system/docker.service ];then
|
||||
systemctl stop docker
|
||||
systemctl disable docker
|
||||
rm -rf /usr/lib/systemd/system/docker.service
|
||||
systemctl daemon-reload
|
||||
fi
|
||||
|
||||
$CMD remove -y docker docker-ce-cli containerd.io
|
||||
# docker-client \
|
||||
# docker-client-latest \
|
||||
# docker-common \
|
||||
# docker-latest \
|
||||
# docker-latest-logrotate \
|
||||
# docker-logrotate \
|
||||
# docker-selinux \
|
||||
# docker-engine-selinux \
|
||||
# docker-engine \
|
||||
# docker-ce
|
||||
|
||||
rm -rf $serverPath/docker
|
||||
echo "Uninstall_Docker" > $install_tmp
|
||||
}
|
||||
|
||||
action=$1
|
||||
if [ "${1}" == 'install' ];then
|
||||
Install_Docker
|
||||
else
|
||||
Uninstall_Docker
|
||||
fi
|
||||
Executable
+783
@@ -0,0 +1,783 @@
|
||||
function dPost(method, version, args,callback){
|
||||
var loadT = layer.msg('正在获取...', { icon: 16, time: 0, shade: 0.3 });
|
||||
|
||||
var req_data = {};
|
||||
req_data['name'] = 'docker';
|
||||
req_data['func'] = method;
|
||||
req_data['version'] = version;
|
||||
|
||||
if (typeof(args) == 'string'){
|
||||
req_data['args'] = JSON.stringify(toArrayObject(args));
|
||||
} else {
|
||||
req_data['args'] = JSON.stringify(args);
|
||||
}
|
||||
|
||||
$.post('/plugins/run', req_data, function(data) {
|
||||
layer.close(loadT);
|
||||
if (!data.status){
|
||||
//错误展示10S
|
||||
layer.msg(data.msg,{icon:0,time:2000,shade: [10, '#000']});
|
||||
return;
|
||||
}
|
||||
|
||||
if(typeof(callback) == 'function'){
|
||||
callback(data);
|
||||
}
|
||||
},'json');
|
||||
}
|
||||
|
||||
function dPostCallbak(method, version, args,callback){
|
||||
var loadT = layer.msg('正在获取...', { icon: 16, time: 0, shade: 0.3 });
|
||||
|
||||
var req_data = {};
|
||||
req_data['name'] = 'docker';
|
||||
req_data['func'] = method;
|
||||
args['version'] = version;
|
||||
|
||||
if (typeof(args) == 'string'){
|
||||
req_data['args'] = JSON.stringify(toArrayObject(args));
|
||||
} else {
|
||||
req_data['args'] = JSON.stringify(args);
|
||||
}
|
||||
|
||||
$.post('/plugins/callback', req_data, function(data) {
|
||||
layer.close(loadT);
|
||||
if (!data.status){
|
||||
layer.msg(data.msg,{icon:0,time:2000,shade: [0.3, '#000']});
|
||||
return;
|
||||
}
|
||||
|
||||
if(typeof(callback) == 'function'){
|
||||
callback(data);
|
||||
}
|
||||
},'json');
|
||||
}
|
||||
|
||||
|
||||
function logsCon(id){
|
||||
dPost('docker_con_log','',{Hostname:id},function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
if(!rdata.status) {
|
||||
layer.msg(rdata.msg,{icon:2});
|
||||
return;
|
||||
};
|
||||
layer.open({
|
||||
type:1,
|
||||
title:'Docker日志',
|
||||
area: '600px',
|
||||
closeBtn: 2,
|
||||
content:'<div class="bt-form">'
|
||||
+'<pre class="crontab-log" style="overflow: auto; \
|
||||
border: 0px none; line-height:23px;padding: 15px; \
|
||||
margin: 0px; white-space: pre-wrap; height: 405px; \
|
||||
background-color: rgb(51,51,51);color:#f1f1f1;\
|
||||
border-radius:0px;">'+ (rdata.msg == '' ? 'No logs':rdata.msg) +'</pre>'
|
||||
+'</div>',
|
||||
success:function(index,layers){
|
||||
$(".crontab-log").scrollTop(1000000);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function deleteCon(Hostname){
|
||||
// 删除容器
|
||||
safeMessage('删除容器 ', '删除容器 ['+Hostname+'], 确定?',function(){
|
||||
dPost('docker_remove_con','',{Hostname:Hostname},function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
showMsg(rdata.msg,function(){
|
||||
if(rdata.status) {
|
||||
dockerConListRender();
|
||||
}
|
||||
},{icon:rdata.status?1:2});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function startCon(Hostname){
|
||||
dPost('docker_run_con','',{Hostname:Hostname},function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
showMsg(rdata.msg,function(){
|
||||
if(rdata.status) {
|
||||
dockerConListRender();
|
||||
}
|
||||
},{icon:rdata.status?1:2});
|
||||
});
|
||||
}
|
||||
|
||||
function stopCon(Hostname){
|
||||
dPost('docker_stop_con','',{Hostname:Hostname},function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
showMsg(rdata.msg,function(){
|
||||
if(rdata.status) {
|
||||
dockerConListRender();
|
||||
}
|
||||
},{icon:rdata.status?1:2});
|
||||
});
|
||||
}
|
||||
|
||||
function execCon(Hostname){
|
||||
webShell();
|
||||
var pdata_socket = {};
|
||||
var shell = setInterval(function(){
|
||||
if($('.term-box').length == 0){
|
||||
pdata_socket['data'] = 'exit\n';
|
||||
socket.emit('webssh',pdata_socket);
|
||||
setTimeout(function(){socket.emit('webssh',pdata_socket['data']);},1000);
|
||||
clearInterval(shell);
|
||||
}
|
||||
},500);
|
||||
setTimeout(function(){
|
||||
dPost('docker_exec','',{Hostname:Hostname},function(res){
|
||||
var res = $.parseJSON(res.data);
|
||||
if(!res.status){
|
||||
layer.msg(res.msg,{icon:res.status?1:2});
|
||||
}else{
|
||||
pdata_socket['data'] = 'clear && ' + res.msg +'\n'
|
||||
socket.emit('webssh',pdata_socket);
|
||||
setTimeout(function(){socket.emit('webssh',pdata_socket['data']);},1000);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function dockerConListRender(){
|
||||
dPost('con_list', '', {}, function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
console.log(rdata);
|
||||
if (!rdata.status){
|
||||
layer.msg(rdata.msg,{icon:2,time:2000});
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
var list = '';
|
||||
var rlist = rdata.data;
|
||||
|
||||
for (var i = 0; i < rlist.length; i++) {
|
||||
var docker_status = 'stop';
|
||||
var status = '<span class="glyphicon glyphicon-pause" style="color:red;font-size:12px"></span>';
|
||||
if (rlist[i]['State']['Status'] == 'running'){
|
||||
docker_status = 'start';
|
||||
status = '<span class="glyphicon glyphicon-play" style="color:#20a53a;font-size:12px"></span>';
|
||||
}
|
||||
|
||||
var op = '';
|
||||
op += '<a href="javascript:;" onclick="execCon(\''+rlist[i]['Config']['Hostname']+'\')" class="btlink">终端</a> | ';
|
||||
op += '<a href="javascript:;" onclick="logsCon(\''+rlist[i]['Id']+'\')" class="btlink">日志</a> | ';
|
||||
op += '<a href="javascript:;" onclick="deleteCon(\''+rlist[i]['Config']['Hostname']+'\')" class="btlink">删除</a>';
|
||||
|
||||
list += '<tr>';
|
||||
list += '<td>'+rlist[i]['Name'].substring(1)+'</td>';
|
||||
list += '<td>'+rlist[i]['Config']['Image']+'</td>';
|
||||
list += '<td>'+getFormatTime(rlist[i]['Created'])+'</td>';
|
||||
|
||||
|
||||
if (docker_status == 'start'){
|
||||
list += '<td style="cursor:pointer;" align="center" onclick="stopCon(\''+rlist[i]['Config']['Hostname']+'\')">'+status+'</td>';
|
||||
} else{
|
||||
list += '<td style="cursor:pointer;" align="center" onclick="startCon(\''+rlist[i]['Config']['Hostname']+'\')">'+status+'</td>';
|
||||
}
|
||||
list += '<td class="text-right">'+op+'</td>';
|
||||
list += '</tr>';
|
||||
}
|
||||
|
||||
$('#con_list tbody').html(list);
|
||||
});
|
||||
}
|
||||
|
||||
function createConTemplate(){
|
||||
|
||||
dPost('get_docker_create_info','',{},function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
console.log(rdata);
|
||||
var rdata = rdata.data;
|
||||
var imageOpt = '';
|
||||
for(var i=0;i<rdata.images.length;i++){
|
||||
var imageName = rdata.images[i].RepoTags.indexOf('panel') == -1? rdata.images[i].RepoTags:'aaPanel:'+rdata.images[i].RepoTags.split(':')[1];
|
||||
imageOpt += '<option value="'+rdata.images[i].RepoTags+'">'+imageName+'</option>';
|
||||
}
|
||||
var iplistOpt = '';
|
||||
for(var i=0;i<rdata.iplist.length;i++){
|
||||
iplistOpt += '<option value="'+rdata.iplist[i].address+'">'+rdata.iplist[i].address+'</option>';
|
||||
}
|
||||
|
||||
var layer_index = layer.open({
|
||||
type: 1,
|
||||
title: "创建容器",
|
||||
area: '556',
|
||||
closeBtn: 2,
|
||||
shadeClose: false,
|
||||
btn: ['确定', '取消'],
|
||||
content: '<div class="bt-form pd20 pb70 ceart-docker new_tname">\
|
||||
<div class="line">\
|
||||
<span class="tname">镜像</span>\
|
||||
<div class="info-r c4"><select class="bt-input-text docker-image" style="width:330px">'+imageOpt+'</select></div>\
|
||||
</div>\
|
||||
<div class="line">\
|
||||
<span class="tname">绑定IP</span>\
|
||||
<div class="info-r c4"><select class="bt-input-text docker-address" style="width:330px"><option value="0.0.0.0">0.0.0.0</optin>'+iplistOpt+'</select></div>\
|
||||
</div>\
|
||||
<div class="line">\
|
||||
<span class="tname">端口映射</span>\
|
||||
<div class="info-r c4">\
|
||||
<div class="type-port">\
|
||||
<input class="bt-input-text" name="name1" type="number" placeholder="容器端口" style="width:110px;margin-right:15px">\
|
||||
<select class="bt-input-text" style="width:90px;margin-right:15px"><option value="TCP">TCP</optin><option value="UDP">UDP</optin></select>\
|
||||
<input class="bt-input-text" name="name2" type="number" placeholder="服务器端口" style="width:90px">\
|
||||
<span class="plus glyphicon glyphicon-plus" style="color: #20a53a;font-size: 11px;"></span>\
|
||||
</div>\
|
||||
<div class="divtable" style="max-height:100px;overflow:auto; margin-top:15px;width:330px;padding-left: 0px;">\
|
||||
<table class="table table-hover">\
|
||||
<tbody id="portabletr"><tr class="more1"><td>当前未添加端口映射</td></tr></tbody>\
|
||||
</table>\
|
||||
</div>\
|
||||
</div>\
|
||||
</div>\
|
||||
<div class="line">\
|
||||
<span class="tname">目录映射</span>\
|
||||
<div class="info-r c4">\
|
||||
<div class="type-volumes">\
|
||||
<input class="bt-input-text" name="path1" type="text" placeholder="容器目录" style="width:110px;margin-right:15px">\
|
||||
<select class="bt-input-text" style="width:90px;margin-right:15px"><option value="rw">read-write</optin><option value="ro">read only</optin></select>\
|
||||
<input class="bt-input-text" name="path2" type="text" placeholder="服务器目录" style="width:90px">\
|
||||
<span class="plus2 glyphicon glyphicon-plus" style="color: #20a53a;font-size: 11px;"></span>\
|
||||
</div>\
|
||||
<div class="divtable" style="max-height:100px;overflow:auto; margin-top:15px;width:330px;padding-left: 0px;">\
|
||||
<table class="table table-hover">\
|
||||
<tbody id="portabletr2"><tr class="more2"><td>当前未添加目录映射</td></tr></tbody>\
|
||||
</table>\
|
||||
</div>\
|
||||
</div>\
|
||||
</div>\
|
||||
<div class="line">\
|
||||
<span class="tname" style="height: auto;line-height: 20px;">环境变量<br>(每行一个)</span>\
|
||||
<div class="info-r c4" style="margin-bottom: 0;">\
|
||||
<div class="type-volumes">\
|
||||
<textarea placeholder="Add variables format as following, one per line:\nJAVA_HOME=/usr/local/java8 HOSTNAME=master" name="environments" class="docker-environments"></textarea>\
|
||||
</div>\
|
||||
</div>\
|
||||
</div>\
|
||||
<div class="line">\
|
||||
<span class="tname">内存配额</span>\
|
||||
<div class="info-r c4"><input class="bt-input-text mr5 docker-mem" type="number" style="width:100px" value="'+parseInt(rdata.memSize/2)+'">\
|
||||
<span class="dc-un">MB</span><i class="help">不超过, '+ rdata.memSize +'MB</i></div>\
|
||||
</div>\
|
||||
<div class="line">\
|
||||
<span class="tname">CPU配额</span>\
|
||||
<div class="info-r c4">\
|
||||
<input class="bt-input-text mr5 docker-cpu" type="number" max="100" min="1" style="width:100px" value="100">\
|
||||
<span class="dc-un"></span><i class="help">越大,占用的CPU越多</i></div>\
|
||||
</div>\
|
||||
<div class="line">\
|
||||
<span class="tname">执行命令</span>\
|
||||
<div class="info-r c4"><input class="bt-input-text docker-command" type="text" style="width:330px" value="" placeholder="/bin/bash"></div>\
|
||||
</div>\
|
||||
<div class="line" style="display:none">\
|
||||
<span class="tname">entrypoint</span>\
|
||||
<div class="info-r c4"><input class="bt-input-text docker-entrypoint" type="text" style="width:300px" value=""></div>\
|
||||
</div>\
|
||||
</div>',
|
||||
success:function(){
|
||||
$(".bt-cancel").click(function(){
|
||||
layer.close(layer_index);
|
||||
});
|
||||
|
||||
|
||||
$(".plus").click(function(){
|
||||
var name1 = $(".type-port input[name='name1']").val();
|
||||
var name2 = $(".type-port input[name='name2']").val();
|
||||
if(name1 < 1 || name1 > 65535 || name2 < 1 || name2 > 65535 || isNaN(name1) || isNaN(name2)){
|
||||
layer.msg('Port setting value range is invalid, range [1-65535]',{icon:2});
|
||||
return;
|
||||
}
|
||||
|
||||
var portval = $('#portabletr')[0].childNodes;
|
||||
for(var i=0;i<portval.length;i++){
|
||||
if(portval[i].childNodes[0].innerText == '当前未添加目录映射') continue;
|
||||
var sport = portval[i].childNodes[2].innerText;
|
||||
if(name2 == sport){
|
||||
layer.msg('The port ['+name2+'] is already in the mapping list!',{icon:2});
|
||||
return;
|
||||
}
|
||||
}
|
||||
var address = $('.docker-address').val();
|
||||
if(address == '0.0.0.0'){
|
||||
address = '*';
|
||||
}
|
||||
var port = address + ':' + name2;
|
||||
var loadT = layer.msg('Testing <img src="/static/img/ing.gif">',{icon:16,time:0,shade: [0.3, "#000"]});
|
||||
$.post('/plugin?action=a&name=docker&s=IsPortExists',{port:port},function(rdata){
|
||||
layer.close(loadT);
|
||||
if(rdata !== false){
|
||||
layer.msg('Port ['+name2+'] is already in the mapping list!',{icon:2});
|
||||
return;
|
||||
}
|
||||
var selecttype = $(".type-port select").val();
|
||||
var portable= '<tr><td>'+name1+'</td><td>'+selecttype+'</td><td>'+name2+'</td><td class="text-right" width="60"><a href="javascript:;" class="btlink minus">Del</a></td></tr>';
|
||||
$("#portabletr").append(portable);
|
||||
$(".more1").remove();
|
||||
$(".minus").click(function(){
|
||||
$(this).parents("tr").remove();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
$(".plus2").click(function(){
|
||||
var path1 = $(".type-volumes input[name='path1']").val();
|
||||
var path2 = $(".type-volumes input[name='path2']").val();
|
||||
|
||||
var notPath = ['/boot','/bin','/sbin','/etc','/usr/bin','/usr/sbin','/dev']
|
||||
if($.inArray(path2,notPath) != -1){
|
||||
layer.msg('Cannot map' + path2,{icon:2});
|
||||
return;
|
||||
}
|
||||
var portval = $('#portabletr2')[0].childNodes;
|
||||
for(var i=0;i<portval.length;i++){
|
||||
if(portval[i].childNodes[0].innerText == '当前未添加目录映射') continue;
|
||||
var sport = portval[i].childNodes[2].innerText;
|
||||
if(path2 == sport){
|
||||
layer.msg('Directory ['+path2+'] is already in the mapping list!',{icon:2});
|
||||
return;
|
||||
}
|
||||
}
|
||||
var selecttype = $(".type-volumes select").val();
|
||||
var portable= '<tr>\
|
||||
<td class="td_width_1" title="'+path1+'">'+path1+'</td>\
|
||||
<td>'+selecttype+'</td><td title="'+path2+'" class="td_width_1" style="max-width: 138px;">'+path2+'</td>\
|
||||
<td class="text-right" width="50"><a href="javascript:;" class="btlink minus2">Del</a></td>\
|
||||
</tr>';
|
||||
$("#portabletr2").append(portable);
|
||||
$(".more2").remove();
|
||||
$(".minus2").click(function(){
|
||||
$(this).parents("tr").remove();
|
||||
});
|
||||
});
|
||||
},
|
||||
yes:function(layero,layer_id){
|
||||
var ports = {};
|
||||
var volumes = {};
|
||||
var portval = $('#portabletr')[0].childNodes;
|
||||
var address = $('.docker-address').val();
|
||||
var portval2 = $('#portabletr2')[0].childNodes;
|
||||
var command = $('.docker-command').val()
|
||||
var entrypoint = $('.docker-entrypoint').val()
|
||||
var accept = [];
|
||||
|
||||
//遍历端口映射
|
||||
for(var i=0;i<portval.length;i++){
|
||||
// console.log(portval[i].childNodes[0].innerText);
|
||||
if(portval[i].childNodes[0].innerText == '当前未添加端口映射') {
|
||||
continue;
|
||||
}
|
||||
var port = portval[i].childNodes[0].innerText.replace(/\s/g,'');
|
||||
var dport = port + '/' + portval[i].childNodes[1].innerText.toLowerCase().replace(/\s/g,'');
|
||||
var sport = [address,parseInt(portval[i].childNodes[2].innerText.replace(/\s/g,''))];
|
||||
ports[dport] = sport
|
||||
accept.push(port);
|
||||
}
|
||||
|
||||
//遍历目录映射
|
||||
volumes['/sys/fs/cgroup'] = {'bind':'/sys/fs/cgroup', 'mode': 'rw'};
|
||||
for(var i=0;i<portval2.length;i++){
|
||||
if(portval2[i].childNodes[0].innerText.replace(/\s/g,' ') == '当前未添加目录映射') {
|
||||
continue;
|
||||
}
|
||||
var dpath = portval2[i].childNodes[2].innerText.replace(/\s/g,'');
|
||||
var spath = {'bind':portval2[i].childNodes[0].innerText.replace(/\s/g,''),'mode':portval2[i].childNodes[1].innerText.toLowerCase().replace(/\s/g,'')};
|
||||
volumes[dpath] = spath
|
||||
}
|
||||
|
||||
var data = {
|
||||
image:$('.docker-image').val(),
|
||||
ports:JSON.stringify(ports),
|
||||
accept:JSON.stringify(accept),
|
||||
volumes:JSON.stringify(volumes),
|
||||
environments:$('.docker-environments').val(),
|
||||
mem_limit:$('.docker-mem').val(),
|
||||
cpu_shares:$('.docker-cpu').val(),
|
||||
command:command,
|
||||
entrypoint:entrypoint
|
||||
}
|
||||
|
||||
if(data.mem_limit > rdata.memSize){
|
||||
layer.msg('内存配额不能大于物理内存 ['+rdata.memSize+']!',{icon:2});
|
||||
return;
|
||||
}
|
||||
|
||||
if(data.cpu_shares > 100 || data.cpu_shares < 1){
|
||||
layer.msg('CPU配额设置值范围应为 [1-100]!',{icon:2});
|
||||
return;
|
||||
}
|
||||
dPost('docker_create_con','', data, function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
showMsg(rdata.msg,function(){
|
||||
if(rdata.status) {
|
||||
layer.close(layer_index);
|
||||
dockerConListRender();
|
||||
}
|
||||
},{ icon: rdata.status ? 1 : 2 });
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
function dockerConList(){
|
||||
|
||||
var con = '<div class="safe bgw">\
|
||||
<button onclick="createConTemplate();" class="btn btn-success btn-sm" type="button" style="margin-right: 5px;">创建容器</button>\
|
||||
<div class="divtable mtb10">\
|
||||
<div class="tablescroll">\
|
||||
<table id="con_list" class="table table-hover" width="100%" cellspacing="0" cellpadding="0" border="0" style="border: 0 none;">\
|
||||
<thead><tr>\
|
||||
<th>名称</th>\
|
||||
<th>镜像</th>\
|
||||
<th>创建时间</th>\
|
||||
<th>状态</th>\
|
||||
<th style="text-align:right;">操作</th></tr></thead>\
|
||||
<tbody></tbody></table>\
|
||||
</div>\
|
||||
</div>\
|
||||
</div>';
|
||||
|
||||
$(".soft-man-con").html(con);
|
||||
dockerConListRender();
|
||||
}
|
||||
|
||||
function deleteImages(tag, id){
|
||||
safeMessage('删除镜像','删除镜像['+tag+'],确定?',function(){
|
||||
dPost('docker_remove_image','', {imageId:id,repoTags:tag},function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
showMsg(rdata.msg,function(){
|
||||
if(rdata.status) {
|
||||
dockerImageListRender();
|
||||
}
|
||||
},{ icon: rdata.status ? 1 : 2 });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function pullImages(tag, id){
|
||||
console.log(tag, id);
|
||||
layer.msg('开发中!',{ icon: 2 });
|
||||
}
|
||||
|
||||
function dockerImageListRender(){
|
||||
dPost('image_list', '', {}, function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
console.log(rdata);
|
||||
if (!rdata.status){
|
||||
layer.msg(rdata.msg,{icon:2,time:2000});
|
||||
return;
|
||||
}
|
||||
|
||||
var list = '';
|
||||
var rlist = rdata.data;
|
||||
|
||||
for (var i = 0; i < rlist.length; i++) {
|
||||
|
||||
var tag = rlist[i]['RepoTags'].split(":")[1];
|
||||
|
||||
var license = 'null';
|
||||
var desc = 'null';
|
||||
if (rlist[i]['Labels'] == null){
|
||||
license = 'free';
|
||||
}
|
||||
|
||||
var op = '';
|
||||
op += '<a href="javascript:;" onclick="pullImages(\''+rlist[i]['RepoTags']+'\',\''+rlist[i]['Id']+'\')" class="btlink">拉取</a> | ';
|
||||
op += '<a href="javascript:;" onclick="deleteImages(\''+rlist[i]['RepoTags']+'\',\''+rlist[i]['Id']+'\')" class="btlink">删除</a>';
|
||||
|
||||
list += '<tr>';
|
||||
list += '<td>'+rlist[i]['RepoTags']+'</td>';
|
||||
list += '<td>'+tag+'</td>';
|
||||
list += '<td>'+toSize(rlist[i]['Size'])+'</td>';
|
||||
list += '<td>'+license+'</td>';
|
||||
list += '<td>'+desc+'</td>';
|
||||
list += '<td class="text-right">'+op+'</td>';
|
||||
list += '</tr>';
|
||||
}
|
||||
|
||||
$('#con_list tbody').html(list);
|
||||
});
|
||||
}
|
||||
|
||||
function dockerPullImagesFileTemplate(){
|
||||
// 拉取镜像文件模板
|
||||
var layer_index = layer.open({
|
||||
type: 1,
|
||||
title: "获取镜像",
|
||||
area: '500px',
|
||||
closeBtn: 2,
|
||||
shadeClose: false,
|
||||
content: '<div class="bt-docker pd20">'+
|
||||
'<div class="docker-sub">'+
|
||||
'<span class="on">官方库</span>'+
|
||||
'<span>公共库</span>'+
|
||||
'<span>私有库</span>'+
|
||||
'</div>'+
|
||||
'<div class="bt-form bt-docker-con">'+
|
||||
'<div class="conter official_pull pd15"><div class="line">'+
|
||||
'<span class="tname">镜像名:</span>\
|
||||
<div class="info-r c4">\
|
||||
<input class="bt-input-text mr5" type="text" name="official_pull_name" style="width:218px" value="">\
|
||||
<button type="button" class="btn btn-sm btn-success official_pull_btn">获取</button>\
|
||||
</div>'+
|
||||
'</div></div>'+
|
||||
'<div class="conter public_pull pd15" style="display: none;"><div class="line">'+
|
||||
'<span class="tname">镜像名:</span>\
|
||||
<div class="info-r c4">\
|
||||
<input class="bt-input-text mr5" type="text" name="public_pull_path" style="width:218px" value="">\
|
||||
<button type="button" class="btn btn-sm btn-success public_pull_btn">获取</button>\
|
||||
</div>'+
|
||||
'</div></div>'+
|
||||
'<div class="conter private_pull pd15" style="display: none;">'+
|
||||
'<div class="line"><span class="tname">镜像地址:</span>\
|
||||
<div class="info-r c4">\
|
||||
<input class="bt-input-text mr5" type="text" name="private_pull_path" style="width:218px" value="">\
|
||||
<button type="button" class="btn btn-sm btn-success private_pull_btn">获取</button>\
|
||||
</div>\
|
||||
</div>\
|
||||
</div>\
|
||||
</div>\
|
||||
</div>',
|
||||
success:function(layero,layer_id){
|
||||
|
||||
$('.docker-sub span').click(function(){
|
||||
var index = $(this).index();
|
||||
$(this).addClass('on').siblings().removeClass('on');
|
||||
$(this).parent().next().find('.conter').eq(index).show().siblings().hide();
|
||||
});
|
||||
|
||||
$('.official_pull_btn').click(function(){
|
||||
var name = $('[name="official_pull_name"]').val();
|
||||
if(name == ''){
|
||||
layer.msg('镜像名不能为空!');
|
||||
return;
|
||||
}
|
||||
dPost('docker_pull','',{images:name}, function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
showMsg(rdata.msg,function(){
|
||||
if(rdata.status) {
|
||||
layer.close(layer_index);
|
||||
dockerImageListRender();
|
||||
|
||||
}
|
||||
},{ icon: rdata.status ? 1 : 2 });
|
||||
});
|
||||
});
|
||||
|
||||
$('.public_pull_btn').click(function(){
|
||||
var path = $('[name="public_pull_path"]').val();
|
||||
if(path == ''){
|
||||
layer.msg('公共网络镜像地址不能为空。');
|
||||
return;
|
||||
}
|
||||
|
||||
dPost('docker_pull_reg','',{path:path}, function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
showMsg(rdata.msg,function(){
|
||||
if(rdata.status) {
|
||||
layer.close(layer_index);
|
||||
dockerImageListRender();
|
||||
}
|
||||
},{ icon: rdata.status ? 1 : 2 });
|
||||
});
|
||||
});
|
||||
$('.private_pull_btn').click(function(){
|
||||
var path = $('[name="private_pull_path"]').val();
|
||||
if(path == ''){
|
||||
layer.msg('专用镜像地址不能为空!');
|
||||
return
|
||||
}
|
||||
|
||||
dPost('docker_pull_private_new','',{path:path}, function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
showMsg(rdata.msg,function(){
|
||||
if(rdata.status) {
|
||||
layer.close(layer_index);
|
||||
dockerImageListRender();
|
||||
}
|
||||
},{ icon: rdata.status ? 1 : 2 });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
function dockerImageList(){
|
||||
|
||||
var con = '<div class="safe bgw">\
|
||||
<button onclick="dockerPullImagesFileTemplate()" class="btn btn-success btn-sm" type="button" style="margin-right: 5px;">获取镜像</button>\
|
||||
<div class="divtable mtb10">\
|
||||
<div class="tablescroll">\
|
||||
<table id="con_list" class="table table-hover" width="100%" cellspacing="0" cellpadding="0" border="0" style="border: 0 none;">\
|
||||
<thead><tr>\
|
||||
<th>名称</th>\
|
||||
<th>版本</th>\
|
||||
<th>大小</th>\
|
||||
<th>证书</th>\
|
||||
<th>描述</th>\
|
||||
<th style="text-align:right;">操作</th></tr></thead>\
|
||||
<tbody></tbody></table>\
|
||||
</div>\
|
||||
<div id="databasePage" class="dataTables_paginate paging_bootstrap page"></div>\
|
||||
</div>\
|
||||
</div>';
|
||||
|
||||
$(".soft-man-con").html(con);
|
||||
|
||||
dockerImageListRender();
|
||||
}
|
||||
|
||||
// login
|
||||
function repoLogin(){
|
||||
var _option1= "";
|
||||
var obj = {hub_name: "", namespace: "",name: "", registry: "", user_pass: "", user_name: "",arry: ['Docker Repository','Other Repository']};
|
||||
for(var i = 0; i< obj.arry.length;i++){
|
||||
_option1 += '<option value="'+ obj.arry[i] +'">'+ obj.arry[i] +'</option>';
|
||||
}
|
||||
var layer_index = layer.open({
|
||||
type: 1,
|
||||
title: "登录到存储库",
|
||||
area: '450px',
|
||||
closeBtn: 2,
|
||||
shadeClose: false,
|
||||
content: '<div class="bt-docker-con docker_content">'+
|
||||
'<style>.line .tname{width:120px;}</style>'+
|
||||
'<div class="soft-man-con pd20 pb70 private_pull">'+
|
||||
'<div class="line"><span class="tname">Repository Type</span><div class="info-r c4"><select class="bt-input-text mr5 project_version" name="dtype" style="width:250px">'+ _option1 +'</select></div></div>'+
|
||||
'<div class="line"><span class="tname">Name:</span><div class="info-r"><input class="bt-input-text" type="text" name="ctm_name" style="width:250px" value="'+obj.name+'"></div></div>'+
|
||||
'<div class="line"><span class="tname">Username:</span><div class="info-r"><input class="bt-input-text" type="text" name="user" style="width:250px" value="'+obj.user_name+'"></div></div>'+
|
||||
'<div class="line"><span class="tname">Password:</span><div class="info-r"><input class="bt-input-text" type="password" name="passwd" style="width:250px" value="'+obj.user_pass+'"></div></div>'+
|
||||
'<div class="line"><span class="tname">Repository Name:</span><div class="info-r"><input class="bt-input-text" type="text" name="hub_name" style="width:250px" value="'+obj.hub_name+'"></div></div>'+
|
||||
'<div class="line"><span class="tname">Namespaces:</span><div class="info-r"><input class="bt-input-text" type="text" name="namespace" style="width:250px" value="'+obj.namespace+'"></div></div>'+
|
||||
'<div class="line" style="display:none"><span class="tname">Registry:</span><div class="info-r"><input class="bt-input-text" type="text" name="registry" style="width:250px" value="'+obj.registry+'"></div></div>'+
|
||||
'<div class="bt-form-submit-btn"><button type="button" class="btn btn-sm btn-success login_aliyun">登录</button></div>'+
|
||||
'</div>'+
|
||||
'</div>',
|
||||
success:function(){
|
||||
$('[name="dtype"]').change(function(e){
|
||||
var docker_type = $(this).val();
|
||||
if(docker_type == 'Other Repository'){
|
||||
$('.docker_content .line').show();
|
||||
}else{
|
||||
$('.docker_content .line').filter(":lt(3)").show().end().filter(":gt(4)").hide();
|
||||
}
|
||||
});
|
||||
$('.login_aliyun').click(function(){
|
||||
var user = $('[name="user"]').val(),
|
||||
passwd = $('[name="passwd"]').val(),
|
||||
registry = $('[name="registry"]').val(),
|
||||
name = $('[name="ctm_name"]').val(),
|
||||
hub_name = $('[name="hub_name"]').val(),
|
||||
namespace = $('[name="namespace"]').val();
|
||||
|
||||
var args = {
|
||||
user:user,
|
||||
passwd:passwd,
|
||||
registry:'',
|
||||
repository_name:name,
|
||||
hub_name:hub_name,
|
||||
namespace:namespace
|
||||
};
|
||||
if($('[name="dtype"]').val() == 'Docker Repository'){
|
||||
args.registry = '';
|
||||
}else{
|
||||
args.registry = registry;
|
||||
}
|
||||
|
||||
console.log(obj);
|
||||
dPost('docker_login', '', args, function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
console.log(rdata);
|
||||
layer.msg(rdata.msg,{icon:rdata.status?1:2});
|
||||
if(res.status){
|
||||
repoListRender();
|
||||
layer.close(layer_index);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
|
||||
function delRepo(address){
|
||||
safeMessage('退出','你将退出 ['+address+'],确定?',function(){
|
||||
dPost('docker_logout', '',
|
||||
{registry:address},
|
||||
function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
layer.msg(rdata.msg,{icon:rdata.status?1:2});
|
||||
if(rdata.status) {
|
||||
repoListRender();
|
||||
}
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function repoListRender(){
|
||||
dPost('repo_list', '', {}, function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
console.log(rdata);
|
||||
if (!rdata.status){
|
||||
layer.msg(rdata.msg,{icon:2,time:2000});
|
||||
return;
|
||||
}
|
||||
|
||||
var list = '';
|
||||
var rlist = rdata.data;
|
||||
|
||||
for (var i = 0; i < rlist.length; i++) {
|
||||
|
||||
list += '<tr>';
|
||||
list += '<td>'+rlist[i]['hub_name']+'</td>';
|
||||
list += '<td>'+rlist[i]['repository_name']+'</td>';
|
||||
list += '<td>'+rlist[i]['namespace']+'</td>';
|
||||
list += '<td>'+rlist[i]['registry']+'</td>';
|
||||
list += '<td class="text-right"><a href="javascript:;" onclick="delRepo(\''+rlist[i]['registry']+'\')" class="btlink">删除</a></td>';
|
||||
list += '</tr>';
|
||||
}
|
||||
|
||||
$('#con_list tbody').html(list);
|
||||
});
|
||||
}
|
||||
function repoList(){
|
||||
|
||||
var con = '<div class="safe bgw">\
|
||||
<button id="docker_login" title="" class="btn btn-success btn-sm" type="button" style="margin-right: 5px;">登录</button>\
|
||||
<div class="divtable mtb10">\
|
||||
<div class="tablescroll">\
|
||||
<table id="con_list" class="table table-hover" width="100%" cellspacing="0" cellpadding="0" border="0" style="border: 0 none;">\
|
||||
<thead><tr>\
|
||||
<th>Name</th>\
|
||||
<th>Repository Name</th>\
|
||||
<th>NameSpace</th>\
|
||||
<th>地址</th>\
|
||||
<th style="text-align:right;">操作</th></tr></thead>\
|
||||
<tbody>\
|
||||
' + '</tbody></table>\
|
||||
</div>\
|
||||
<div id="databasePage" class="dataTables_paginate paging_bootstrap page"></div>\
|
||||
</div>\
|
||||
</div>';
|
||||
|
||||
$(".soft-man-con").html(con);
|
||||
|
||||
//login
|
||||
$('#docker_login').click(function(){
|
||||
repoLogin();
|
||||
});
|
||||
|
||||
repoListRender();
|
||||
}
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ max_connections = 500
|
||||
max_connect_errors = 100
|
||||
open_files_limit = 65535
|
||||
|
||||
skip-name-resolve=1
|
||||
skip_name_resolve=1
|
||||
#skip-grant-tables
|
||||
#skip-networking
|
||||
#skip-external-locking
|
||||
|
||||
@@ -41,7 +41,7 @@ max_connections = 500
|
||||
max_connect_errors = 100
|
||||
open_files_limit = 65535
|
||||
|
||||
skip-name-resolve=1
|
||||
skip_name_resolve=1
|
||||
#skip-grant-tables
|
||||
#skip-networking
|
||||
#skip-external-locking
|
||||
|
||||
@@ -17,6 +17,7 @@ datadir = {$SERVER_APP_PATH}/data
|
||||
log-error = {$SERVER_APP_PATH}/data/error.log
|
||||
server-id = {$SERVER_ID}
|
||||
|
||||
explicit_defaults_for_timestamp=true
|
||||
default_storage_engine = InnoDB
|
||||
|
||||
|
||||
@@ -40,7 +41,7 @@ max_connect_errors = 100
|
||||
open_files_limit = 2560
|
||||
max_allowed_packet = 128M
|
||||
|
||||
skip_name_resolve = 1
|
||||
skip_name_resolve=1
|
||||
skip-ssl
|
||||
#skip-networking
|
||||
#skip-external-locking
|
||||
@@ -95,7 +96,7 @@ innodb_file_per_table = 1
|
||||
innodb_large_prefix = 1
|
||||
|
||||
secure-file-priv={$SERVER_APP_PATH}/tmp
|
||||
|
||||
#secure-file-priv=disabled
|
||||
[mysqldump]
|
||||
quick
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ max_connect_errors = 100
|
||||
open_files_limit = 2560
|
||||
max_allowed_packet = 128M
|
||||
|
||||
skip_name_resolve = 1
|
||||
skip_name_resolve=1
|
||||
#skip-networking
|
||||
#skip-external-locking
|
||||
#loose-skip-innodb
|
||||
|
||||
@@ -383,7 +383,7 @@ def initMysql57Data():
|
||||
myconf = serverdir + "/etc/my.cnf"
|
||||
user = pGetDbUser()
|
||||
cmd = 'cd ' + serverdir + ' && ./bin/mysqld --defaults-file=' + myconf + \
|
||||
' --initialize-insecure --explicit_defaults_for_timestamp'
|
||||
' --initialize-insecure --explicit_defaults_for_timestamp --user=mysql'
|
||||
data = mw.execShell(cmd)
|
||||
# print(data)
|
||||
return False
|
||||
|
||||
@@ -181,7 +181,7 @@ function changeMySQLDataPath(act) {
|
||||
$.post('/database?action=GetMySQLInfo', '', function(rdata) {
|
||||
var LimitCon = '<p class="conf_p">\
|
||||
<input id="datadir" class="phpUploadLimit bt-input-text mr5" style="width:350px;" type="text" value="' + rdata.datadir + '" name="datadir">\
|
||||
<span onclick="ChangePath(\'datadir\')" class="glyphicon glyphicon-folder-open cursor mr20" style="width:auto"></span><button class="btn btn-success btn-sm" onclick="changeMySQLDataPath(1)">' + lan.soft.mysql_to + '</button>\
|
||||
<span onclick="changePath(\'datadir\')" class="glyphicon glyphicon-folder-open cursor mr20" style="width:auto"></span><button class="btn btn-success btn-sm" onclick="changeMySQLDataPath(1)">' + lan.soft.mysql_to + '</button>\
|
||||
</p>';
|
||||
$(".soft-man-con").html(LimitCon);
|
||||
});
|
||||
|
||||
@@ -86,6 +86,7 @@ Install_mysql()
|
||||
make -j${cpuCore} && make install && make clean
|
||||
|
||||
if [ -d $serverPath/mysql ];then
|
||||
rm -rf ${mysqlDir}/mysql-${VERSION}
|
||||
echo '5.5' > $serverPath/mysql/version.pl
|
||||
echo '安装完成' > $install_tmp
|
||||
else
|
||||
|
||||
@@ -105,6 +105,7 @@ Install_mysql()
|
||||
|
||||
|
||||
if [ -d $serverPath/mysql ];then
|
||||
rm -rf ${mysqlDir}/mysql-${VERSION}
|
||||
echo '5.6' > $serverPath/mysql/version.pl
|
||||
echo '安装完成' > $install_tmp
|
||||
else
|
||||
|
||||
@@ -118,6 +118,7 @@ Install_mysql()
|
||||
make -j${cpuCore} && make install && make clean
|
||||
|
||||
if [ -d $serverPath/mysql ];then
|
||||
rm -rf ${mysqlDir}/mysql-${VERSION}
|
||||
echo '5.7' > $serverPath/mysql/version.pl
|
||||
echo '安装完成' > $install_tmp
|
||||
else
|
||||
|
||||
@@ -210,6 +210,7 @@ Install_mysql()
|
||||
make -j${cpuCore} && make install && make clean
|
||||
|
||||
if [ -d $serverPath/mysql ];then
|
||||
rm -rf ${mysqlDir}/mysql-${VERSION}
|
||||
echo '8.0' > $serverPath/mysql/version.pl
|
||||
echo '安装完成' > $install_tmp
|
||||
else
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 878 B |
Executable
+26
@@ -0,0 +1,26 @@
|
||||
<div class="bt-form">
|
||||
<div class="bt-w-main">
|
||||
<div class='plugin_version'></div>
|
||||
<div class="bt-w-menu">
|
||||
<p class="bgw" onclick="pluginService('nezha',$('.plugin_version').attr('version'));">面板服务</p>
|
||||
<p onclick="pluginInitD('nezha',$('.plugin_version').attr('version'));">面板自启动</p>
|
||||
<p onclick="nezha.cfg($('.plugin_version').attr('version'));">面板配置</p>
|
||||
<p onclick="pluginConfig('nezha', $('.plugin_version').attr('version'), 'conf');">面板配置文件</p>
|
||||
<p onclick="pluginService('nezha', $('.plugin_version').attr('version'), 'agent');">AGENT服务</p>
|
||||
<p onclick="pluginInitD('nezha', $('.plugin_version').attr('version'), 'agent');">AGENT自启动</p>
|
||||
<p onclick="nezha.agent_cfg($('.plugin_version').attr('version'));">AGENT配置</p>
|
||||
<p onclick="nezha.readme();">说明</p>
|
||||
</div>
|
||||
<div class="bt-w-con pd15">
|
||||
<div class="soft-man-con"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script type="text/javascript">
|
||||
resetPluginWinHeight(530);
|
||||
$.getScript( "/plugins/file?name=nezha&f=js/nezha.js", function(){
|
||||
nezha.init();
|
||||
pluginService('nezha');
|
||||
});
|
||||
</script>
|
||||
Executable
+364
@@ -0,0 +1,364 @@
|
||||
# coding:utf-8
|
||||
|
||||
import sys
|
||||
import io
|
||||
import os
|
||||
import time
|
||||
import re
|
||||
import socket
|
||||
import json
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
sys.path.append(os.getcwd() + "/class/core")
|
||||
import mw
|
||||
|
||||
app_debug = False
|
||||
if mw.isAppleSystem():
|
||||
app_debug = True
|
||||
|
||||
|
||||
class App:
|
||||
__setupPath = '/www/server/nezha'
|
||||
__cfg = ''
|
||||
__agent_cfg = ''
|
||||
|
||||
def __init__(self):
|
||||
self.__setupPath = self.getServerDir()
|
||||
self.__cfg = self.__setupPath + '/nezha.cfg'
|
||||
self.__agent_cfg = self.__setupPath + '/agent.cfg'
|
||||
|
||||
def getArgs(self):
|
||||
args = sys.argv[2:]
|
||||
tmp = {}
|
||||
args_len = len(args)
|
||||
|
||||
if args_len == 1:
|
||||
t = args[0].strip('{').strip('}')
|
||||
t = t.split(':', 1)
|
||||
tmp[t[0]] = t[1]
|
||||
elif args_len > 1:
|
||||
for i in range(len(args)):
|
||||
t = args[i].split(':', 1)
|
||||
tmp[t[0]] = t[1]
|
||||
|
||||
return tmp
|
||||
|
||||
def checkArgs(self, data, ck=[]):
|
||||
for i in range(len(ck)):
|
||||
if not ck[i] in data:
|
||||
return (False, mw.returnJson(False, '参数:(' + ck[i] + ')没有!'))
|
||||
return (True, mw.returnJson(True, 'ok'))
|
||||
|
||||
def __release_port(self, port):
|
||||
from collections import namedtuple
|
||||
try:
|
||||
import firewall_api
|
||||
firewall_api.firewall_api().addAcceptPortArgs(port, 'nezha', 'port')
|
||||
return port
|
||||
except Exception as e:
|
||||
return "Release failed {}".format(e)
|
||||
|
||||
def openPort(self):
|
||||
for i in ["9527", "5555"]:
|
||||
self.__release_port(i)
|
||||
return True
|
||||
|
||||
def getPluginName(self):
|
||||
return 'nezha'
|
||||
|
||||
def getPluginDir(self):
|
||||
return mw.getPluginDir() + '/' + self.getPluginName()
|
||||
|
||||
def getServerDir(self):
|
||||
return mw.getServerDir() + '/' + self.getPluginName()
|
||||
|
||||
def getInitdConfTpl(self):
|
||||
path = self.getPluginDir() + "/init.d/nezha.tpl"
|
||||
return path
|
||||
|
||||
def getInitdAgentConfTpl(self):
|
||||
path = self.getPluginDir() + "/init.d/nezha-agent.tpl"
|
||||
return path
|
||||
|
||||
def getHomeDir(self):
|
||||
if mw.isAppleSystem():
|
||||
user = mw.execShell(
|
||||
"who | sed -n '2, 1p' |awk '{print $1}'")[0].strip()
|
||||
return '/Users/' + user
|
||||
else:
|
||||
return '/root'
|
||||
|
||||
def getRunUser(self):
|
||||
if mw.isAppleSystem():
|
||||
user = mw.execShell(
|
||||
"who | sed -n '2, 1p' |awk '{print $1}'")[0].strip()
|
||||
return user
|
||||
else:
|
||||
return 'root'
|
||||
|
||||
def status(self):
|
||||
cmd = "ps -ef|grep " + self.getPluginName() + \
|
||||
" |grep -v grep | grep -v nezha-agent | grep -v python | awk '{print $2}'"
|
||||
data = mw.execShell(cmd)
|
||||
if data[0] == '':
|
||||
return "stop"
|
||||
return 'start'
|
||||
|
||||
def status_agent(self):
|
||||
cmd = "ps -ef | grep nezha-agent | grep -v grep | grep -v python | awk '{print $2}'"
|
||||
data = mw.execShell(cmd)
|
||||
if data[0] == '':
|
||||
return 'stop'
|
||||
return 'start'
|
||||
|
||||
def contentReplace(self, content):
|
||||
|
||||
service_path = mw.getServerDir()
|
||||
content = content.replace('{$ROOT_PATH}', mw.getRootDir())
|
||||
content = content.replace('{$SERVER_PATH}', service_path)
|
||||
content = content.replace('{$RUN_USER}', self.getRunUser())
|
||||
content = content.replace('{$HOME_DIR}', self.getHomeDir())
|
||||
|
||||
return content
|
||||
|
||||
def initDreplace(self):
|
||||
|
||||
file_tpl = self.getInitdConfTpl()
|
||||
service_path = mw.getServerDir()
|
||||
|
||||
initD_path = self.getServerDir() + '/init.d'
|
||||
if not os.path.exists(initD_path):
|
||||
os.mkdir(initD_path)
|
||||
self.openPort()
|
||||
|
||||
file_bin = initD_path + '/' + self.getPluginName()
|
||||
|
||||
if not os.path.exists(file_bin):
|
||||
content = mw.readFile(file_tpl)
|
||||
content = self.contentReplace(content)
|
||||
mw.writeFile(file_bin, content)
|
||||
mw.execShell('chmod +x ' + file_bin)
|
||||
|
||||
# systemd
|
||||
systemDir = mw.systemdCfgDir()
|
||||
systemService = systemDir + '/nezha.service'
|
||||
systemServiceTpl = self.getPluginDir() + '/init.d/nezha.service.tpl'
|
||||
if os.path.exists(systemDir) and not os.path.exists(systemService):
|
||||
service_path = mw.getServerDir()
|
||||
se_content = mw.readFile(systemServiceTpl)
|
||||
se_content = self.contentReplace(se_content)
|
||||
mw.writeFile(systemService, se_content)
|
||||
mw.execShell('systemctl daemon-reload')
|
||||
|
||||
return file_bin
|
||||
|
||||
def contentAgentReplace(self, content):
|
||||
path = self.__agent_cfg
|
||||
if os.path.exists(path):
|
||||
data = self.get_agent_cfg()
|
||||
content = content.replace('{$APP_HOST}', data['host'])
|
||||
content = content.replace('{$APP_SECRET}', data['secret'])
|
||||
|
||||
return content
|
||||
|
||||
def initDAgent(self):
|
||||
file_tpl = self.getInitdAgentConfTpl()
|
||||
|
||||
initD_path = self.getServerDir() + '/init.d'
|
||||
if not os.path.exists(initD_path):
|
||||
os.mkdir(initD_path)
|
||||
|
||||
file_agent_bin = initD_path + '/nezha-agent'
|
||||
|
||||
content = mw.readFile(file_tpl)
|
||||
content = self.contentReplace(content)
|
||||
content = self.contentAgentReplace(content)
|
||||
mw.writeFile(file_agent_bin, content)
|
||||
mw.execShell('chmod +x ' + file_agent_bin)
|
||||
|
||||
# systemd
|
||||
sysDir = mw.systemdCfgDir()
|
||||
sysService = sysDir + '/nezha-agent.service'
|
||||
sysServiceTpl = self.getPluginDir() + '/init.d/nezha-agent.service.tpl'
|
||||
service_path = mw.getServerDir()
|
||||
content = mw.readFile(sysServiceTpl)
|
||||
content = self.contentReplace(content)
|
||||
content = self.contentAgentReplace(content)
|
||||
mw.writeFile(sysService, content)
|
||||
mw.execShell('systemctl daemon-reload')
|
||||
|
||||
return file_agent_bin
|
||||
|
||||
def init_cfg(self):
|
||||
self.initDreplace()
|
||||
self.initDAgent()
|
||||
|
||||
def imOp(self, method):
|
||||
|
||||
file = self.initDreplace()
|
||||
|
||||
if not mw.isAppleSystem():
|
||||
cmd = 'systemctl {} {}'.format(method, self.getPluginName())
|
||||
data = mw.execShell(cmd)
|
||||
if data[1] == '':
|
||||
return 'ok'
|
||||
return 'fail'
|
||||
|
||||
data = mw.execShell(file + ' ' + method)
|
||||
if data[1] == '':
|
||||
return 'ok'
|
||||
return data[0]
|
||||
|
||||
def start(self):
|
||||
return self.imOp('start')
|
||||
|
||||
def stop(self):
|
||||
return self.imOp('stop')
|
||||
|
||||
def restart(self):
|
||||
return self.imOp('restart')
|
||||
|
||||
def reload(self):
|
||||
return self.imOp('reload')
|
||||
|
||||
def agOp(self, method):
|
||||
file = self.initDAgent()
|
||||
|
||||
path = self.__agent_cfg
|
||||
if not os.path.exists(path):
|
||||
return '请先设置Agent配置!'
|
||||
|
||||
if not mw.isAppleSystem():
|
||||
cmd = 'systemctl {} {}'.format(method, 'nezha-agent')
|
||||
data = mw.execShell(cmd)
|
||||
if data[1] == '':
|
||||
return 'ok'
|
||||
return 'fail'
|
||||
|
||||
data = mw.execShell(file + ' ' + method)
|
||||
if data[1] == '':
|
||||
return 'ok'
|
||||
return data[0]
|
||||
|
||||
def start_agent(self):
|
||||
return self.agOp('start')
|
||||
|
||||
def stop_agent(self):
|
||||
return self.agOp('stop')
|
||||
|
||||
def restart_agent(self):
|
||||
return self.agOp('restart')
|
||||
|
||||
def reload_agent(self):
|
||||
return self.agentOp('reload')
|
||||
|
||||
def initd_status(self):
|
||||
cmd = 'systemctl status nezha | grep loaded | grep "enabled;"'
|
||||
data = mw.execShell(cmd)
|
||||
if data[0] == '':
|
||||
return 'fail'
|
||||
return 'ok'
|
||||
|
||||
def initd_install(self):
|
||||
mw.execShell('systemctl enable nezha')
|
||||
return 'ok'
|
||||
|
||||
def initd_uninstall(self):
|
||||
mw.execShell('systemctl disable nezha')
|
||||
return 'ok'
|
||||
|
||||
def initd_status_agent(self):
|
||||
cmd = 'systemctl status nezha-agent | grep loaded | grep "enabled;"'
|
||||
data = mw.execShell(cmd)
|
||||
if data[0] == '':
|
||||
return 'fail'
|
||||
return 'ok'
|
||||
|
||||
def initd_install_agent(self):
|
||||
mw.execShell('systemctl enable nezha-agent')
|
||||
return 'ok'
|
||||
|
||||
def initd_uninstall_agent(self):
|
||||
mw.execShell('systemctl disable nezha-agent')
|
||||
return 'ok'
|
||||
|
||||
def conf(self):
|
||||
return self.getServerDir() + '/dashboard/data/config.yaml'
|
||||
|
||||
def nezha_cfg(self):
|
||||
path = self.__cfg
|
||||
if not os.path.exists(path):
|
||||
d = {}
|
||||
cmd_un = 'cd ' + self.getServerDir() + '/dashboard && ./nezha conf -u ""'
|
||||
mw.execShell(cmd_un)
|
||||
td = mw.execShell(cmd_un)
|
||||
d['username'] = td[0].strip()
|
||||
|
||||
pwd = mw.getRandomString(16)
|
||||
cmd_pwd = 'cd ' + self.getServerDir() + '/dashboard && ./nezha conf -u "" -p ' + pwd
|
||||
td = mw.execShell(cmd_pwd)
|
||||
d['password'] = pwd
|
||||
|
||||
mw.writeFile(path, mw.enDoubleCrypt('nezha', mw.getJson(d)))
|
||||
|
||||
info = mw.readFile(path)
|
||||
info = mw.deDoubleCrypt('nezha', info)
|
||||
|
||||
info = json.loads(info)
|
||||
return mw.returnJson(True, 'ok', info)
|
||||
|
||||
def nezha_save_cfg(self):
|
||||
args = self.getArgs()
|
||||
data = self.checkArgs(args, ['username', 'password'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
path = self.__cfg
|
||||
|
||||
cmd = 'cd ' + self.getServerDir() + '/dashboard && ./nezha conf -su "' + \
|
||||
args['username'] + '" -p ' + args['password']
|
||||
# print(cmd)
|
||||
t = mw.execShell(cmd)
|
||||
# print(t)
|
||||
mw.writeFile(path, mw.enDoubleCrypt('nezha', mw.getJson(args)))
|
||||
return mw.returnJson(True, '修改成功!')
|
||||
|
||||
def get_agent_cfg(self):
|
||||
path = self.__agent_cfg
|
||||
info = mw.readFile(path)
|
||||
info = mw.deDoubleCrypt('agent', info)
|
||||
info = json.loads(info)
|
||||
return info
|
||||
|
||||
def agent_cfg(self):
|
||||
path = self.__agent_cfg
|
||||
if not os.path.exists(path):
|
||||
d = {}
|
||||
d['host'] = '127.0.0.1:5555'
|
||||
d['secret'] = 'secret'
|
||||
mw.writeFile(path, mw.enDoubleCrypt('agent', mw.getJson(d)))
|
||||
|
||||
info = self.get_agent_cfg()
|
||||
return mw.returnJson(True, 'ok', info)
|
||||
|
||||
def agent_save_cfg(self):
|
||||
args = self.getArgs()
|
||||
data = self.checkArgs(args, ['host', 'secret'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
path = self.__agent_cfg
|
||||
mw.writeFile(path, mw.enDoubleCrypt('agent', mw.getJson(args)))
|
||||
return mw.returnJson(True, '修改成功!')
|
||||
|
||||
def run_log(self):
|
||||
return self.getServerDir() + '/logs/nezha.log'
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
func = sys.argv[1]
|
||||
classApp = App()
|
||||
try:
|
||||
data = eval("classApp." + func + "()")
|
||||
print(data)
|
||||
except Exception as e:
|
||||
print('error:' + str(e))
|
||||
Executable
+18
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"sort": 7,
|
||||
"ps": "哪吒监控面板/改造版",
|
||||
"name": "nezha",
|
||||
"title": "哪吒监控",
|
||||
"shell": "install.sh",
|
||||
"versions":["0.15.2"],
|
||||
"tip": "soft",
|
||||
"checks": "server/nezha",
|
||||
"path": "server/nezha",
|
||||
"display": 1,
|
||||
"author": "midoks",
|
||||
"date": "2023-06-26",
|
||||
"home": "https://github.com/midoks/nezha",
|
||||
"doc1": "https://nezha.wiki/",
|
||||
"type": 0,
|
||||
"pid": "5"
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
[Unit]
|
||||
Description=Nezha Agent
|
||||
After=syslog.target
|
||||
#After=network.target
|
||||
#After=nezha-dashboard.service
|
||||
|
||||
[Service]
|
||||
# Modify these two values and uncomment them if you have
|
||||
# repos with lots of files and get an HTTP error 500 because
|
||||
# of that
|
||||
###
|
||||
#LimitMEMLOCK=infinity
|
||||
#LimitNOFILE=65535
|
||||
Type=simple
|
||||
User=root
|
||||
Group=root
|
||||
WorkingDirectory={$SERVER_PATH}/nezha/agent/
|
||||
ExecStart={$SERVER_PATH}/nezha/agent/nezha-agent -s {$APP_HOST} -p {$APP_SECRET}
|
||||
Restart=always
|
||||
#Environment=DEBUG=true
|
||||
|
||||
# Some distributions may not support these hardening directives. If you cannot start the service due
|
||||
# to an unknown option, comment out the ones not supported by your version of systemd.
|
||||
#ProtectSystem=full
|
||||
#PrivateDevices=yes
|
||||
#PrivateTmp=yes
|
||||
#NoNewPrivileges=true
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,90 @@
|
||||
#!/bin/bash
|
||||
# chkconfig: 2345 55 25
|
||||
# description: Nezha Agent Service
|
||||
|
||||
### BEGIN INIT INFO
|
||||
# Provides: Nezha Agent
|
||||
# Required-Start: $all
|
||||
# Required-Stop: $all
|
||||
# Default-Start: 2 3 4 5
|
||||
# Default-Stop: 0 1 6
|
||||
# Short-Description: starts Nezha Agent
|
||||
# Description: starts the Nezha Agent
|
||||
### END INIT INFO
|
||||
|
||||
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
|
||||
|
||||
if [ -f /etc/init.d/functions ];then
|
||||
. /etc/init.d/functions
|
||||
fi
|
||||
|
||||
if [ -f /etc/rc.d/init.d/functions ];then
|
||||
. /etc/rc.d/init.d/functions
|
||||
fi
|
||||
|
||||
SERVICENAME=nezha-agent
|
||||
LOG_PATH={$SERVER_PATH}/nezha/logs
|
||||
APP_PATH={$SERVER_PATH}/nezha/agent
|
||||
APP_HOST={$APP_HOST}
|
||||
APP_SECRET={$APP_SECRET}
|
||||
|
||||
|
||||
app_start(){
|
||||
isStart=`ps -ef|grep "${SERVICENAME}" | grep -v grep | grep -v python | grep -v "/bin/bash" | awk '{print $2}'`
|
||||
if [ "$isStart" == '' ];then
|
||||
echo -e "Starting ${SERVICENAME}... \c"
|
||||
cd $APP_PATH
|
||||
exec nohup ${APP_PATH}/${SERVICENAME} -d -s ${APP_HOST} -p ${APP_SECRET} >> ${LOG_PATH}/${SERVICENAME}.log 2>&1 &
|
||||
isStart=""
|
||||
while [[ "$isStart" == "" ]];
|
||||
do
|
||||
echo -e ".\c"
|
||||
sleep 0.5
|
||||
isStart=$(ps -ef|grep "${SERVICENAME}" |grep -v grep | grep -v python | grep -v "/bin/bash" | awk '{print $2}')
|
||||
let n+=1
|
||||
if [ $n -gt 15 ];then
|
||||
break;
|
||||
fi
|
||||
done
|
||||
if [ "$isStart" == '' ];then
|
||||
echo -e "\033[31mError: ${SERVICENAME} service startup failed.\033[0m"
|
||||
return;
|
||||
fi
|
||||
echo -e "\033[32mdone\033[0m"
|
||||
else
|
||||
echo "Starting ${SERVICENAME}(pid $(echo $isStart)) already running"
|
||||
fi
|
||||
}
|
||||
|
||||
app_stop(){
|
||||
pids=`ps -ef | grep "${SERVICENAME}" | grep -v grep | grep -v python | grep -v "/bin/bash" |awk '{print $2}'`
|
||||
arr=($pids)
|
||||
echo -e "Stopping ${SERVICENAME}... \c"
|
||||
for p in ${arr[@]}
|
||||
do
|
||||
# echo "$p"
|
||||
kill -9 $p
|
||||
done
|
||||
echo -e "\033[32mdone\033[0m"
|
||||
}
|
||||
|
||||
app_status(){
|
||||
isStart=`ps -ef | grep "${SERVICENAME}" | grep -v grep | grep -v python | grep -v "/bin/bash" | awk '{print $2}'`
|
||||
if [ "$isStart" == '' ];then
|
||||
echo -e "${SERVICENAME} not running"
|
||||
else
|
||||
echo -e "${SERVICENAME}(pid $(echo $isStart)) already running"
|
||||
fi
|
||||
}
|
||||
|
||||
case "$1" in
|
||||
'start') app_start;;
|
||||
'stop') app_stop;;
|
||||
'status') app_status;;
|
||||
'reload')
|
||||
app_stop
|
||||
app_start;;
|
||||
'restart')
|
||||
app_stop
|
||||
app_start;;
|
||||
esac
|
||||
@@ -0,0 +1,30 @@
|
||||
[Unit]
|
||||
Description=Nezha Dashborad
|
||||
After=syslog.target
|
||||
After=network.target
|
||||
After=mariadb.service mysqld.service postgresql.service memcached.service redis.service
|
||||
|
||||
[Service]
|
||||
# Modify these two values and uncomment them if you have
|
||||
# repos with lots of files and get an HTTP error 500 because
|
||||
# of that
|
||||
###
|
||||
#LimitMEMLOCK=infinity
|
||||
#LimitNOFILE=65535
|
||||
Type=simple
|
||||
#User=root
|
||||
#Group=root
|
||||
WorkingDirectory={$SERVER_PATH}/nezha/dashboard/
|
||||
ExecStart={$SERVER_PATH}/nezha/dashboard/nezha web
|
||||
Restart=always
|
||||
#Environment=DEBUG=true
|
||||
|
||||
# Some distributions may not support these hardening directives. If you cannot start the service due
|
||||
# to an unknown option, comment out the ones not supported by your version of systemd.
|
||||
ProtectSystem=full
|
||||
PrivateDevices=yes
|
||||
PrivateTmp=yes
|
||||
NoNewPrivileges=true
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,87 @@
|
||||
#!/bin/bash
|
||||
# chkconfig: 2345 55 25
|
||||
# description: Nezha Service
|
||||
|
||||
### BEGIN INIT INFO
|
||||
# Provides: Nezha
|
||||
# Required-Start: $all
|
||||
# Required-Stop: $all
|
||||
# Default-Start: 2 3 4 5
|
||||
# Default-Stop: 0 1 6
|
||||
# Short-Description: starts Nezha
|
||||
# Description: starts the Nezha
|
||||
### END INIT INFO
|
||||
|
||||
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
|
||||
|
||||
if [ -f /etc/init.d/functions ];then
|
||||
. /etc/init.d/functions
|
||||
fi
|
||||
|
||||
if [ -f /etc/rc.d/init.d/functions ];then
|
||||
. /etc/rc.d/init.d/functions
|
||||
fi
|
||||
|
||||
SERVICENAME=nezha
|
||||
LOG_PATH={$SERVER_PATH}/${SERVICENAME}/logs
|
||||
APP_PATH={$SERVER_PATH}/${SERVICENAME}/dashboard
|
||||
|
||||
|
||||
app_start(){
|
||||
isStart=`ps -ef|grep "${SERVICENAME} web" | grep -v grep | grep -v python | grep -v "/bin/bash" | awk '{print $2}'`
|
||||
if [ "$isStart" == '' ];then
|
||||
echo -e "Starting ${SERVICENAME}... \c"
|
||||
cd $APP_PATH && exec nohup ${APP_PATH}/${SERVICENAME} web >> ${LOG_PATH}/${SERVICENAME}.log 2>&1 &
|
||||
isStart=""
|
||||
while [[ "$isStart" == "" ]];
|
||||
do
|
||||
echo -e ".\c"
|
||||
sleep 0.5
|
||||
isStart=$(ps -ef|grep "${SERVICENAME} web" |grep -v grep | grep -v python | grep -v "/bin/bash" | awk '{print $2}')
|
||||
let n+=1
|
||||
if [ $n -gt 15 ];then
|
||||
break;
|
||||
fi
|
||||
done
|
||||
if [ "$isStart" == '' ];then
|
||||
echo -e "\033[31mError: ${SERVICENAME} service startup failed.\033[0m"
|
||||
return;
|
||||
fi
|
||||
echo -e "\033[32mdone\033[0m"
|
||||
else
|
||||
echo "Starting ${SERVICENAME}(pid $(echo $isStart)) already running"
|
||||
fi
|
||||
}
|
||||
|
||||
app_stop(){
|
||||
pids=`ps -ef | grep "${SERVICENAME} web" | grep -v grep | grep -v python | grep -v "/bin/bash" |awk '{print $2}'`
|
||||
arr=($pids)
|
||||
echo -e "Stopping ${SERVICENAME}... \c"
|
||||
for p in ${arr[@]}
|
||||
do
|
||||
# echo "$p"
|
||||
kill -9 $p
|
||||
done
|
||||
echo -e "\033[32mdone\033[0m"
|
||||
}
|
||||
|
||||
app_status(){
|
||||
isStart=`ps -ef | grep "${SERVICENAME} web" | grep -v grep | grep -v python | grep -v "/bin/bash" | awk '{print $2}'`
|
||||
if [ "$isStart" == '' ];then
|
||||
echo -e "${SERVICENAME} not running"
|
||||
else
|
||||
echo -e "${SERVICENAME}(pid $(echo $isStart)) already running"
|
||||
fi
|
||||
}
|
||||
|
||||
case "$1" in
|
||||
'start') app_start;;
|
||||
'stop') app_stop;;
|
||||
'status') app_status;;
|
||||
'reload')
|
||||
app_stop
|
||||
app_start;;
|
||||
'restart')
|
||||
app_stop
|
||||
app_start;;
|
||||
esac
|
||||
Executable
+43
@@ -0,0 +1,43 @@
|
||||
#!/bin/bash
|
||||
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
|
||||
export PATH
|
||||
|
||||
curPath=`pwd`
|
||||
rootPath=$(dirname "$curPath")
|
||||
rootPath=$(dirname "$rootPath")
|
||||
serverPath=$(dirname "$rootPath")
|
||||
|
||||
install_tmp=${rootPath}/tmp/mw_install.pl
|
||||
|
||||
action=$1
|
||||
type=$2
|
||||
|
||||
if [ "${2}" == "" ];then
|
||||
echo '缺少安装脚本...' > $install_tmp
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ ! -d $curPath/versions/$2 ];then
|
||||
echo '缺少安装脚本2...' > $install_tmp
|
||||
exit 0
|
||||
fi
|
||||
|
||||
sh -x $curPath/versions/$2/install.sh $1
|
||||
|
||||
if [ "${action}" == "uninstall" ];then
|
||||
if [ -f /usr/lib/systemd/system/nezha.service ] || [ -f /lib/systemd/system/nezha.service ] ;then
|
||||
systemctl stop nezha
|
||||
systemctl disable nezha
|
||||
rm -rf /usr/lib/systemd/system/nezha.service
|
||||
rm -rf /lib/systemd/system/nezha.service
|
||||
systemctl daemon-reload
|
||||
fi
|
||||
|
||||
if [ -f /usr/lib/systemd/system/nezha-agent.service ] || [ -f /lib/systemd/system/nezha-agent.service ] ;then
|
||||
systemctl stop nezha-agent
|
||||
systemctl disable nezha-agent
|
||||
rm -rf /usr/lib/systemd/system/nezha-agent.service
|
||||
rm -rf /lib/systemd/system/nezha-agent.service
|
||||
systemctl daemon-reload
|
||||
fi
|
||||
fi
|
||||
Executable
+184
@@ -0,0 +1,184 @@
|
||||
var nezha = {
|
||||
plugin_name: 'nezha',
|
||||
init: function () {
|
||||
var _this = this;
|
||||
},
|
||||
|
||||
send:function(info){
|
||||
var tips = info['tips'];
|
||||
var method = info['method'];
|
||||
var args = info['data'];
|
||||
var callback = info['success'];
|
||||
|
||||
var loadT = layer.msg(tips, { icon: 16, time: 0, shade: 0.3 });
|
||||
|
||||
var data = {};
|
||||
data['name'] = 'nezha';
|
||||
data['func'] = method;
|
||||
data['version'] = $('.plugin_version').attr('version');
|
||||
|
||||
if (typeof(args) == 'string'){
|
||||
data['args'] = JSON.stringify(toArrayObject(args));
|
||||
} else {
|
||||
data['args'] = JSON.stringify(args);
|
||||
}
|
||||
|
||||
$.post('/plugins/run', data, function(res) {
|
||||
layer.close(loadT);
|
||||
if (!res.status){
|
||||
layer.msg(res.msg,{icon:2,time:10000});
|
||||
return;
|
||||
}
|
||||
|
||||
var ret_data = $.parseJSON(res.data);
|
||||
console.log("send:",ret_data);
|
||||
// if (!ret_data.status){
|
||||
// layer.msg(ret_data.msg,{icon:2,time:2000});
|
||||
// return;
|
||||
// }
|
||||
|
||||
// console.log("send2:",ret_data);
|
||||
|
||||
if(typeof(callback) == 'function'){
|
||||
callback(ret_data);
|
||||
}
|
||||
},'json');
|
||||
},
|
||||
|
||||
postCallback:function(info){
|
||||
var tips = info['tips'];
|
||||
var method = info['method'];
|
||||
var args = info['data'];
|
||||
var callback = info['success'];
|
||||
|
||||
var loadT = layer.msg(tips, { icon: 16, time: 0, shade: 0.3 });
|
||||
|
||||
var data = {};
|
||||
data['name'] = 'nezha';
|
||||
data['func'] = method;
|
||||
data['version'] = $('.plugin_version').attr('version');
|
||||
|
||||
if (typeof(args) == 'string'){
|
||||
data['args'] = JSON.stringify(toArrayObject(args));
|
||||
} else {
|
||||
data['args'] = JSON.stringify(args);
|
||||
}
|
||||
|
||||
$.post('/plugins/callback', data, function(res) {
|
||||
layer.close(loadT);
|
||||
if (!res.status){
|
||||
layer.msg(res.msg,{icon:2,time:10000});
|
||||
return;
|
||||
}
|
||||
|
||||
var ret_data = $.parseJSON(res.data);
|
||||
if (!ret_data.status){
|
||||
layer.msg(ret_data.msg,{icon:2,time:2000});
|
||||
return;
|
||||
}
|
||||
|
||||
if(typeof(callback) == 'function'){
|
||||
callback(res);
|
||||
}
|
||||
},'json');
|
||||
},
|
||||
|
||||
repeatPwd:function (a, id) {
|
||||
$("#"+id).val(randomStrPwd(a))
|
||||
},
|
||||
|
||||
save_cfg:function(version){
|
||||
var username = $("input[name='username']").val();
|
||||
var password = $("input[name='password']").val();
|
||||
|
||||
this.send({
|
||||
tips:'正在设置中...',
|
||||
data:{'username':username,'password':password},
|
||||
method:'nezha_save_cfg',
|
||||
success:function(rdata){
|
||||
layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 });
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
cfg:function(version){
|
||||
this.send({
|
||||
tips:'正在获取中...',
|
||||
method:'nezha_cfg',
|
||||
success:function(data){
|
||||
var d = data.data;
|
||||
var value = '<p>\
|
||||
<span>用户名</span>\
|
||||
<input id="nz_username" style="width: 160px;" class="bt-input-text mr5" name="username" value="'+d['username']+'" type="text">\
|
||||
,<span title="随机用户名" class="glyphicon glyphicon-repeat cursor" onclick="nezha.repeatPwd(8,\'nz_username\')"></span>\
|
||||
</p>';
|
||||
|
||||
value += '<p>\
|
||||
<span>密码</span>\
|
||||
<input id="nz_password" style="width: 160px;" class="bt-input-text mr5" name="password" value="'+d['password']+'" type="text">\
|
||||
,<span title="随机密码" class="glyphicon glyphicon-repeat cursor" onclick="nezha.repeatPwd(16,\'nz_password\')"></span>\
|
||||
</p>';
|
||||
var conf = '<style>.conf_p p{margin-bottom: 2px;} .conf_p span {width: 50px;}</style><div class="conf_p" style="margin-bottom:0">\
|
||||
' + value + '\
|
||||
<div style="margin-top:10px; padding-right:15px" class="text-right">\
|
||||
<button class="btn btn-success btn-sm mr5" onclick="nezha.cfg(\'' + version + '\')">刷新</button>\
|
||||
<button class="btn btn-success btn-sm" onclick="nezha.save_cfg(\'' + version + '\')">保存</button>\
|
||||
</div>\
|
||||
</div>'
|
||||
$(".soft-man-con").html(conf);
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
agent_save_cfg:function(version){
|
||||
var host = $("input[name='host']").val();
|
||||
var secret = $("input[name='secret']").val();
|
||||
|
||||
this.send({
|
||||
tips:'正在设置中...',
|
||||
data:{'host':host,'secret':secret},
|
||||
method:'agent_save_cfg',
|
||||
success:function(rdata){
|
||||
layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 });
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
agent_cfg:function(version){
|
||||
this.send({
|
||||
tips:'正在获取中...',
|
||||
method:'agent_cfg',
|
||||
success:function(data){
|
||||
var d = data.data;
|
||||
var value = '<p>\
|
||||
<span>地址</span>\
|
||||
<input id="nz_username" style="width: 160px;" class="bt-input-text mr5" name="host" value="'+d['host']+'" type="text">\
|
||||
,<font>如1.1.1.1:5444</font>\
|
||||
</p>';
|
||||
|
||||
value += '<p>\
|
||||
<span>密钥</span>\
|
||||
<input id="nz_password" style="width: 160px;" class="bt-input-text mr5" name="secret" value="'+d['secret']+'" type="text">\
|
||||
,<font>密钥</font>\
|
||||
</p>';
|
||||
var conf = '<style>.conf_p p{margin-bottom: 2px;} .conf_p span {width: 50px;}</style><div class="conf_p" style="margin-bottom:0">\
|
||||
' + value + '\
|
||||
<div style="margin-top:10px; padding-right:15px" class="text-right">\
|
||||
<button class="btn btn-success btn-sm mr5" onclick="nezha.agent_cfg(\'' + version + '\')">刷新</button>\
|
||||
<button class="btn btn-success btn-sm" onclick="nezha.agent_save_cfg(\'' + version + '\')">保存</button>\
|
||||
</div>\
|
||||
</div>'
|
||||
$(".soft-man-con").html(conf);
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
readme:function (){
|
||||
var readme = '<ul class="help-info-text c7">';
|
||||
readme += '<li>安装时不会自动启动。</li>';
|
||||
readme += '<li>哪吒面板是改造版,用户名和密码登录【面板配置】,不依赖github/gitee/gitlab。</li>';
|
||||
readme += '<li>Agent需要先手动填写正确信息。</li>';
|
||||
readme += '</ul>';
|
||||
$('.soft-man-con').html(readme);
|
||||
}
|
||||
}
|
||||
Executable
+158
@@ -0,0 +1,158 @@
|
||||
#!/bin/bash
|
||||
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
|
||||
export PATH
|
||||
|
||||
curPath=`pwd`
|
||||
rootPath=$(dirname "$curPath")
|
||||
rootPath=$(dirname "$rootPath")
|
||||
serverPath=$(dirname "$rootPath")
|
||||
|
||||
install_tmp=${rootPath}/tmp/mw_install.pl
|
||||
VERSION=0.15.2
|
||||
|
||||
# bash install.sh install 0.15.2
|
||||
# cd /www/server/mdserver-web/plugins/nezha && bash install.sh install 0.15.2
|
||||
# cd /Users/midoks/Desktop/mwdev/server/mdserver-web/plugins/nezha && bash install.sh install 0.15.2
|
||||
|
||||
bash ${rootPath}/scripts/getos.sh
|
||||
OSNAME=`cat ${rootPath}/data/osname.pl`
|
||||
OSNAME_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'`
|
||||
|
||||
|
||||
ARCH="amd64"
|
||||
|
||||
get_arch() {
|
||||
TMP_ARCH=`arch`
|
||||
if [ "$TMP_ARCH" == "x86_64" ];then
|
||||
ARCH="amd64"
|
||||
elif [ "$TMP_ARCH" == "aarch64" ];then
|
||||
ARCH="arm64"
|
||||
else
|
||||
echo $ARCH
|
||||
fi
|
||||
}
|
||||
|
||||
load_vars() {
|
||||
OS=$(uname | tr '[:upper:]' '[:lower:]')
|
||||
TARGET_DIR="$serverPath/nezha/dashboard"
|
||||
|
||||
|
||||
## China_IP
|
||||
if [[ -z "${CN}" ]]; then
|
||||
if [[ $(curl -m 10 -s https://ipapi.co/json | grep 'China') != "" ]]; then
|
||||
CN=true
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ -z "${CN}" ]]; then
|
||||
GITHUB_RAW_URL="raw.githubusercontent.com/midoks/nezha/main"
|
||||
GITHUB_URL="github.com"
|
||||
else
|
||||
GITHUB_RAW_URL="cdn.jsdelivr.net/gh/midoks/nezha@main"
|
||||
GITHUB_URL="dn-dao-github-mirror.daocloud.io"
|
||||
fi
|
||||
|
||||
echo $GITHUB_RAW_URL
|
||||
echo $GITHUB_URL
|
||||
}
|
||||
|
||||
# download file
|
||||
download_file() {
|
||||
url="${1}"
|
||||
destination="${2}"
|
||||
|
||||
printf "Fetching ${url} \n\n"
|
||||
|
||||
if test -x "$(command -v curl)"; then
|
||||
code=$(curl --connect-timeout 15 -w '%{http_code}' -L "${url}" -o "${destination}")
|
||||
elif test -x "$(command -v wget)"; then
|
||||
code=$(wget -t2 -T15 -O "${destination}" --server-response "${url}" 2>&1 | awk '/^ HTTP/{print $2}' | tail -1)
|
||||
else
|
||||
printf "\e[1;31mNeither curl nor wget was available to perform http requests.\e[0m\n"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ "${code}" != 200 ]; then
|
||||
printf "\e[1;31mRequest failed with code %s\e[0m\n" $code
|
||||
exit 1
|
||||
else
|
||||
printf "\n\e[1;33mDownload succeeded\e[0m\n"
|
||||
fi
|
||||
}
|
||||
|
||||
|
||||
Install_dashborad(){
|
||||
echo '正在安装哪吒监控...' > $install_tmp
|
||||
mkdir -p $serverPath/source
|
||||
|
||||
if [ ! -f $TARGET_DIR/nezha ];then
|
||||
|
||||
DOWNLOAD_URL="https://${GITHUB_URL}/midoks/nezha/releases/download/v${VERSION}/nezha-${OS}-${ARCH}.zip"
|
||||
|
||||
DOWNLOAD_FILE="$(mktemp).zip"
|
||||
download_file $DOWNLOAD_URL $DOWNLOAD_FILE
|
||||
|
||||
if [ ! -d $TARGET_DIR ]; then
|
||||
mkdir -p $TARGET_DIR
|
||||
fi
|
||||
|
||||
unzip $DOWNLOAD_FILE -d $TARGET_DIR
|
||||
rm -rf $DOWNLOAD_FILE
|
||||
fi
|
||||
|
||||
}
|
||||
|
||||
Install_agent(){
|
||||
echo -e "正在下载监控端" > $install_tmp
|
||||
mkdir -p $serverPath/source
|
||||
|
||||
version=v0.15.1
|
||||
|
||||
AGENT_TARGET_DIR="$serverPath/nezha/agent"
|
||||
|
||||
DOWNLOAD_URL="https://${GITHUB_URL}/nezhahq/agent/releases/download/${version}/nezha-agent_${OS}_${ARCH}.zip"
|
||||
DOWNLOAD_FILE="$(mktemp).zip"
|
||||
|
||||
if [ ! -f $AGENT_TARGET_DIR/nezha-agent ];then
|
||||
download_file $DOWNLOAD_URL $DOWNLOAD_FILE
|
||||
|
||||
if [ ! -d $AGENT_TARGET_DIR ]; then
|
||||
mkdir -p $AGENT_TARGET_DIR
|
||||
fi
|
||||
|
||||
unzip $DOWNLOAD_FILE -d $AGENT_TARGET_DIR
|
||||
rm -rf $DOWNLOAD_FILE
|
||||
fi
|
||||
}
|
||||
|
||||
Install_App()
|
||||
{
|
||||
load_vars
|
||||
get_arch
|
||||
|
||||
Install_dashborad
|
||||
Install_agent
|
||||
|
||||
if [ -d $serverPath/nezha ];then
|
||||
echo "$VERSION" > $serverPath/nezha/version.pl
|
||||
cd ${rootPath} && python3 ${rootPath}/plugins/nezha/index.py init_cfg
|
||||
fi
|
||||
echo 'install successful' > $install_tmp
|
||||
}
|
||||
|
||||
Uninstall_App()
|
||||
{
|
||||
cd ${rootPath} && python3 ${rootPath}/plugins/nezha/index.py initd_uninstall
|
||||
cd ${rootPath} && python3 ${rootPath}/plugins/nezha/index.py initd_uninstall_agent
|
||||
cd ${rootPath} && python3 ${rootPath}/plugins/nezha/index.py stop
|
||||
cd ${rootPath} && python3 ${rootPath}/plugins/nezha/index.py stop_agent
|
||||
rm -rf $serverPath/nezha
|
||||
echo "install fail" > $install_tmp
|
||||
}
|
||||
|
||||
action=$1
|
||||
if [ "${1}" == 'install' ];then
|
||||
Install_App
|
||||
else
|
||||
Uninstall_App
|
||||
fi
|
||||
@@ -0,0 +1,2 @@
|
||||
## 指定共享内存
|
||||
lua_shared_dict healthcheck 10m;
|
||||
@@ -0,0 +1,64 @@
|
||||
location / {
|
||||
proxy_pass http://{$UPSTREAM_NAME};
|
||||
|
||||
client_max_body_size 10m;
|
||||
client_body_buffer_size 128k;
|
||||
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header Host $proxy_host;
|
||||
proxy_connect_timeout 90;
|
||||
proxy_send_timeout 90;
|
||||
proxy_read_timeout 90;
|
||||
proxy_buffer_size 4k;
|
||||
proxy_buffers 4 32k;
|
||||
proxy_busy_buffers_size 64k;
|
||||
proxy_temp_file_write_size 64k;
|
||||
}
|
||||
|
||||
|
||||
#location /upstream_status {
|
||||
# allow 127.0.0.1;
|
||||
# deny all;
|
||||
# access_log off;
|
||||
# default_type text/plain;
|
||||
# content_by_lua_block {
|
||||
# local hc = require "resty.upstream.healthcheck"
|
||||
# ngx.say("OpenResty Worker PID: ", ngx.worker.pid())
|
||||
# ngx.print(hc.status_page())
|
||||
# }
|
||||
#}
|
||||
|
||||
location /upstream_status_{$UPSTREAM_NAME} {
|
||||
allow 127.0.0.1;
|
||||
deny all;
|
||||
access_log off;
|
||||
default_type text/plain;
|
||||
content_by_lua_block {
|
||||
local json = require "cjson"
|
||||
local ok, upstream = pcall(require, "ngx.upstream")
|
||||
if not ok then
|
||||
ngx.print("[]")
|
||||
return
|
||||
end
|
||||
|
||||
local get_primary_peers = upstream.get_primary_peers
|
||||
local get_backup_peers = upstream.get_backup_peers
|
||||
local upstream_name = "{$UPSTREAM_NAME}"
|
||||
|
||||
peers, err = get_primary_peers(upstream_name)
|
||||
if not peers then
|
||||
ngx.print("[]")
|
||||
return
|
||||
end
|
||||
|
||||
peers_backup, err = get_backup_peers(upstream_name)
|
||||
if peers_backup then
|
||||
for k, v in pairs(peers_backup) do
|
||||
table.insert(peers,v)
|
||||
end
|
||||
end
|
||||
|
||||
ngx.print(json.encode(peers))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
upstream {$UPSTREAM_NAME}
|
||||
{
|
||||
{$NODE_ALGO}
|
||||
{$NODE_SERVER_LIST}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 853 B |
Executable
+21
@@ -0,0 +1,21 @@
|
||||
<div class="bt-form">
|
||||
<div class="bt-w-main">
|
||||
<div class="bt-w-menu">
|
||||
<p class="bgw" onclick="pluginService('op_load_balance');">服务</p>
|
||||
<p onclick="loadBalanceList();">负载均衡</p>
|
||||
</div>
|
||||
<div class="bt-w-con pd15">
|
||||
<div class="soft-man-con"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<script type="text/javascript" src="/plugins/file?name=op_load_balance&f=js/app.js"></script>
|
||||
<script type="text/javascript">
|
||||
resetPluginWinWidth(800);
|
||||
resetPluginWinHeight(300);
|
||||
$.getScript( "/plugins/file?name=op_load_balance&f=js/app.js", function(){
|
||||
pluginService('op_load_balance');
|
||||
});
|
||||
</script>
|
||||
Executable
+474
@@ -0,0 +1,474 @@
|
||||
# coding:utf-8
|
||||
|
||||
import sys
|
||||
import io
|
||||
import os
|
||||
import time
|
||||
import subprocess
|
||||
import json
|
||||
import re
|
||||
|
||||
sys.path.append(os.getcwd() + "/class/core")
|
||||
import mw
|
||||
|
||||
|
||||
app_debug = False
|
||||
if mw.isAppleSystem():
|
||||
app_debug = True
|
||||
|
||||
|
||||
def getPluginName():
|
||||
return 'op_load_balance'
|
||||
|
||||
|
||||
def getPluginDir():
|
||||
return mw.getPluginDir() + '/' + getPluginName()
|
||||
|
||||
|
||||
def getServerDir():
|
||||
return mw.getServerDir() + '/' + getPluginName()
|
||||
|
||||
|
||||
def getArgs():
|
||||
args = sys.argv[2:]
|
||||
tmp = {}
|
||||
args_len = len(args)
|
||||
|
||||
if args_len == 1:
|
||||
t = args[0].strip('{').strip('}')
|
||||
if t.strip() == '':
|
||||
tmp = []
|
||||
else:
|
||||
t = t.split(':')
|
||||
tmp[t[0]] = t[1]
|
||||
tmp[t[0]] = t[1]
|
||||
elif args_len > 1:
|
||||
for i in range(len(args)):
|
||||
t = args[i].split(':')
|
||||
tmp[t[0]] = t[1]
|
||||
return tmp
|
||||
|
||||
|
||||
def checkArgs(data, ck=[]):
|
||||
for i in range(len(ck)):
|
||||
if not ck[i] in data:
|
||||
return (False, mw.returnJson(False, '参数:(' + ck[i] + ')没有!'))
|
||||
return (True, mw.returnJson(True, 'ok'))
|
||||
|
||||
|
||||
def getConf():
|
||||
path = getServerDir() + "/cfg.json"
|
||||
|
||||
if not os.path.exists(path):
|
||||
mw.writeFile(path, '[]')
|
||||
|
||||
c = mw.readFile(path)
|
||||
return json.loads(c)
|
||||
|
||||
|
||||
def writeConf(data):
|
||||
path = getServerDir() + "/cfg.json"
|
||||
mw.writeFile(path, json.dumps(data))
|
||||
|
||||
|
||||
def contentReplace(content):
|
||||
service_path = mw.getServerDir()
|
||||
content = content.replace('{$ROOT_PATH}', mw.getRootDir())
|
||||
content = content.replace('{$SERVER_PATH}', service_path)
|
||||
content = content.replace('{$APP_PATH}', app_path)
|
||||
return content
|
||||
|
||||
|
||||
def restartWeb():
|
||||
mw.opWeb('stop')
|
||||
mw.opWeb('start')
|
||||
|
||||
|
||||
def loadBalanceConf():
|
||||
path = mw.getServerDir() + '/web_conf/nginx/vhost/load_balance.conf'
|
||||
return path
|
||||
|
||||
|
||||
def initDreplace():
|
||||
|
||||
dst_conf_tpl = getPluginDir() + '/conf/load_balance.conf'
|
||||
dst_conf = loadBalanceConf()
|
||||
|
||||
if not os.path.exists(dst_conf):
|
||||
con = mw.readFile(dst_conf_tpl)
|
||||
mw.writeFile(dst_conf, con)
|
||||
|
||||
|
||||
def status():
|
||||
if not mw.getWebStatus():
|
||||
return 'stop'
|
||||
|
||||
dst_conf = loadBalanceConf()
|
||||
if not os.path.exists(dst_conf):
|
||||
return 'stop'
|
||||
|
||||
return 'start'
|
||||
|
||||
|
||||
def start():
|
||||
initDreplace()
|
||||
restartWeb()
|
||||
return 'ok'
|
||||
|
||||
|
||||
def stop():
|
||||
dst_conf = loadBalanceConf()
|
||||
os.remove(dst_conf)
|
||||
|
||||
deleteLoadBalanceAllCfg()
|
||||
restartWeb()
|
||||
return 'ok'
|
||||
|
||||
|
||||
def restart():
|
||||
restartWeb()
|
||||
return 'ok'
|
||||
|
||||
|
||||
def reload():
|
||||
restartWeb()
|
||||
return 'ok'
|
||||
|
||||
|
||||
def installPreInspection():
|
||||
check_op = mw.getServerDir() + "/openresty"
|
||||
if not os.path.exists(check_op):
|
||||
return "请先安装OpenResty"
|
||||
return 'ok'
|
||||
|
||||
|
||||
def deleteLoadBalanceAllCfg():
|
||||
cfg = getConf()
|
||||
upstream_dir = mw.getServerDir() + '/web_conf/nginx/upstream'
|
||||
lua_dir = mw.getServerDir() + '/web_conf/nginx/lua/init_worker_by_lua_file'
|
||||
rewrite_dir = mw.getServerDir() + '/web_conf/nginx/rewrite'
|
||||
vhost_dir = mw.getServerDir() + '/web_conf/nginx/vhost'
|
||||
|
||||
for conf in cfg:
|
||||
upstream_file = upstream_dir + '/' + conf['upstream_name'] + '.conf'
|
||||
if os.path.exists(upstream_file):
|
||||
os.remove(upstream_file)
|
||||
|
||||
lua_file = lua_dir + '/' + conf['upstream_name'] + '.lua'
|
||||
if os.path.exists(lua_file):
|
||||
os.remove(lua_file)
|
||||
|
||||
rewrite_file = rewrite_dir + '/' + conf['domain'] + '.conf'
|
||||
mw.writeFile(rewrite_file, '')
|
||||
|
||||
path = vhost_dir + '/' + conf['domain'] + '.conf'
|
||||
|
||||
content = mw.readFile(path)
|
||||
content = re.sub('include ' + upstream_file + ';' + "\n", '', content)
|
||||
mw.writeFile(path, content)
|
||||
|
||||
mw.opLuaInitWorkerFile()
|
||||
|
||||
|
||||
def makeConfServerList(data):
|
||||
slist = ''
|
||||
for x in data:
|
||||
slist += 'server '
|
||||
slist += x['ip'] + ':' + x['port']
|
||||
|
||||
if x['state'] == '0':
|
||||
slist += ' down;\n\t'
|
||||
continue
|
||||
|
||||
if x['state'] == '2':
|
||||
slist += ' backup;\n\t'
|
||||
continue
|
||||
|
||||
slist += ' weight=' + x['weight']
|
||||
slist += ' max_fails=' + x['max_fails']
|
||||
slist += ' fail_timeout=' + x['fail_timeout'] + "s;\n\t"
|
||||
return slist
|
||||
|
||||
|
||||
def makeLoadBalanceAllCfg(row):
|
||||
# 生成所有配置
|
||||
cfg = getConf()
|
||||
|
||||
upstream_dir = mw.getServerDir() + '/web_conf/nginx/upstream'
|
||||
rewrite_dir = mw.getServerDir() + '/web_conf/nginx/rewrite'
|
||||
vhost_dir = mw.getServerDir() + '/web_conf/nginx/vhost'
|
||||
upstream_tpl = getPluginDir() + '/conf/upstream.tpl.conf'
|
||||
rewrite_tpl = getPluginDir() + '/conf/rewrite.tpl.conf'
|
||||
|
||||
if not os.path.exists(upstream_dir):
|
||||
os.makedirs(upstream_dir)
|
||||
|
||||
conf = cfg[row]
|
||||
|
||||
# replace vhost start
|
||||
vhost_file = vhost_dir + '/' + conf['domain'] + '.conf'
|
||||
vcontent = mw.readFile(vhost_file)
|
||||
|
||||
vhost_find_str = 'upstream/' + conf['upstream_name'] + '.conf'
|
||||
vhead = 'include ' + mw.getServerDir() + '/web_conf/nginx/' + \
|
||||
vhost_find_str + ';'
|
||||
|
||||
vpos = vcontent.find(vhost_find_str)
|
||||
if vpos < 0:
|
||||
vcontent = vhead + "\n" + vcontent
|
||||
mw.writeFile(vhost_file, vcontent)
|
||||
# replace vhost end
|
||||
|
||||
# make upstream start
|
||||
upstream_file = upstream_dir + '/' + conf['upstream_name'] + '.conf'
|
||||
content = ''
|
||||
if len(conf['node_list']) > 0:
|
||||
content = mw.readFile(upstream_tpl)
|
||||
slist = makeConfServerList(conf['node_list'])
|
||||
content = content.replace('{$NODE_SERVER_LIST}', slist)
|
||||
content = content.replace('{$UPSTREAM_NAME}', conf['upstream_name'])
|
||||
if conf['node_algo'] != 'polling':
|
||||
content = content.replace('{$NODE_ALGO}', conf['node_algo'] + ';')
|
||||
else:
|
||||
content = content.replace('{$NODE_ALGO}', '')
|
||||
mw.writeFile(upstream_file, content)
|
||||
# make upstream end
|
||||
|
||||
# make rewrite start
|
||||
rewrite_file = rewrite_dir + '/' + conf['domain'] + '.conf'
|
||||
rcontent = ''
|
||||
if len(conf['node_list']) > 0:
|
||||
rcontent = mw.readFile(rewrite_tpl)
|
||||
rcontent = rcontent.replace('{$UPSTREAM_NAME}', conf['upstream_name'])
|
||||
mw.writeFile(rewrite_file, rcontent)
|
||||
# make rewrite end
|
||||
|
||||
# health check start
|
||||
lua_dir = mw.getServerDir() + '/web_conf/nginx/lua/init_worker_by_lua_file'
|
||||
lua_init_worker_file = lua_dir + '/' + conf['upstream_name'] + '.lua'
|
||||
if conf['node_health_check'] == 'ok':
|
||||
lua_dir_tpl = getPluginDir() + '/lua/health_check.lua.tpl'
|
||||
content = mw.readFile(lua_dir_tpl)
|
||||
content = content.replace('{$UPSTREAM_NAME}', conf['upstream_name'])
|
||||
content = content.replace('{$DOMAIN}', conf['domain'])
|
||||
mw.writeFile(lua_init_worker_file, content)
|
||||
else:
|
||||
if os.path.exists(lua_init_worker_file):
|
||||
os.remove(lua_init_worker_file)
|
||||
|
||||
mw.opLuaInitWorkerFile()
|
||||
# health check end
|
||||
return True
|
||||
|
||||
|
||||
def add_load_balance(args):
|
||||
|
||||
data = checkArgs(
|
||||
args, ['domain', 'upstream_name', 'node_algo', 'node_list', 'node_health_check'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
domain_json = args['domain']
|
||||
|
||||
tmp = json.loads(domain_json)
|
||||
domain = tmp['domain']
|
||||
|
||||
cfg = getConf()
|
||||
cfg_len = len(cfg)
|
||||
tmp = {}
|
||||
tmp['domain'] = domain
|
||||
tmp['data'] = args['domain']
|
||||
tmp['upstream_name'] = args['upstream_name']
|
||||
tmp['node_algo'] = args['node_algo']
|
||||
tmp['node_list'] = args['node_list']
|
||||
tmp['node_health_check'] = args['node_health_check']
|
||||
cfg.append(tmp)
|
||||
writeConf(cfg)
|
||||
|
||||
import site_api
|
||||
sobj = site_api.site_api()
|
||||
domain_path = mw.getWwwDir() + '/' + domain
|
||||
|
||||
ps = '负载均衡[' + domain + ']'
|
||||
data = sobj.add(domain_json, '80', ps, domain_path, '00')
|
||||
|
||||
makeLoadBalanceAllCfg(cfg_len)
|
||||
mw.restartWeb()
|
||||
return mw.returnJson(True, '添加成功', data)
|
||||
|
||||
|
||||
def edit_load_balance(args):
|
||||
data = checkArgs(
|
||||
args, ['row', 'node_algo', 'node_list', 'node_health_check'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
row = int(args['row'])
|
||||
|
||||
cfg = getConf()
|
||||
tmp = cfg[row]
|
||||
tmp['node_algo'] = args['node_algo']
|
||||
tmp['node_list'] = args['node_list']
|
||||
tmp['node_health_check'] = args['node_health_check']
|
||||
cfg[row] = tmp
|
||||
writeConf(cfg)
|
||||
|
||||
makeLoadBalanceAllCfg(row)
|
||||
mw.restartWeb()
|
||||
return mw.returnJson(True, '修改成功', data)
|
||||
|
||||
|
||||
def loadBalanceList():
|
||||
cfg = getConf()
|
||||
return mw.returnJson(True, 'ok', cfg)
|
||||
|
||||
|
||||
def loadBalanceDelete():
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['row'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
row = int(args['row'])
|
||||
|
||||
cfg = getConf()
|
||||
data = cfg[row]
|
||||
|
||||
import site_api
|
||||
sobj = site_api.site_api()
|
||||
|
||||
sid = mw.M('sites').where('name=?', (data['domain'],)).getField('id')
|
||||
|
||||
if type(sid) == list:
|
||||
del(cfg[row])
|
||||
writeConf(cfg)
|
||||
return mw.returnJson(False, '已经删除了!')
|
||||
|
||||
status = sobj.delete(sid, data['domain'], 1)
|
||||
status_data = json.loads(status)
|
||||
|
||||
if status_data['status']:
|
||||
del(cfg[row])
|
||||
writeConf(cfg)
|
||||
|
||||
upstream_dir = mw.getServerDir() + '/web_conf/nginx/upstream'
|
||||
rewrite_dir = mw.getServerDir() + '/web_conf/nginx/rewrite'
|
||||
|
||||
upstream_file = upstream_dir + '/' + data['upstream_name'] + '.conf'
|
||||
if os.path.exists(upstream_file):
|
||||
os.remove(upstream_file)
|
||||
|
||||
rewrite_file = rewrite_dir + '/' + data['domain'] + '.conf'
|
||||
if os.path.exists(rewrite_file):
|
||||
mw.writeFile(rewrite_file, '')
|
||||
|
||||
return mw.returnJson(status_data['status'], status_data['msg'])
|
||||
|
||||
|
||||
def http_get(url):
|
||||
ret = re.search(r'https://', url)
|
||||
if ret:
|
||||
try:
|
||||
from gevent import monkey
|
||||
monkey.patch_ssl()
|
||||
import requests
|
||||
ret = requests.get(url=str(url), verify=False, timeout=10)
|
||||
status = [200, 301, 302, 404, 403]
|
||||
if ret.status_code in status:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
except:
|
||||
return False
|
||||
else:
|
||||
try:
|
||||
if sys.version_info[0] == 2:
|
||||
import urllib2
|
||||
rec = urllib2.urlopen(url, timeout=3)
|
||||
else:
|
||||
import urllib.request
|
||||
rec = urllib.request.urlopen(url, timeout=3)
|
||||
status = [200, 301, 302, 404, 403]
|
||||
if rec.getcode() in status:
|
||||
return True
|
||||
return False
|
||||
except:
|
||||
return False
|
||||
|
||||
|
||||
def checkUrl():
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['ip', 'port', 'path'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
ip = args['ip']
|
||||
port = args['port']
|
||||
path = args['path']
|
||||
|
||||
if port == '443':
|
||||
url = 'https://' + str(ip) + ':' + str(port) + str(path.strip())
|
||||
else:
|
||||
url = 'http://' + str(ip) + ':' + str(port) + str(path.strip())
|
||||
ret = http_get(url)
|
||||
if not ret:
|
||||
return mw.returnJson(False, '访问节点[%s]失败' % url)
|
||||
return mw.returnJson(True, '访问节点[%s]成功' % url)
|
||||
|
||||
|
||||
def getHealthStatus():
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['row'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
row = int(args['row'])
|
||||
|
||||
cfg = getConf()
|
||||
data = cfg[row]
|
||||
|
||||
url = 'http://' + data['domain'] + \
|
||||
'/upstream_status_' + data['upstream_name']
|
||||
|
||||
url_data = mw.httpGet(url)
|
||||
return mw.returnJson(True, 'ok', json.loads(url_data))
|
||||
|
||||
|
||||
def getLogs():
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['domain'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
domain = args['domain']
|
||||
logs = mw.getLogsDir() + '/' + domain + '.log'
|
||||
return logs
|
||||
|
||||
if __name__ == "__main__":
|
||||
func = sys.argv[1]
|
||||
if func == 'status':
|
||||
print(status())
|
||||
elif func == 'start':
|
||||
print(start())
|
||||
elif func == 'stop':
|
||||
print(stop())
|
||||
elif func == 'restart':
|
||||
print(restart())
|
||||
elif func == 'reload':
|
||||
print(reload())
|
||||
elif func == 'install_pre_inspection':
|
||||
print(installPreInspection())
|
||||
elif func == 'add_load_balance':
|
||||
print(addLoadBalance())
|
||||
elif func == 'load_balance_list':
|
||||
print(loadBalanceList())
|
||||
elif func == 'load_balance_delete':
|
||||
print(loadBalanceDelete())
|
||||
elif func == 'check_url':
|
||||
print(checkUrl())
|
||||
elif func == 'get_logs':
|
||||
print(getLogs())
|
||||
elif func == 'get_health_status':
|
||||
print(getHealthStatus())
|
||||
else:
|
||||
print('error')
|
||||
Executable
+16
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"title":"OP负载均衡",
|
||||
"tip":"soft",
|
||||
"name":"op_load_balance",
|
||||
"type":"其他插件",
|
||||
"install_pre_inspection":true,
|
||||
"ps":"基于OpenResty的负载均衡",
|
||||
"shell":"install.sh",
|
||||
"checks":"server/op_load_balance",
|
||||
"path":"server/op_load_balance",
|
||||
"author":"midoks",
|
||||
"home":"https://github.com/midoks",
|
||||
"date":"2023-02-02",
|
||||
"pid": "1",
|
||||
"versions": ["1.0"]
|
||||
}
|
||||
Executable
+45
@@ -0,0 +1,45 @@
|
||||
#!/bin/bash
|
||||
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
|
||||
export PATH
|
||||
|
||||
curPath=`pwd`
|
||||
rootPath=$(dirname "$curPath")
|
||||
rootPath=$(dirname "$rootPath")
|
||||
serverPath=$(dirname "$rootPath")
|
||||
|
||||
install_tmp=${rootPath}/tmp/mw_install.pl
|
||||
|
||||
action=$1
|
||||
version=$2
|
||||
sys_os=`uname`
|
||||
|
||||
if [ -f ${rootPath}/bin/activate ];then
|
||||
source ${rootPath}/bin/activate
|
||||
fi
|
||||
|
||||
if [ "$sys_os" == "Darwin" ];then
|
||||
BAK='_bak'
|
||||
else
|
||||
BAK=''
|
||||
fi
|
||||
|
||||
Install_App(){
|
||||
echo '正在安装脚本文件...' > $install_tmp
|
||||
mkdir -p $serverPath/op_load_balance
|
||||
echo "${version}" > $serverPath/op_load_balance/version.pl
|
||||
cd ${rootPath} && python3 ${rootPath}/plugins/op_load_balance/index.py start
|
||||
echo 'install ok' > $install_tmp
|
||||
}
|
||||
|
||||
Uninstall_App(){
|
||||
cd ${rootPath} && python3 ${rootPath}/plugins/op_load_balance/index.py stop
|
||||
rm -rf $serverPath/op_load_balance
|
||||
}
|
||||
|
||||
|
||||
action=$1
|
||||
if [ "${1}" == 'install' ];then
|
||||
Install_App
|
||||
else
|
||||
Uninstall_App
|
||||
fi
|
||||
@@ -0,0 +1,606 @@
|
||||
function ooPost(method,args,callback){
|
||||
var _args = null;
|
||||
if (typeof(args) == 'string'){
|
||||
_args = JSON.stringify(toArrayObject(args));
|
||||
} else {
|
||||
_args = JSON.stringify(args);
|
||||
}
|
||||
|
||||
var loadT = layer.msg('正在获取...', { icon: 16, time: 0, shade: 0.3 });
|
||||
$.post('/plugins/run', {name:'op_load_balance', func:method, args:_args}, function(data) {
|
||||
layer.close(loadT);
|
||||
if (!data.status){
|
||||
layer.msg(data.msg,{icon:0,time:2000,shade: [0.3, '#000']});
|
||||
return;
|
||||
}
|
||||
|
||||
if(typeof(callback) == 'function'){
|
||||
callback(data);
|
||||
}
|
||||
},'json');
|
||||
}
|
||||
|
||||
function ooAsyncPost(method,args){
|
||||
var _args = null;
|
||||
if (typeof(args) == 'string'){
|
||||
_args = JSON.stringify(toArrayObject(args));
|
||||
} else {
|
||||
_args = JSON.stringify(args);
|
||||
}
|
||||
return syncPost('/plugins/run', {name:'op_load_balance', func:method, args:_args});
|
||||
}
|
||||
|
||||
function ooPostCallbak(method, args, callback){
|
||||
var loadT = layer.msg('正在获取...', { icon: 16, time: 0, shade: 0.3 });
|
||||
|
||||
var req_data = {};
|
||||
req_data['name'] = 'op_load_balance';
|
||||
req_data['func'] = method;
|
||||
args['version'] = '1.0';
|
||||
|
||||
if (typeof(args) == 'string'){
|
||||
req_data['args'] = JSON.stringify(toArrayObject(args));
|
||||
} else {
|
||||
req_data['args'] = JSON.stringify(args);
|
||||
}
|
||||
|
||||
$.post('/plugins/callback', req_data, function(data) {
|
||||
layer.close(loadT);
|
||||
if (!data.status){
|
||||
layer.msg(data.msg,{icon:0,time:2000,shade: [0.3, '#000']});
|
||||
return;
|
||||
}
|
||||
|
||||
if(typeof(callback) == 'function'){
|
||||
callback(data);
|
||||
}
|
||||
},'json');
|
||||
}
|
||||
|
||||
function addNode(){
|
||||
layer.open({
|
||||
type: 1,
|
||||
area: ['450px','580px'],
|
||||
title: '添加节点',
|
||||
closeBtn: 1,
|
||||
shift: 5,
|
||||
shadeClose: true,
|
||||
btn:['提交','关闭'],
|
||||
content: "<form class='bt-form pd20'>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>IP地址</span>\
|
||||
<div class='info-r'>\
|
||||
<input name='ip' class='bt-input-text mr5' placeholder='负载名称,可以是英文字母和下划线,不能使用中文' type='text' style='width:250px' value='127.0.0.1'>\
|
||||
</div>\
|
||||
</div>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>端口</span>\
|
||||
<div class='info-r'>\
|
||||
<input name='port' class='bt-input-text mr5' type='text' style='width:250px' value='80'>\
|
||||
</div>\
|
||||
</div>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>验证文件路径</span>\
|
||||
<div class='info-r'>\
|
||||
<input name='path' class='bt-input-text mr5' type='text' style='width:250px' value='/'>\
|
||||
</div>\
|
||||
</div>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>节点状态</span>\
|
||||
<div class='info-r'>\
|
||||
<select name='state'>\
|
||||
<option value='1'>参与者</option>\
|
||||
<option value='2'>备份</option>\
|
||||
<option value='0'>停用</option>\
|
||||
</select>\
|
||||
</div>\
|
||||
</div>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>权重</span>\
|
||||
<div class='info-r'>\
|
||||
<input name='weight' class='bt-input-text mr5' type='text' style='width:250px' value='1'>\
|
||||
</div>\
|
||||
</div>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>阈值</span>\
|
||||
<div class='info-r'>\
|
||||
<input name='max_fails' class='bt-input-text mr5' type='text' style='width:250px' value='2'>次\
|
||||
</div>\
|
||||
</div>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>恢复时间</span>\
|
||||
<div class='info-r'>\
|
||||
<input name='fail_timeout' class='bt-input-text mr5' type='text' style='width:250px' value='10'>秒\
|
||||
</div>\
|
||||
</div>\
|
||||
<ul style='margin-left:10px' class='help-info-text c7'>\
|
||||
<li>备份状态: 指当其它节点都无法使用时才会使用此节点</li>\
|
||||
<li>参与状态: 正常参与负载均衡,请至少添加1个普通节点</li>\
|
||||
<li>验证文件路径: 用于检查文件路径地址是否可用</li>\
|
||||
<li>IP地址: 仅支持IP地址,否则无法正常参与负载均衡</li>\
|
||||
<li>阈值: 在恢复时间的时间段内,如果OpenResty与节点通信尝试失败的次数达到此值,OpenResty就认为服务器不可用</li>\
|
||||
</ul>\
|
||||
</form>",
|
||||
success:function(){
|
||||
},
|
||||
yes:function(index) {
|
||||
|
||||
var ip = $('input[name="ip"]').val();
|
||||
var port = $('input[name="port"]').val();
|
||||
var path = $('input[name="path"]').val();
|
||||
var state = $('select[name="state"]').val();
|
||||
var weight = $('input[name="weight"]').val();
|
||||
var max_fails = $('input[name="max_fails"]').val();
|
||||
var fail_timeout = $('input[name="fail_timeout"]').val();
|
||||
|
||||
ooPost('check_url', {ip:ip,port:port,path:path},function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
showMsg(rdata.msg, function(){
|
||||
if (rdata.status){
|
||||
layer.close(index);
|
||||
$('#nodecon .nulltr').hide();
|
||||
|
||||
var tbody = '<tr>';
|
||||
tbody +='<td>'+ip+'</td>';
|
||||
tbody +='<td>'+port+'</td>';
|
||||
tbody +='<td>'+path+'</td>';
|
||||
|
||||
tbody +="<td><select name='state'>";
|
||||
var state_option_list = {
|
||||
'1':'参与者',
|
||||
'2':'备份',
|
||||
'0':'停用',
|
||||
}
|
||||
for (i in state_option_list) {
|
||||
if (i == state){
|
||||
tbody +="<option value='"+i+"' selected>"+state_option_list[i]+"</option>";
|
||||
} else{
|
||||
tbody +="<option value='"+i+"'>"+state_option_list[i]+"</option>";
|
||||
}
|
||||
}
|
||||
tbody +="</select></td>";
|
||||
|
||||
tbody +='<td><input type="number" name="weight" value="'+weight+'" style="width:50px"></td>';
|
||||
tbody +='<td><input type="number" name="max_fails" value="'+max_fails+'" style="width:50px"></td>';
|
||||
tbody +='<td><input type="number" name="fail_timeout" value="'+fail_timeout+'" style="width:50px"></td>';
|
||||
tbody +='<td class="text-right" width="50"><a class="btlink minus delete">删除</a></td>';
|
||||
tbody += '</tr>';
|
||||
$('#nodecon').append(tbody);
|
||||
|
||||
$('#nodecon .delete').click(function(){
|
||||
$(this).parent().parent().remove();
|
||||
if ($('#nodecon tr').length == 1 ){
|
||||
$('#nodecon .nulltr').show();
|
||||
}
|
||||
});
|
||||
}
|
||||
},{ icon: rdata.status ? 1 : 2 }, 2000);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function addBalance(){
|
||||
layer.open({
|
||||
type: 1,
|
||||
area: ['750px','460px'],
|
||||
title: '创建负载',
|
||||
closeBtn: 1,
|
||||
shift: 5,
|
||||
shadeClose: true,
|
||||
btn:['提交','关闭'],
|
||||
content: "<form class='bt-form pd20'>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>域名</span>\
|
||||
<div class='info-r'><textarea name='load_domain' class='bt-input-text mr5' placeholder='' style='width:95%;resize: none;height:90px;line-height:20px;'></textarea></div>\
|
||||
</div>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>负载名称</span>\
|
||||
<div class='info-r'>\
|
||||
<input name='upstream_name' class='bt-input-text mr5' placeholder='负载名称,可以是英文字母和下划线,不能使用中文' type='text' style='width:95%' value=''>\
|
||||
</div>\
|
||||
</div>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>节点调度</span>\
|
||||
<div class='info-r'>\
|
||||
<select name='node_algo'>\
|
||||
<option value='polling'>轮询[默认]</option>\
|
||||
<option value='ip_hash'>ip_hash</option>\
|
||||
<option value='fair'>fair</option>\
|
||||
<option value='url_hash'>url_hash</option>\
|
||||
<option value='least_conn'>least_conn</option>\
|
||||
</select>\
|
||||
</div>\
|
||||
</div>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>节点健康检查</span>\
|
||||
<div class='info-r'>\
|
||||
<input type='checkbox' name='node_health_check' checked>\
|
||||
</div>\
|
||||
</div>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>节点</span>\
|
||||
<div class='info-r'>\
|
||||
<div class='table-con divtable' style='max-height:120px;overflow:auto; margin-bottom:8px;width:95%'>\
|
||||
<table class='table table-hover' id='fixTable3'>\
|
||||
<thead>\
|
||||
<tr>\
|
||||
<th width='120'>IP地址</th>\
|
||||
<th width='60'>端口</th>\
|
||||
<th width='120'>验证路径</th>\
|
||||
<th width='60'>状态</th>\
|
||||
<th width='60'>权重</th>\
|
||||
<th width='60'>阀值</th>\
|
||||
<th width='120'>恢复时间</th>\
|
||||
<th width='80' class='text-right'>操作</th>\
|
||||
</tr>\
|
||||
</thead>\
|
||||
<tbody id='nodecon'>\
|
||||
<tr class='nulltr'>\
|
||||
<td colspan='8' align='center'>当前节点为空,请至少添加一个普通节点</td>\
|
||||
</tr>\
|
||||
</tbody>\
|
||||
</table>\
|
||||
</div>\
|
||||
<span class='btn btn-success btn-sm add_node' style='vertical-align:0'>添加节点</span>\
|
||||
</div>\
|
||||
</div>\
|
||||
</form>",
|
||||
success:function(){
|
||||
$('textarea[name="load_domain"]').attr('placeholder','每行填写一个域名,默认为80端口。\n泛解析添加方法 *.domain.com\n如另加端口格式为 www.domain.com:88');
|
||||
var rval = getRandomString(6);
|
||||
$('input[name="upstream_name"]').val('load_balance_'+rval);
|
||||
|
||||
$('.add_node').click(function(){
|
||||
addNode();
|
||||
});
|
||||
},
|
||||
yes:function(index) {
|
||||
var data = {};
|
||||
|
||||
var upstream_name = $('input[name="upstream_name"]').val();
|
||||
if (upstream_name == ''){
|
||||
layer.msg('负载名称不能为空!',{icon:0,time:2000,shade: [0.3, '#000']});
|
||||
return;
|
||||
}
|
||||
|
||||
var domain = $('textarea[name="load_domain"]').val().replace('http://','').replace('https://','').split("\n");
|
||||
if (domain[0] == ''){
|
||||
layer.msg('域名不能为空!',{icon:0,time:2000,shade: [0.3, '#000']});
|
||||
return;
|
||||
}
|
||||
|
||||
var domainlist = '';
|
||||
for(var i=1; i<domain.length; i++){
|
||||
domainlist += '"'+domain[i]+'",';
|
||||
}
|
||||
domain ='{"domain":"'+domain[0]+'","domainlist":['+domainlist+'],"count":'+domain.length+'}';//拼接json
|
||||
data['domain'] = domain;
|
||||
data['upstream_name'] = upstream_name;
|
||||
|
||||
data['node_algo'] = $('select[name="node_algo"]').val();
|
||||
|
||||
data['node_health_check'] = 'fail';
|
||||
if ($('input[name="node_health_check"]').prop('checked')){
|
||||
data['node_health_check'] = 'ok';
|
||||
}
|
||||
|
||||
var node_list = [];
|
||||
$('#nodecon tr').each(function(){
|
||||
|
||||
var ip = $(this).find('td').eq(0).text();
|
||||
var port = $(this).find('td').eq(1).text();
|
||||
|
||||
if (port == ''){return;}
|
||||
|
||||
var path = $(this).find('td').eq(2).text();
|
||||
var state = $(this).find('select[name="state"]').val();
|
||||
var weight = $(this).find('input[name="weight"]').val();
|
||||
var max_fails = $(this).find('input[name="max_fails"]').val();
|
||||
var fail_timeout = $(this).find('input[name="fail_timeout"]').val();
|
||||
|
||||
var tmp = {
|
||||
ip:ip,
|
||||
port:port,
|
||||
path:path,
|
||||
state:state,
|
||||
weight:weight,
|
||||
max_fails:max_fails,
|
||||
fail_timeout:fail_timeout,
|
||||
}
|
||||
node_list.push(tmp);
|
||||
});
|
||||
data['node_list'] = node_list;
|
||||
ooPostCallbak('add_load_balance', data, function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
showMsg(rdata.msg, function(){
|
||||
layer.close(index);
|
||||
loadBalanceListRender();
|
||||
},{ icon: rdata.status ? 1 : 2 }, 2000);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function editBalance(data, row){
|
||||
layer.open({
|
||||
type: 1,
|
||||
area: ['750px','400px'],
|
||||
title: '编辑负载',
|
||||
closeBtn: 1,
|
||||
shift: 5,
|
||||
shadeClose: true,
|
||||
btn:['提交','关闭'],
|
||||
content: "<form class='bt-form pd20'>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>负载名称</span>\
|
||||
<div class='info-r'><input name='upstream_name' class='bt-input-text mr5' type='text' style='width:95%;background: rgb(238, 238, 238);' value='' readonly></div>\
|
||||
</div>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>节点调度</span>\
|
||||
<div class='info-r'>\
|
||||
<select name='node_algo'>\
|
||||
<option value='polling'>轮询[默认]</option>\
|
||||
<option value='ip_hash'>ip_hash</option>\
|
||||
<option value='fair'>fair</option>\
|
||||
<option value='url_hash'>url_hash</option>\
|
||||
<option value='least_conn'>least_conn</option>\
|
||||
</select>\
|
||||
</div>\
|
||||
</div>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>节点健康检查</span>\
|
||||
<div class='info-r'>\
|
||||
<input type='checkbox' name='node_health_check'>\
|
||||
</div>\
|
||||
</div>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>节点</span>\
|
||||
<div class='info-r'>\
|
||||
<div class='table-con divtable' style='max-height:120px;overflow:auto; margin-bottom:8px;width:95%'>\
|
||||
<table class='table table-hover' id='fixTable3'>\
|
||||
<thead>\
|
||||
<tr>\
|
||||
<th width='120'>IP地址</th>\
|
||||
<th width='60'>端口</th>\
|
||||
<th width='120'>验证路径</th>\
|
||||
<th width='60'>状态</th>\
|
||||
<th width='60'>权重</th>\
|
||||
<th width='60'>阀值</th>\
|
||||
<th width='120'>恢复时间</th>\
|
||||
<th width='80' class='text-right'>操作</th>\
|
||||
</tr>\
|
||||
</thead>\
|
||||
<tbody id='nodecon'>\
|
||||
<tr class='nulltr'>\
|
||||
<td colspan='8' align='center'>当前节点为空,请至少添加一个普通节点</td>\
|
||||
</tr>\
|
||||
</tbody>\
|
||||
</table>\
|
||||
</div>\
|
||||
<span class='btn btn-success btn-sm add_node' style='vertical-align:0'>添加节点</span>\
|
||||
</div>\
|
||||
</div>\
|
||||
</form>",
|
||||
success:function(){
|
||||
$('input[name="upstream_name"]').val(data['upstream_name']);
|
||||
$('select[name="node_algo"]').val(data['node_algo']);
|
||||
|
||||
$('input[name="node_health_check"]').prop('checked',false);
|
||||
if (data['node_health_check'] == 'ok'){
|
||||
$('input[name="node_health_check"]').prop('checked',true);
|
||||
}
|
||||
|
||||
var node_list = data['node_list'];
|
||||
if (node_list.length>0){
|
||||
$('#nodecon .nulltr').hide();
|
||||
}
|
||||
|
||||
var state_option_list = {
|
||||
'1':'参与者',
|
||||
'2':'备份',
|
||||
'0':'停用',
|
||||
}
|
||||
|
||||
for (var n in node_list) {
|
||||
|
||||
var tbody = '<tr>';
|
||||
tbody +='<td>'+node_list[n]['ip']+'</td>';
|
||||
tbody +='<td>'+node_list[n]['port']+'</td>';
|
||||
tbody +='<td>'+node_list[n]['path']+'</td>';
|
||||
|
||||
tbody +="<td><select name='state'>";
|
||||
|
||||
for (i in state_option_list) {
|
||||
if (i == node_list[n]['state']){
|
||||
tbody +="<option value='"+i+"' selected>"+state_option_list[i]+"</option>";
|
||||
} else{
|
||||
tbody +="<option value='"+i+"'>"+state_option_list[i]+"</option>";
|
||||
}
|
||||
}
|
||||
tbody +="</select></td>";
|
||||
|
||||
tbody +='<td><input type="number" name="weight" value="'+node_list[n]['weight']+'" style="width:50px"></td>';
|
||||
tbody +='<td><input type="number" name="max_fails" value="'+node_list[n]['max_fails']+'" style="width:50px"></td>';
|
||||
tbody +='<td><input type="number" name="fail_timeout" value="'+node_list[n]['fail_timeout']+'" style="width:50px"></td>';
|
||||
tbody +='<td class="text-right" width="50"><a class="btlink minus delete">删除</a></td>';
|
||||
tbody += '</tr>';
|
||||
$('#nodecon').append(tbody);
|
||||
}
|
||||
|
||||
$('#nodecon .delete').click(function(){
|
||||
$(this).parent().parent().remove();
|
||||
if ($('#nodecon tr').length == 1 ){
|
||||
$('#nodecon .nulltr').show();
|
||||
}
|
||||
});
|
||||
|
||||
$('.add_node').click(function(){
|
||||
addNode();
|
||||
});
|
||||
},
|
||||
yes:function(index) {
|
||||
var data = {};
|
||||
|
||||
data['node_algo'] = $('select[name="node_algo"]').val();
|
||||
data['node_health_check'] = 'fail';
|
||||
if ($('input[name="node_health_check"]').prop('checked')){
|
||||
data['node_health_check'] = 'ok';
|
||||
}
|
||||
|
||||
var node_list = [];
|
||||
$('#nodecon tr').each(function(){
|
||||
|
||||
var ip = $(this).find('td').eq(0).text();
|
||||
var port = $(this).find('td').eq(1).text();
|
||||
|
||||
if (port == ''){return;}
|
||||
|
||||
var path = $(this).find('td').eq(2).text();
|
||||
var state = $(this).find('select[name="state"]').val();
|
||||
var weight = $(this).find('input[name="weight"]').val();
|
||||
var max_fails = $(this).find('input[name="max_fails"]').val();
|
||||
var fail_timeout = $(this).find('input[name="fail_timeout"]').val();
|
||||
|
||||
var tmp = {
|
||||
ip:ip,
|
||||
port:port,
|
||||
path:path,
|
||||
state:state,
|
||||
weight:weight,
|
||||
max_fails:max_fails,
|
||||
fail_timeout:fail_timeout,
|
||||
}
|
||||
node_list.push(tmp);
|
||||
});
|
||||
data['node_list'] = node_list;
|
||||
data['row'] = row;
|
||||
ooPostCallbak('edit_load_balance', data, function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
showMsg(rdata.msg, function(){
|
||||
layer.close(index);
|
||||
loadBalanceListRender();
|
||||
},{ icon: rdata.status ? 1 : 2 }, 2000);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function loadBalanceListRender(){
|
||||
ooPost('load_balance_list', {}, function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
var alist = rdata.data;
|
||||
|
||||
var tbody = '';
|
||||
for (var i = 0; i < alist.length; i++) {
|
||||
tbody += '<tr>';
|
||||
tbody += '<td>'+alist[i]['domain']+'</td>';
|
||||
tbody += '<td>'+alist[i]['upstream_name']+'</td>';
|
||||
tbody += '<td>'+alist[i]['node_list'].length+'</td>';
|
||||
tbody += '<td><a class="btlink log_look" data-row="'+i+'">查看</a></td>';
|
||||
tbody += '<td><a class="btlink health_status" data-row="'+i+'">查看</a></td>';
|
||||
tbody += '<td style="text-align: right;"><a class="btlink edit" data-row="'+i+'">修改</a> | <a class="btlink delete" data-row="'+i+'">删除</a></td>';
|
||||
tbody += '</tr>';
|
||||
}
|
||||
|
||||
$('#nodeTable').html(tbody);
|
||||
$('.nodeTablePage .Pcount').text('共'+alist.length+'条');
|
||||
$('#nodeTable .edit').click(function(){
|
||||
var row = $(this).data('row');
|
||||
editBalance(alist[row],row);
|
||||
});
|
||||
|
||||
$('#nodeTable .log_look').click(function(){
|
||||
var row = $(this).data('row');
|
||||
var args = {'domain':alist[row]['domain']};
|
||||
pluginRollingLogs('op_load_balance','','get_logs',JSON.stringify(args),20);
|
||||
});
|
||||
|
||||
$('#nodeTable .health_status').click(function(){
|
||||
var row = $(this).data('row');
|
||||
ooPost('get_health_status', {row:row}, function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
|
||||
var tval = '';
|
||||
for (var i = 0; i < rdata.data.length; i++) {
|
||||
tval += '<tr>';
|
||||
tval += '<td>'+rdata.data[i]['name']+'</td>';
|
||||
|
||||
if (typeof(rdata.data[i]['down']) != 'undefined' && rdata.data[i]['down']){
|
||||
tval += '<td><span style="color:red;">不正常</span></td>';
|
||||
} else{
|
||||
tval += '<td><span class="btlink">正常</span></td>';
|
||||
}
|
||||
tval += '</tr>';
|
||||
}
|
||||
|
||||
var tbody = "<div class='bt-form pd20'>\
|
||||
<div>\
|
||||
<div id='gitea_table' class='divtable' style='margin-top:5px;'>\
|
||||
<table class='table table-hover'>\
|
||||
<thead>\
|
||||
<tr>\
|
||||
<th width='120'>地址</th>\
|
||||
<th width='60'>状态</th>\
|
||||
</tr>\
|
||||
</thead>\
|
||||
<tbody>"+tval+"</tbody>\
|
||||
</table>\
|
||||
</div>\
|
||||
</div>\
|
||||
</div>";
|
||||
|
||||
layer.open({
|
||||
type: 1,
|
||||
area: ['500px','300px'],
|
||||
title: '节点状态',
|
||||
closeBtn: 1,
|
||||
shift: 5,
|
||||
shadeClose: true,
|
||||
btn:['提交','关闭'],
|
||||
content:tbody,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
$('#nodeTable .delete').click(function(){
|
||||
var row = $(this).data('row');
|
||||
ooPost('load_balance_delete', {row:row}, function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
showMsg(rdata.msg, function(){
|
||||
loadBalanceListRender();
|
||||
},{ icon: rdata.status ? 1 : 2 }, 2000);
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
function loadBalanceList() {
|
||||
var body = '<div class="bt-box active" style="display: block;">\
|
||||
<div class="mb10">\
|
||||
<button class="btn btn-success btn-sm" data-index="0" onclick="addBalance()">添加负载</button>\
|
||||
<div class="divtable mt10">\
|
||||
<table class="table table-hover">\
|
||||
<thead>\
|
||||
<tr>\
|
||||
<th>网站</th>\
|
||||
<th>负载名称</th>\
|
||||
<th>节点</th>\
|
||||
<th>日志</th>\
|
||||
<th>状态</th>\
|
||||
<th width="100" style="text-align: right;">操作</th>\
|
||||
</tr>\
|
||||
</thead>\
|
||||
<tbody id="nodeTable"></tbody>\
|
||||
</table>\
|
||||
<div class="nodeTablePage page" data-type="nodePage">\
|
||||
<div><span class="Pcount">共0条</span></div>\
|
||||
</div>\
|
||||
</div>\
|
||||
</div>\
|
||||
</div>\
|
||||
</div>';
|
||||
$(".soft-man-con").html(body);
|
||||
loadBalanceListRender();
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
local hc = require "resty.upstream.healthcheck"
|
||||
local ok, err = hc.spawn_checker {
|
||||
shm = "healthcheck",
|
||||
type = "http",
|
||||
upstream = "{$UPSTREAM_NAME}",
|
||||
http_req = "GET / HTTP/1.0\r\nHost: {$UPSTREAM_NAME}\r\n\r\n",
|
||||
interval = 2000,
|
||||
timeout = 6000,
|
||||
fall = 3,
|
||||
rise = 2,
|
||||
valid_statuses = {200, 302},
|
||||
concurrency = 20,
|
||||
}
|
||||
|
||||
if not ok then
|
||||
ngx.log(ngx.ERR, "=======> load balance health checker error: ", err)
|
||||
return
|
||||
end
|
||||
@@ -7,6 +7,7 @@ Description=The PHP {$VERSION} FastCGI Process Manager
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Environment="LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/www/server/lib/icu/lib"
|
||||
PIDFile={$SERVER_PATH}/php/{$VERSION}/var/run/php-fpm.pid
|
||||
ExecStart={$SERVER_PATH}/php/{$VERSION}/sbin/php-fpm --nodaemonize --fpm-config {$SERVER_PATH}/php/{$VERSION}/etc/php-fpm.conf
|
||||
ExecReload=/bin/kill -USR2 $MAINPID
|
||||
|
||||
@@ -59,6 +59,7 @@ if [ "${action}" == "install" ] && [ -d ${serverPath}/php/${type} ];then
|
||||
echo "install PHP${type} extend start"
|
||||
|
||||
# cd /www/server/mdserver-web/plugins/php/versions/common && bash iconv.sh install 53
|
||||
# cd /www/server/mdserver-web/plugins/php/versions/common && bash intl.sh install 73
|
||||
# cd /www/server/mdserver-web/plugins/php/versions/common && bash gd.sh install 56
|
||||
# cd /www/server/mdserver-web/plugins/php/versions/common && bash openssl.sh install 56
|
||||
# cd /www/server/mdserver-web/plugins/php/versions/common && bash sodium.sh install 81
|
||||
@@ -72,7 +73,6 @@ if [ "${action}" == "install" ] && [ -d ${serverPath}/php/${type} ];then
|
||||
cd ${rootPath}/plugins/php/versions/common && bash gettext.sh install ${type}
|
||||
cd ${rootPath}/plugins/php/versions/common && bash redis.sh install ${type}
|
||||
cd ${rootPath}/plugins/php/versions/common && bash memcached.sh install ${type}
|
||||
cd ${rootPath}/plugins/php/versions/common && bash zlib.sh install ${type}
|
||||
|
||||
if [ "${type}" -gt "72" ];then
|
||||
cd ${rootPath}/plugins/php/versions/common && bash zip.sh install ${type}
|
||||
|
||||
@@ -10,7 +10,6 @@ sourcePath=${serverPath}/source
|
||||
sysName=`uname`
|
||||
install_tmp=${rootPath}/tmp/mw_install.pl
|
||||
|
||||
|
||||
function version_gt() { test "$(echo "$@" | tr " " "\n" | sort -V | head -n 1)" != "$1"; }
|
||||
function version_le() { test "$(echo "$@" | tr " " "\n" | sort -V | head -n 1)" == "$1"; }
|
||||
function version_lt() { test "$(echo "$@" | tr " " "\n" | sort -rV | head -n 1)" != "$1"; }
|
||||
@@ -29,6 +28,12 @@ cd ${rootPath}/plugins/php/lib && /bin/bash freetype_new.sh
|
||||
cd ${rootPath}/plugins/php/lib && /bin/bash zlib.sh
|
||||
cd ${rootPath}/plugins/php/lib && /bin/bash libzip.sh
|
||||
|
||||
# redat ge 8
|
||||
which yum
|
||||
if [ "$?" == "0" ];then
|
||||
cd ${rootPath}/plugins/php/lib && /bin/bash oniguruma.sh
|
||||
fi
|
||||
|
||||
if [ ! -d $sourcePath/php/php${PHP_VER} ];then
|
||||
|
||||
if [ ! -f $sourcePath/php/php-${version}.tar.xz ];then
|
||||
|
||||
@@ -16,7 +16,7 @@ function version_lt() { test "$(echo "$@" | tr " " "\n" | sort -rV | head -n 1)"
|
||||
function version_ge() { test "$(echo "$@" | tr " " "\n" | sort -rV | head -n 1)" == "$1"; }
|
||||
|
||||
|
||||
version=8.0.27
|
||||
version=8.0.29
|
||||
PHP_VER=80
|
||||
Install_php()
|
||||
{
|
||||
@@ -28,6 +28,12 @@ mkdir -p $serverPath/php
|
||||
cd ${rootPath}/plugins/php/lib && /bin/bash freetype_new.sh
|
||||
cd ${rootPath}/plugins/php/lib && /bin/bash zlib.sh
|
||||
|
||||
# redat ge 8
|
||||
which yum
|
||||
if [ "$?" == "0" ];then
|
||||
cd ${rootPath}/plugins/php/lib && /bin/bash oniguruma.sh
|
||||
fi
|
||||
|
||||
if [ ! -d $sourcePath/php/php${PHP_VER} ];then
|
||||
|
||||
if [ ! -f $sourcePath/php/php-${version}.tar.xz ];then
|
||||
|
||||
@@ -16,7 +16,7 @@ function version_lt() { test "$(echo "$@" | tr " " "\n" | sort -rV | head -n 1)"
|
||||
function version_ge() { test "$(echo "$@" | tr " " "\n" | sort -rV | head -n 1)" == "$1"; }
|
||||
|
||||
|
||||
version=8.1.15
|
||||
version=8.1.20
|
||||
PHP_VER=81
|
||||
Install_php()
|
||||
{
|
||||
@@ -28,6 +28,11 @@ mkdir -p $serverPath/php
|
||||
cd ${rootPath}/plugins/php/lib && /bin/bash freetype_new.sh
|
||||
cd ${rootPath}/plugins/php/lib && /bin/bash zlib.sh
|
||||
|
||||
# redat ge 8
|
||||
which yum
|
||||
if [ "$?" == "0" ];then
|
||||
cd ${rootPath}/plugins/php/lib && /bin/bash oniguruma.sh
|
||||
fi
|
||||
|
||||
if [ ! -d $sourcePath/php/php${PHP_VER} ];then
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ function version_lt() { test "$(echo "$@" | tr " " "\n" | sort -rV | head -n 1)"
|
||||
function version_ge() { test "$(echo "$@" | tr " " "\n" | sort -rV | head -n 1)" == "$1"; }
|
||||
|
||||
|
||||
version=8.2.2
|
||||
version=8.2.7
|
||||
PHP_VER=82
|
||||
Install_php()
|
||||
{
|
||||
@@ -28,6 +28,11 @@ mkdir -p $serverPath/php
|
||||
cd ${rootPath}/plugins/php/lib && /bin/bash freetype_new.sh
|
||||
cd ${rootPath}/plugins/php/lib && /bin/bash zlib.sh
|
||||
|
||||
# redat ge 8
|
||||
which yum
|
||||
if [ "$?" == "0" ];then
|
||||
cd ${rootPath}/plugins/php/lib && /bin/bash oniguruma.sh
|
||||
fi
|
||||
|
||||
if [ ! -d $sourcePath/php/php${PHP_VER} ];then
|
||||
|
||||
|
||||
@@ -38,9 +38,10 @@ done
|
||||
|
||||
cd $DIR
|
||||
PHP_VER_LIST=(53 54 55 56 70 71 72 73 74 80 81 82)
|
||||
# yar
|
||||
PHP_EXT_LIST=(ioncube ZendGuardLoader pdo mysqlnd sqlite3 openssl pcntl opcache mcrypt fileinfo \
|
||||
exif gd intl memcache memcached redis imagemagick xdebug xhprof \
|
||||
swoole yaf yar yac apc mongo mongodb solr seaslog mbstring iconv phalcon)
|
||||
swoole yaf yac apc mongo mongodb solr seaslog mbstring iconv phalcon)
|
||||
|
||||
for PHP_VER in ${PHP_VER_LIST[@]}; do
|
||||
echo "php${PHP_VER} -- start"
|
||||
|
||||
@@ -11,9 +11,37 @@ rootPath=$(dirname "$rootPath")
|
||||
serverPath=$(dirname "$rootPath")
|
||||
sourcePath=${serverPath}/source/php
|
||||
|
||||
|
||||
# _os=`uname`
|
||||
|
||||
# if [ ${_os} == "Darwin" ]; then
|
||||
# OSNAME='macos'
|
||||
# elif grep -Eq "openSUSE" /etc/*-release; then
|
||||
# OSNAME='opensuse'
|
||||
# elif grep -Eq "FreeBSD" /etc/*-release; then
|
||||
# OSNAME='freebsd'
|
||||
# elif grep -Eqi "CentOS" /etc/issue || grep -Eqi "CentOS" /etc/*-release; then
|
||||
# OSNAME='rhel'
|
||||
# elif grep -Eqi "Fedora" /etc/issue || grep -Eqi "Fedora" /etc/*-release; then
|
||||
# OSNAME='rhel'
|
||||
# elif grep -Eqi "Rocky" /etc/issue || grep -Eqi "Rocky" /etc/*-release; then
|
||||
# OSNAME='rhel'
|
||||
# elif grep -Eqi "AlmaLinux" /etc/issue || grep -Eqi "AlmaLinux" /etc/*-release; then
|
||||
# OSNAME='rhel'
|
||||
# elif grep -Eqi "Amazon Linux" /etc/issue || grep -Eqi "Amazon Linux" /etc/*-release; then
|
||||
# OSNAME='amazon'
|
||||
# elif grep -Eqi "Debian" /etc/issue || grep -Eqi "Debian" /etc/*-release; then
|
||||
# OSNAME='debian'
|
||||
# elif grep -Eqi "Ubuntu" /etc/issue || grep -Eqi "Ubuntu" /etc/*-release; then
|
||||
# OSNAME='ubuntu'
|
||||
# else
|
||||
# OSNAME='unknow'
|
||||
# fi
|
||||
|
||||
actionType=$1
|
||||
version=$2
|
||||
|
||||
|
||||
LIBNAME=intl
|
||||
LIBV=0
|
||||
|
||||
@@ -33,7 +61,9 @@ else
|
||||
fi
|
||||
|
||||
OPTIONS=''
|
||||
if [ "$version" -lt "71" ];then
|
||||
if [ "$version" -lt "74" ];then
|
||||
|
||||
# cd /www/server/mdserver-web/plugins/php/lib && /bin/bash icu.sh
|
||||
cd ${rootPath}/plugins/php/lib && /bin/bash icu.sh
|
||||
OPTIONS="--with-icu-dir=${serverPath}/lib/icu"
|
||||
fi
|
||||
|
||||
@@ -23,7 +23,7 @@ if [ "$version" -lt "73" ];then
|
||||
fi
|
||||
|
||||
if [ "$version" -gt "74" ];then
|
||||
LIBV=5.1.2
|
||||
LIBV=5.2.1
|
||||
fi
|
||||
|
||||
LIB_PATH_NAME=lib/php
|
||||
|
||||
@@ -32,6 +32,11 @@ if [ "$version" -eq "72" ] || [ "$version" -eq "73" ];then
|
||||
fi
|
||||
|
||||
|
||||
if [ "$version" -gt "74" ];then
|
||||
LIBV=3.3.5
|
||||
fi
|
||||
|
||||
|
||||
LIB_PATH_NAME=lib/php
|
||||
if [ -d $serverPath/php/${version}/lib64 ];then
|
||||
LIB_PATH_NAME=lib64
|
||||
|
||||
@@ -51,10 +51,11 @@ Install_pureftp()
|
||||
|
||||
# https://github.com/jedisct1/pure-ftpd/releases/download/1.0.49/pure-ftpd-1.0.49.tar.gz
|
||||
# https://download.pureftpd.org/pub/pure-ftpd/releases/pure-ftpd-1.0.49.tar.gz
|
||||
# DOWNLOAD=https://github.com/jedisct1/pure-ftpd/releases/download/${VER}/pure-ftpd-${VER}.tar.gz
|
||||
|
||||
|
||||
VER=$1
|
||||
DOWNLOAD=https://download.pureftpd.org/pub/pure-ftpd/releases/pure-ftpd-${VER}.tar.gz
|
||||
DOWNLOAD=https://github.com/jedisct1/pure-ftpd/releases/download/${VER}/pure-ftpd-${VER}.tar.gz
|
||||
# DOWNLOAD=https://download.pureftpd.org/pub/pure-ftpd/releases/pure-ftpd-${VER}.tar.gz
|
||||
|
||||
# curl -sSLo pure-ftpd-1.0.49.tar.gz https://download.pureftpd.org/pub/pure-ftpd/releases/pure-ftpd-1.0.49.tar.gz
|
||||
if [ ! -f $serverPath/source/pureftp/pure-ftpd-${VER}.tar.gz ];then
|
||||
@@ -68,14 +69,14 @@ Install_pureftp()
|
||||
md5_check=`md5sum $serverPath/source/pureftp/pure-ftpd-${VER}.tar.gz | awk '{print $1}'`
|
||||
if [ "${md5_ok}" == "${md5_check}" ]; then
|
||||
echo "pure-ftpd file check ok"
|
||||
else
|
||||
# 重新下载
|
||||
rm -rf $serverPath/source/pureftp/pure-ftpd-${VER}
|
||||
wget --no-check-certificate -O $serverPath/source/pureftp/pure-ftpd-${VER}.tar.gz $DOWNLOAD
|
||||
# curl -sSLo $serverPath/source/pureftp/pure-ftpd-${VER}.tar.gz $DOWNLOAD
|
||||
fi
|
||||
fi
|
||||
|
||||
# Last Download Method
|
||||
if [ ! -f $serverPath/source/pureftp/pure-ftpd-${VER}.tar.gz ];then
|
||||
wget --no-check-certificate -O $serverPath/source/pureftp/pure-ftpd-${VER}.tar.gz https://dl.midoks.me/soft/ftp/pure-ftpd-${VER}.tar.gz -T 3
|
||||
fi
|
||||
|
||||
if [ ! -d $serverPath/source/pureftp/pure-ftpd-${VER} ];then
|
||||
cd $serverPath/source/pureftp && tar zxvf pure-ftpd-${VER}.tar.gz
|
||||
fi
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
# ---> Python
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# poetry
|
||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||
#poetry.lock
|
||||
|
||||
# pdm
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||
#pdm.lock
|
||||
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
||||
# in version control.
|
||||
# https://pdm.fming.dev/#use-with-ide
|
||||
.pdm.toml
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
# PyCharm
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
Executable
+960
@@ -0,0 +1,960 @@
|
||||
{
|
||||
"open": false,
|
||||
"service": {
|
||||
"open": true,
|
||||
"name": "服务加固",
|
||||
"ps": "保护系统服务,开启后将无法添加和删除服务,部分软件无法安装!",
|
||||
"paths": [
|
||||
{
|
||||
"path": "/etc/rc.d",
|
||||
"chattr": "i",
|
||||
"s_mode": 509,
|
||||
"d_mode": 509
|
||||
},
|
||||
{
|
||||
"path": "/etc/rc.d/init.d",
|
||||
"chattr": "i",
|
||||
"s_mode": 493,
|
||||
"d_mode": 493
|
||||
},
|
||||
{
|
||||
"path": "/etc/rc.d/rc0.d",
|
||||
"chattr": "i",
|
||||
"s_mode": 493,
|
||||
"d_mode": 493
|
||||
},
|
||||
{
|
||||
"path": "/etc/rc.d/rc1.d",
|
||||
"chattr": "i",
|
||||
"s_mode": 493,
|
||||
"d_mode": 493
|
||||
},
|
||||
{
|
||||
"path": "/etc/rc.d/rc2.d",
|
||||
"chattr": "i",
|
||||
"s_mode": 493,
|
||||
"d_mode": 493
|
||||
},
|
||||
{
|
||||
"path": "/etc/rc.d/rc3.d",
|
||||
"chattr": "i",
|
||||
"s_mode": 493,
|
||||
"d_mode": 493
|
||||
},
|
||||
{
|
||||
"path": "/etc/rc.d/rc4.d",
|
||||
"chattr": "i",
|
||||
"s_mode": 493,
|
||||
"d_mode": 493
|
||||
},
|
||||
{
|
||||
"path": "/etc/rc.d/rc5.d",
|
||||
"chattr": "i",
|
||||
"s_mode": 493,
|
||||
"d_mode": 493
|
||||
},
|
||||
{
|
||||
"path": "/etc/rc.d/rc6.d",
|
||||
"chattr": "i",
|
||||
"s_mode": 493,
|
||||
"d_mode": 493
|
||||
},
|
||||
{
|
||||
"path": "/etc/rc.d/rc.local",
|
||||
"chattr": "i",
|
||||
"s_mode": 493,
|
||||
"d_mode": 493
|
||||
},
|
||||
{
|
||||
"path": "/etc/init.d",
|
||||
"chattr": "i",
|
||||
"s_mode": 493,
|
||||
"d_mode": 493
|
||||
},
|
||||
{
|
||||
"path": "/etc/rc0.d",
|
||||
"chattr": "i",
|
||||
"s_mode": 493,
|
||||
"d_mode": 493
|
||||
},
|
||||
{
|
||||
"path": "/etc/rc1.d",
|
||||
"chattr": "i",
|
||||
"s_mode": 493,
|
||||
"d_mode": 493
|
||||
},
|
||||
{
|
||||
"path": "/etc/rc2.d",
|
||||
"chattr": "i",
|
||||
"s_mode": 493,
|
||||
"d_mode": 493
|
||||
},
|
||||
{
|
||||
"path": "/etc/rc3.d",
|
||||
"chattr": "i",
|
||||
"s_mode": 493,
|
||||
"d_mode": 493
|
||||
},
|
||||
{
|
||||
"path": "/etc/rc4.d",
|
||||
"chattr": "i",
|
||||
"s_mode": 493,
|
||||
"d_mode": 493
|
||||
},
|
||||
{
|
||||
"path": "/etc/rc5.d",
|
||||
"chattr": "i",
|
||||
"s_mode": 493,
|
||||
"d_mode": 493
|
||||
},
|
||||
{
|
||||
"path": "/etc/rc6.d",
|
||||
"chattr": "i",
|
||||
"s_mode": 493,
|
||||
"d_mode": 493
|
||||
},
|
||||
{
|
||||
"path": "/etc/rcS.d",
|
||||
"chattr": "i",
|
||||
"s_mode": 493,
|
||||
"d_mode": 493
|
||||
},
|
||||
{
|
||||
"path": "/etc/systemd",
|
||||
"chattr": "i",
|
||||
"s_mode": 493,
|
||||
"d_mode": 493
|
||||
},
|
||||
{
|
||||
"path": "/lib/systemd",
|
||||
"chattr": "i",
|
||||
"s_mode": 493,
|
||||
"d_mode": 493
|
||||
}
|
||||
]
|
||||
},
|
||||
"home": {
|
||||
"open": true,
|
||||
"name": "环境变量加固",
|
||||
"ps": "保护用户环境变量不被修改,开启后无法自定义用户环境变量!",
|
||||
"paths": [
|
||||
{
|
||||
"path": "/root/.bash_history",
|
||||
"chattr": "a",
|
||||
"s_mode": 420,
|
||||
"d_mode": 420
|
||||
},
|
||||
{
|
||||
"path": "/root/.bashrc",
|
||||
"chattr": "i",
|
||||
"s_mode": 420,
|
||||
"d_mode": 420
|
||||
},
|
||||
{
|
||||
"path": "/root/.bash_logout",
|
||||
"chattr": "i",
|
||||
"s_mode": 420,
|
||||
"d_mode": 420
|
||||
},
|
||||
{
|
||||
"path": "/root/.bash_profile",
|
||||
"chattr": "i",
|
||||
"s_mode": 420,
|
||||
"d_mode": 420
|
||||
},
|
||||
{
|
||||
"path": "/root/.profile",
|
||||
"chattr": "i",
|
||||
"s_mode": 420,
|
||||
"d_mode": 420
|
||||
},
|
||||
{
|
||||
"path": "/etc/profile",
|
||||
"chattr": "i",
|
||||
"s_mode": 420,
|
||||
"d_mode": 420
|
||||
},
|
||||
{
|
||||
"path": "/etc/bash.bashrc",
|
||||
"chattr": "i",
|
||||
"s_mode": 420,
|
||||
"d_mode": 420
|
||||
},
|
||||
{
|
||||
"path": "/etc/sysctl.conf",
|
||||
"chattr": "i",
|
||||
"s_mode": 420,
|
||||
"d_mode": 420
|
||||
},
|
||||
{
|
||||
"path": "/etc/sysctl.d",
|
||||
"chattr": "i",
|
||||
"s_mode": 420,
|
||||
"d_mode": 420
|
||||
}
|
||||
]
|
||||
},
|
||||
"user": {
|
||||
"open": true,
|
||||
"name": "用户加固",
|
||||
"ps": "保护用户,开启后将无法添加删除用户和修改用户密码!",
|
||||
"paths": [
|
||||
{
|
||||
"path": "/etc/passwd",
|
||||
"chattr": "i",
|
||||
"s_mode": 420,
|
||||
"d_mode": 420
|
||||
},
|
||||
{
|
||||
"path": "/etc/group",
|
||||
"chattr": "i",
|
||||
"s_mode": 420,
|
||||
"d_mode": 420
|
||||
},
|
||||
{
|
||||
"path": "/usr/sbin/groupadd",
|
||||
"chattr": "i",
|
||||
"s_mode": 488,
|
||||
"d_mode": 420
|
||||
},
|
||||
{
|
||||
"path": "/usr/sbin/useradd",
|
||||
"chattr": "i",
|
||||
"s_mode": 488,
|
||||
"d_mode": 420
|
||||
},
|
||||
{
|
||||
"path": "/usr/bin/passwd",
|
||||
"chattr": "i",
|
||||
"s_mode": 509,
|
||||
"d_mode": 420
|
||||
}
|
||||
]
|
||||
},
|
||||
"bin": {
|
||||
"open": true,
|
||||
"name": "关键目录加固",
|
||||
"ps": "保护系统关键文件不被修改替换!",
|
||||
"paths": [
|
||||
{
|
||||
"path": "/usr/bin",
|
||||
"chattr": "i",
|
||||
"s_mode": 365,
|
||||
"d_mode": 365
|
||||
},
|
||||
{
|
||||
"path": "/usr/sbin",
|
||||
"chattr": "i",
|
||||
"s_mode": 365,
|
||||
"d_mode": 365
|
||||
},
|
||||
{
|
||||
"path": "/etc/bashrc",
|
||||
"chattr": "i",
|
||||
"s_mode": 420,
|
||||
"d_mode": 420
|
||||
},
|
||||
{
|
||||
"path": "/usr/local/bin",
|
||||
"chattr": "i",
|
||||
"s_mode": 365,
|
||||
"d_mode": 365
|
||||
},
|
||||
{
|
||||
"path": "/usr/local/sbin",
|
||||
"chattr": "i",
|
||||
"s_mode": 365,
|
||||
"d_mode": 365
|
||||
},
|
||||
{
|
||||
"path": "/sbin",
|
||||
"chattr": "i",
|
||||
"s_mode": 365,
|
||||
"d_mode": 365
|
||||
},
|
||||
{
|
||||
"path": "/bin",
|
||||
"chattr": "i",
|
||||
"s_mode": 365,
|
||||
"d_mode": 365
|
||||
}
|
||||
]
|
||||
},
|
||||
"cron": {
|
||||
"open": true,
|
||||
"name": "计划任务加固",
|
||||
"ps": "保护计划任务不被篡改,开启后无法添加删除计划任务!",
|
||||
"paths": [
|
||||
{
|
||||
"path": "/usr/bin/crontab",
|
||||
"chattr": "i",
|
||||
"s_mode": 509,
|
||||
"d_mode": 420
|
||||
},
|
||||
{
|
||||
"path": "/etc/crontab",
|
||||
"chattr": "i",
|
||||
"s_mode": 420,
|
||||
"d_mode": 420
|
||||
},
|
||||
{
|
||||
"path": "/etc/cron.d",
|
||||
"chattr": "i",
|
||||
"s_mode": 509,
|
||||
"d_mode": 509
|
||||
},
|
||||
{
|
||||
"path": "/etc/cron.daily",
|
||||
"chattr": "i",
|
||||
"s_mode": 509,
|
||||
"d_mode": 420
|
||||
},
|
||||
{
|
||||
"path": "/etc/cron.hourly",
|
||||
"chattr": "i",
|
||||
"s_mode": 509,
|
||||
"d_mode": 420
|
||||
},
|
||||
{
|
||||
"path": "/etc/cron.monthly",
|
||||
"chattr": "i",
|
||||
"s_mode": 509,
|
||||
"d_mode": 420
|
||||
},
|
||||
{
|
||||
"path": "/etc/cron.weekly",
|
||||
"chattr": "i",
|
||||
"s_mode": 509,
|
||||
"d_mode": 420
|
||||
},
|
||||
{
|
||||
"path": "/etc/anacrontab",
|
||||
"chattr": "i",
|
||||
"s_mode": 384,
|
||||
"d_mode": 384
|
||||
},
|
||||
{
|
||||
"path": "/var/spool/cron",
|
||||
"chattr": "i",
|
||||
"s_mode": 448,
|
||||
"d_mode": 448
|
||||
},
|
||||
{
|
||||
"path": "/var/spool/cron/root",
|
||||
"chattr": "i",
|
||||
"s_mode": 384,
|
||||
"d_mode": 384
|
||||
},
|
||||
{
|
||||
"path": "/var/spool/anacron",
|
||||
"chattr": "i",
|
||||
"s_mode": 509,
|
||||
"d_mode": 509
|
||||
}
|
||||
]
|
||||
},
|
||||
"ssh": {
|
||||
"open": true,
|
||||
"name": "SSH服务加固",
|
||||
"ps": "保护SSH不被暴力破解,记录用户登录日志",
|
||||
"cycle": 120,
|
||||
"limit": 3600,
|
||||
"limit_count": 3
|
||||
},
|
||||
"process": {
|
||||
"open": true,
|
||||
"name": "异常进程监控",
|
||||
"ps": "监控服务器进程列表,发现异常的进程后立即结束",
|
||||
"process_white": [
|
||||
"pip",
|
||||
"pip3",
|
||||
"yum",
|
||||
"apt-get",
|
||||
"apt",
|
||||
"redis-cli",
|
||||
"memcached",
|
||||
"sshd",
|
||||
"vm",
|
||||
"vim",
|
||||
"htop",
|
||||
"top",
|
||||
"sh",
|
||||
"bash",
|
||||
"zip",
|
||||
"gzip",
|
||||
"rsync",
|
||||
"tar",
|
||||
"unzip",
|
||||
"rar",
|
||||
"unrar",
|
||||
"php",
|
||||
"composer",
|
||||
"pkill",
|
||||
"mongo",
|
||||
"mongod",
|
||||
"php-fpm",
|
||||
"php-fpm5.6",
|
||||
"php-fpm7.0",
|
||||
"php-fpm7.1",
|
||||
"php-fpm7.2",
|
||||
"php-fpm7.3",
|
||||
"php-fpm7.4",
|
||||
"php-fpm8.1",
|
||||
"php-fpm8.2",
|
||||
"nginx",
|
||||
"httpd",
|
||||
"lsof",
|
||||
"ps",
|
||||
"vi",
|
||||
"vim",
|
||||
"redis-server",
|
||||
"mysqld",
|
||||
"mysqld_safe",
|
||||
"mysql",
|
||||
"pure-ftpd",
|
||||
"sparse_dd",
|
||||
"stunnel",
|
||||
"squeezed",
|
||||
"vncterm",
|
||||
"awk",
|
||||
"ruby",
|
||||
"postgres",
|
||||
"mpathalert",
|
||||
"vncterm",
|
||||
"multipathd",
|
||||
"fe",
|
||||
"elasticsyslog",
|
||||
"syslogd",
|
||||
"v6d",
|
||||
"xapi",
|
||||
"screen",
|
||||
"runsvdir",
|
||||
"svlogd",
|
||||
"java",
|
||||
"udevd",
|
||||
"ntpd",
|
||||
"irqbalance",
|
||||
"qmgr",
|
||||
"wpa_supplicant",
|
||||
"mysqld_safe",
|
||||
"sftp-server",
|
||||
"lvmetad",
|
||||
"gitlab-web",
|
||||
"pure-ftpd",
|
||||
"auditd",
|
||||
"master",
|
||||
"dbus-daemon",
|
||||
"tapdisk",
|
||||
"init",
|
||||
"ksoftirqd",
|
||||
"kworker",
|
||||
"kmpathd",
|
||||
"kmpath_handlerd",
|
||||
"python",
|
||||
"kdmflush",
|
||||
"bioset",
|
||||
"crond",
|
||||
"kthreadd",
|
||||
"migration",
|
||||
"rcu_sched",
|
||||
"kjournald",
|
||||
"gcc",
|
||||
"gcc++",
|
||||
"nginx",
|
||||
"mysqld",
|
||||
"php-cgi",
|
||||
"login",
|
||||
"firewalld",
|
||||
"iptables",
|
||||
"systemd",
|
||||
"network",
|
||||
"dhclient",
|
||||
"systemd-journald",
|
||||
"chrony",
|
||||
"chronyd",
|
||||
"chronyc",
|
||||
"NetworkManager",
|
||||
"systemd-logind",
|
||||
"systemd-udevd",
|
||||
"polkitd",
|
||||
"tuned",
|
||||
"rsyslogd",
|
||||
"AliYunDunUpdate",
|
||||
"AliYunDun",
|
||||
"du",
|
||||
"sendmail",
|
||||
"gunicorn",
|
||||
"python2",
|
||||
"python3",
|
||||
"python34",
|
||||
"python2.6",
|
||||
"runsv",
|
||||
"dd",
|
||||
"mkfs",
|
||||
"fdisk",
|
||||
"systemd-resolve",
|
||||
"rpm",
|
||||
"cc1",
|
||||
"cc1plus",
|
||||
"as",
|
||||
"acme.sh",
|
||||
"cc",
|
||||
"du",
|
||||
"grep",
|
||||
"awk",
|
||||
"sed",
|
||||
"cut",
|
||||
"free",
|
||||
"df",
|
||||
"firewall-cmd",
|
||||
"ufw",
|
||||
"echo",
|
||||
"ls",
|
||||
"cp",
|
||||
"mv",
|
||||
"rm",
|
||||
"diff",
|
||||
"ln",
|
||||
"cat",
|
||||
"more",
|
||||
"wtmp",
|
||||
"date",
|
||||
"e2fsck",
|
||||
"gunzip",
|
||||
"ifconfig",
|
||||
"ip",
|
||||
"route",
|
||||
"ping",
|
||||
"scp",
|
||||
"telnet",
|
||||
"cd",
|
||||
"comm",
|
||||
"touch",
|
||||
"man",
|
||||
"w",
|
||||
"who",
|
||||
"last",
|
||||
"clock",
|
||||
"uname",
|
||||
"su",
|
||||
"uptime",
|
||||
"vmstat",
|
||||
"mount",
|
||||
"umount",
|
||||
"mkdir",
|
||||
"mkswap",
|
||||
"swapon",
|
||||
"e2fsck",
|
||||
"tune2fs",
|
||||
"groupadd",
|
||||
"useradd",
|
||||
"passwd",
|
||||
"userdel",
|
||||
"chown",
|
||||
"chmod",
|
||||
"chgrp",
|
||||
"id",
|
||||
"mail",
|
||||
"gzip",
|
||||
"bzip2",
|
||||
"bunzip2",
|
||||
"networking",
|
||||
"ssh",
|
||||
"find",
|
||||
"locate",
|
||||
"slocate",
|
||||
"dir",
|
||||
"vdir",
|
||||
"pwd",
|
||||
"rename",
|
||||
"rmdir",
|
||||
"updatedb",
|
||||
"whereis",
|
||||
"which",
|
||||
"compress",
|
||||
"ar",
|
||||
"arj",
|
||||
"gzexe",
|
||||
"bzip2",
|
||||
"cksum",
|
||||
"cmp",
|
||||
"col",
|
||||
"colrm",
|
||||
"csplit",
|
||||
"diff3",
|
||||
"emacs",
|
||||
"join",
|
||||
"head",
|
||||
"sort",
|
||||
"wc",
|
||||
"uniq",
|
||||
"tail",
|
||||
"sum",
|
||||
"ulimit",
|
||||
"pkill",
|
||||
"kill",
|
||||
"killall",
|
||||
"pidof",
|
||||
"pstree",
|
||||
"watch",
|
||||
"pgrep",
|
||||
"dumpe2fs",
|
||||
"mke2fs",
|
||||
"sync",
|
||||
"lsyncd",
|
||||
"tune2fs",
|
||||
"basename",
|
||||
"file",
|
||||
"locate/slocate",
|
||||
"ls/dir/vdir",
|
||||
"bzcat",
|
||||
"bzip2recover",
|
||||
"bzless/bzmore",
|
||||
"cpio",
|
||||
"dump",
|
||||
"lha",
|
||||
"resotre",
|
||||
"unarj",
|
||||
"uncompress",
|
||||
"zcat",
|
||||
"zforce",
|
||||
"zipinfo",
|
||||
"znew",
|
||||
"diffstat",
|
||||
"ed",
|
||||
"ex",
|
||||
"expand",
|
||||
"fmt",
|
||||
"fold",
|
||||
"grep/egrep/fgrep",
|
||||
"ispell",
|
||||
"jed",
|
||||
"joe",
|
||||
"less",
|
||||
"look",
|
||||
"od",
|
||||
"paste",
|
||||
"pico",
|
||||
"spell",
|
||||
"split",
|
||||
"tac",
|
||||
"tee",
|
||||
"tr",
|
||||
"unexpand",
|
||||
"alias",
|
||||
"bg",
|
||||
"bind",
|
||||
"declare",
|
||||
"dirs",
|
||||
"enable",
|
||||
"eval",
|
||||
"exec",
|
||||
"exit",
|
||||
"export",
|
||||
"fc",
|
||||
"fg",
|
||||
"hash",
|
||||
"history",
|
||||
"jobs",
|
||||
"logout",
|
||||
"popd",
|
||||
"pushd",
|
||||
"set",
|
||||
"shopt",
|
||||
"umask",
|
||||
"unalias",
|
||||
"unset",
|
||||
"accept",
|
||||
"cancel",
|
||||
"disable",
|
||||
"lp",
|
||||
"lpadmin",
|
||||
"lpc",
|
||||
"lpq",
|
||||
"lpr",
|
||||
"lprm",
|
||||
"lpstat",
|
||||
"pr",
|
||||
"reject",
|
||||
"bc",
|
||||
"cal",
|
||||
"clear",
|
||||
"consoletype",
|
||||
"ctrlaltdel",
|
||||
"dircolors",
|
||||
"eject",
|
||||
"halt",
|
||||
"hostid",
|
||||
"hwclock",
|
||||
"info",
|
||||
"md5sum",
|
||||
"letsencrypt",
|
||||
"mandb",
|
||||
"mesg",
|
||||
"mtools",
|
||||
"mtoolstest",
|
||||
"poweroff",
|
||||
"reboot",
|
||||
"shutdown",
|
||||
"sleep",
|
||||
"stat",
|
||||
"talk",
|
||||
"wall",
|
||||
"whatis",
|
||||
"whoami",
|
||||
"write",
|
||||
"cmsgoagent.linu",
|
||||
"yes",
|
||||
"chfn",
|
||||
"chsh",
|
||||
"finger",
|
||||
"gpasswd",
|
||||
"groupdel",
|
||||
"groupmod",
|
||||
"groups",
|
||||
"grpck",
|
||||
"grpconv",
|
||||
"grpunconv",
|
||||
"logname",
|
||||
"pwck",
|
||||
"pwconv",
|
||||
"dd",
|
||||
"mariadbd",
|
||||
"pwunconv",
|
||||
"usermod",
|
||||
"users",
|
||||
"nice",
|
||||
"nohup",
|
||||
"renice",
|
||||
"badblocks",
|
||||
"blockdev",
|
||||
"chattr",
|
||||
"convertquota",
|
||||
"e2image",
|
||||
"e2label",
|
||||
"edquota",
|
||||
"fail2ban-server",
|
||||
"findfs",
|
||||
"fsck",
|
||||
"grub",
|
||||
"hdparm",
|
||||
"lilo",
|
||||
"lsattr",
|
||||
"mkbootdisk",
|
||||
"mkinitrd",
|
||||
"mkisofs",
|
||||
"mknod",
|
||||
"mktemp",
|
||||
"parted",
|
||||
"quota",
|
||||
"quotacheck",
|
||||
"xargs",
|
||||
"bcm-agent",
|
||||
"bcm-si",
|
||||
"quotaoff",
|
||||
"quotaon",
|
||||
"quotastat",
|
||||
"repquota",
|
||||
"swapoff",
|
||||
"depmod",
|
||||
"dmesg",
|
||||
"insmod",
|
||||
"iostat",
|
||||
"ipcs",
|
||||
"kernelversion",
|
||||
"lsmod",
|
||||
"modinfo",
|
||||
"modprobe",
|
||||
"mpstat",
|
||||
"rmmod",
|
||||
"sar",
|
||||
"slabtop",
|
||||
"sysctl",
|
||||
"tload",
|
||||
"startx",
|
||||
"xauth",
|
||||
"xhost",
|
||||
"xinit",
|
||||
"xlsatoms",
|
||||
"xlsclients",
|
||||
"xlsfonts",
|
||||
"xset",
|
||||
"chroot",
|
||||
"nmap",
|
||||
"ntfs-3g",
|
||||
"sftp",
|
||||
"slogin",
|
||||
"sudo",
|
||||
"awk/gawk",
|
||||
"expr",
|
||||
"gdb",
|
||||
"ldd",
|
||||
"make",
|
||||
"nm",
|
||||
"perl",
|
||||
"test",
|
||||
"arch",
|
||||
"at",
|
||||
"atq",
|
||||
"atrm",
|
||||
"batch",
|
||||
"chkconfig",
|
||||
"crontab",
|
||||
"lastb",
|
||||
"logrotate",
|
||||
"logsave",
|
||||
"logwatch",
|
||||
"lsusb",
|
||||
"patch",
|
||||
"runlevel",
|
||||
"service",
|
||||
"telinit",
|
||||
"dnsdomainname",
|
||||
"domainname",
|
||||
"hostname",
|
||||
"ifcfg",
|
||||
"ifdown",
|
||||
"ifup",
|
||||
"stmpd",
|
||||
"nisdomainname",
|
||||
"ypdomainname",
|
||||
"arp",
|
||||
"arping",
|
||||
"arpwatch",
|
||||
"dig",
|
||||
"elinks",
|
||||
"elm",
|
||||
"ftp",
|
||||
"host",
|
||||
"ipcalc",
|
||||
"lynx",
|
||||
"ncftp",
|
||||
"netstat",
|
||||
"nslookup",
|
||||
"pine",
|
||||
"dhclient-script",
|
||||
"rsh",
|
||||
"tftp",
|
||||
"tracepath",
|
||||
"traceroute",
|
||||
"wget",
|
||||
"arptables",
|
||||
"iptables-save",
|
||||
"iptables-restore",
|
||||
"tcpdump",
|
||||
"ab",
|
||||
"apachectl",
|
||||
"exportfs",
|
||||
"htdigest",
|
||||
"htpasswd",
|
||||
"mailq",
|
||||
"mysqladmin",
|
||||
"msqldump",
|
||||
"mysqlimport",
|
||||
"mysqlshow",
|
||||
"nfsstat",
|
||||
"showmount",
|
||||
"smbclient",
|
||||
"smbmount",
|
||||
"smbpasswd",
|
||||
"squid",
|
||||
"pickup",
|
||||
"local",
|
||||
"localedef",
|
||||
"bounce",
|
||||
"smtp",
|
||||
"smtpd",
|
||||
"trivial-rewrite",
|
||||
"xe-daemon",
|
||||
"cleanup",
|
||||
"nm-dispatcher",
|
||||
"lsinitrd",
|
||||
"barad_agent",
|
||||
"stop.sh",
|
||||
"YDService",
|
||||
"agetty",
|
||||
"systemctl",
|
||||
"AliSecureCheckA",
|
||||
"containerd",
|
||||
"containerd-shim",
|
||||
"certbot-auto",
|
||||
"oneav",
|
||||
"oneavd",
|
||||
"oneav_service_m",
|
||||
"s3fs",
|
||||
"bosfs",
|
||||
"cosfs",
|
||||
"flock",
|
||||
"raidcheck",
|
||||
"run-parts",
|
||||
"man-db.cron",
|
||||
"YDLive",
|
||||
"sgagent"
|
||||
],
|
||||
"process_white_rule": [
|
||||
"vif",
|
||||
"node",
|
||||
"pm2",
|
||||
"npm",
|
||||
"yarn",
|
||||
"qemu",
|
||||
"scsi_eh",
|
||||
"xcp",
|
||||
"xen",
|
||||
"docker",
|
||||
"yunsuo",
|
||||
"scsi",
|
||||
"jbd2",
|
||||
"ext4",
|
||||
"xfs",
|
||||
"aliyun",
|
||||
"kswapd",
|
||||
"PM2",
|
||||
"yunsuo",
|
||||
"mkfs",
|
||||
"Ali",
|
||||
"watchdog",
|
||||
"kworker",
|
||||
"ksoftirqd",
|
||||
"migration",
|
||||
"mysql",
|
||||
"/www/server/",
|
||||
"cmsgoagent",
|
||||
"python",
|
||||
"python3",
|
||||
"ifdown",
|
||||
"node",
|
||||
"sd-pam"
|
||||
],
|
||||
"process_exclude": [
|
||||
"php-fpm",
|
||||
"git",
|
||||
"mysqld",
|
||||
"mongod",
|
||||
"dockerd",
|
||||
"docker-containerd",
|
||||
"memcached",
|
||||
"jsvc",
|
||||
"jsvc.exec",
|
||||
"nginx",
|
||||
"node",
|
||||
"pm2",
|
||||
"npm",
|
||||
"yarn",
|
||||
"httpd",
|
||||
"gunicorn",
|
||||
"configure",
|
||||
"make",
|
||||
"curl",
|
||||
"wget",
|
||||
"anacron",
|
||||
"mysqldump",
|
||||
"node",
|
||||
"php",
|
||||
"mysql",
|
||||
"netstat",
|
||||
"redis",
|
||||
"postfix"
|
||||
]
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 812 B |
Executable
+24
@@ -0,0 +1,24 @@
|
||||
<div class="bt-form">
|
||||
<div class="bt-w-main">
|
||||
<div class="bt-w-menu">
|
||||
<p class="bgw" onclick="pluginService('system_safe');">服务</p>
|
||||
<p onclick="pluginInitD('system_safe');">自启动</p>
|
||||
<p onclick="ssConfigList();">防护配置</p>
|
||||
<p onclick="ssLockAddress();">封锁IP</p>
|
||||
<p onclick="ssLogAudit();">日志审计</p>
|
||||
<p onclick="ssOpLog();">操作日志</p>
|
||||
</div>
|
||||
<div class="bt-w-con pd15">
|
||||
<div class="soft-man-con"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script type="text/javascript" src="/plugins/file?name=system_safe&f=js/app.js"></script>
|
||||
<script type="text/javascript">
|
||||
resetPluginWinWidth(800);
|
||||
resetPluginWinHeight(500);
|
||||
$.getScript("/plugins/file?name=system_safe&f=js/app.js", function(){
|
||||
pluginService('system_safe');
|
||||
});
|
||||
</script>
|
||||
Executable
+20
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"sort": 1,
|
||||
"ps": "提供灵活的系统加固功能,防止系统被植入木马,支持服务器日志审计功能",
|
||||
"name": "system_safe",
|
||||
"title": "系统加固",
|
||||
"shell": "install.sh",
|
||||
"versions":["1.0"],
|
||||
"updates":["1.0"],
|
||||
"tip": "soft",
|
||||
"icon":"ico.png",
|
||||
"checks": "server/system_safe",
|
||||
"path": "server/system_safe",
|
||||
"display": 1,
|
||||
"author": "midoks",
|
||||
"date": "2022-01-12",
|
||||
"home": "",
|
||||
"type": 0,
|
||||
"pid": "4"
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
[Unit]
|
||||
Description=system_safe server daemon
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=forking
|
||||
ExecStart={$SERVER_PATH}/init.d/system_safe start
|
||||
ExecStop={$SERVER_PATH}/init.d/system_safe stop
|
||||
ExecReload={$SERVER_PATH}/init.d/system_safe reload
|
||||
ExecRestart={$SERVER_PATH}/init.d/system_safe restart
|
||||
KillMode=process
|
||||
Restart=on-failure
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,94 @@
|
||||
#!/bin/bash
|
||||
# chkconfig: 2345 55 25
|
||||
# description:system_safe
|
||||
|
||||
### BEGIN INIT INFO
|
||||
# Provides: system_safe
|
||||
# Required-Start: $all
|
||||
# Required-Stop: $all
|
||||
# Default-Start: 2 3 4 5
|
||||
# Default-Stop: 0 1 6
|
||||
# Short-Description: starts system_safe
|
||||
# Description: starts the system_safe
|
||||
### END INIT INFO
|
||||
|
||||
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
|
||||
mw_path={$SERVER_PATH}
|
||||
rootPath=$(dirname "$mw_path")
|
||||
PATH=$PATH:$mw_path/bin
|
||||
|
||||
if [ -f $rootPath/mdserver-web/bin/activate ];then
|
||||
source $rootPath/mdserver-web/bin/activate
|
||||
fi
|
||||
|
||||
sys_start()
|
||||
{
|
||||
isStart=$(ps aux |grep -E "(system_safe)"|grep -v grep|grep -v '/bin/bash'|grep -v 'system_safe/system_safe.py start' | grep -v 'system_safe/system_safe.py reload' | grep -v 'system_safe/system_safe.py restart' | grep -v systemctl | grep -v '/bin/sh' | awk '{print $2}'|xargs)
|
||||
if [ "$isStart" == '' ];then
|
||||
echo -e "Starting system_safe service... \c"
|
||||
cd $rootPath/mdserver-web
|
||||
nohup python3 plugins/system_safe/system_safe.py bg_start &> $mw_path/service.log &
|
||||
sleep 0.5
|
||||
isStart=$(ps aux |grep -E "(system_safe)"|grep -v grep|awk '{print $2}'|xargs)
|
||||
if [ "$isStart" == '' ];then
|
||||
echo -e "\033[31mfailed\033[0m"
|
||||
echo '------------------------------------------------------'
|
||||
cat $mw_path/service.log
|
||||
echo '------------------------------------------------------'
|
||||
echo -e "\033[31mError: system_safe service startup failed.\033[0m"
|
||||
return;
|
||||
fi
|
||||
echo -e "\033[32mdone\033[0m"
|
||||
else
|
||||
echo "Starting system_safe service (pid $isStart) already running"
|
||||
fi
|
||||
}
|
||||
|
||||
sys_stop()
|
||||
{
|
||||
echo -e "Stopping system_safe service... \c";
|
||||
pids=$(ps aux |grep -E "(system_safe)"|grep -v grep|grep -v '/bin/bash'|grep -v systemctl | grep -v 'system_safe/system_safe.py bg_stop'|grep -v 'system_safe/system_safe.py stop' | grep -v 'system_safe/system_safe.py reload' | grep -v 'system_safe/system_safe.py restart' |awk '{print $2}'|xargs)
|
||||
arr=($pids)
|
||||
for p in ${arr[@]}
|
||||
do
|
||||
kill -9 $p
|
||||
done
|
||||
cd $rootPath/mdserver-web
|
||||
python3 plugins/system_safe/system_safe.py bg_stop
|
||||
echo -e "\033[32mdone\033[0m"
|
||||
}
|
||||
|
||||
sys_status()
|
||||
{
|
||||
isStart=$(ps aux |grep -E "(system_safe)"|grep -v grep|grep -v systemctl|awk '{print $2}'|xargs)
|
||||
if [ "$isStart" != '' ];then
|
||||
echo -e "\033[32msystem_safe service (pid $isStart) already running\033[0m"
|
||||
else
|
||||
echo -e "\033[31msystem_safe service not running\033[0m"
|
||||
fi
|
||||
}
|
||||
|
||||
case "$1" in
|
||||
'start')
|
||||
sys_start
|
||||
;;
|
||||
'stop')
|
||||
sys_stop
|
||||
;;
|
||||
'restart')
|
||||
sys_stop
|
||||
sleep 0.2
|
||||
sys_start
|
||||
;;
|
||||
'reload')
|
||||
sys_stop
|
||||
sleep 0.2
|
||||
sys_start
|
||||
;;
|
||||
'status')
|
||||
sys_status
|
||||
;;
|
||||
*)
|
||||
echo "Usage: systemctl {start|stop|restart|reload} system_safe"
|
||||
;;
|
||||
esac
|
||||
Executable
+47
@@ -0,0 +1,47 @@
|
||||
#!/bin/bash
|
||||
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
|
||||
export PATH
|
||||
|
||||
curPath=`pwd`
|
||||
rootPath=$(dirname "$curPath")
|
||||
rootPath=$(dirname "$rootPath")
|
||||
serverPath=$(dirname "$rootPath")
|
||||
|
||||
install_tmp=${rootPath}/tmp/mw_install.pl
|
||||
SYSOS=`uname`
|
||||
VERSION=$2
|
||||
APP_NAME=system_safe
|
||||
|
||||
Install_App()
|
||||
{
|
||||
echo '正在安装脚本文件...' > $install_tmp
|
||||
mkdir -p $serverPath/system_safe
|
||||
echo "$VERSION" > $serverPath/system_safe/version.pl
|
||||
echo 'install complete' > $install_tmp
|
||||
|
||||
#初始化
|
||||
cd ${serverPath}/mdserver-web && python3 plugins/system_safe/system_safe.py start $VERSION
|
||||
cd ${serverPath}/mdserver-web && python3 plugins/system_safe/system_safe.py initd_install $VERSION
|
||||
}
|
||||
|
||||
Uninstall_App()
|
||||
{
|
||||
|
||||
if [ -f /usr/lib/systemd/system/${APP_NAME}.service ] || [ -f /lib/systemd/system/${APP_NAME}.service ] ;then
|
||||
systemctl stop ${APP_NAME}
|
||||
systemctl disable ${APP_NAME}
|
||||
rm -rf /usr/lib/systemd/system/${APP_NAME}.service
|
||||
rm -rf /lib/systemd/system/${APP_NAME}.service
|
||||
systemctl daemon-reload
|
||||
fi
|
||||
|
||||
rm -rf $serverPath/system_safe
|
||||
echo "uninstall completed" > $install_tmp
|
||||
}
|
||||
|
||||
action=$1
|
||||
if [ "${1}" == 'install' ];then
|
||||
Install_App
|
||||
else
|
||||
Uninstall_App
|
||||
fi
|
||||
@@ -0,0 +1,606 @@
|
||||
function ssPost(method,args,callback){
|
||||
var _args = null;
|
||||
if (typeof(args) == 'string'){
|
||||
_args = JSON.stringify(toArrayObject(args));
|
||||
} else {
|
||||
_args = JSON.stringify(args);
|
||||
}
|
||||
|
||||
var loadT = layer.msg('正在获取...', { icon: 16, time: 0, shade: 0.3 });
|
||||
|
||||
|
||||
|
||||
var req_data = {};
|
||||
req_data['name'] = 'system_safe';
|
||||
req_data['script'] = 'system_safe';
|
||||
req_data['func'] = method;
|
||||
req_data['args'] = _args;
|
||||
$.post('/plugins/run', req_data, function(data) {
|
||||
layer.close(loadT);
|
||||
if (!data.status){
|
||||
layer.msg(data.msg,{icon:0,time:2000,shade: [0.3, '#000']});
|
||||
return;
|
||||
}
|
||||
|
||||
if(typeof(callback) == 'function'){
|
||||
callback(data);
|
||||
}
|
||||
},'json');
|
||||
}
|
||||
|
||||
function ssAsyncPost(method,args){
|
||||
var _args = null;
|
||||
if (typeof(args) == 'string'){
|
||||
_args = JSON.stringify(toArrayObject(args));
|
||||
} else {
|
||||
_args = JSON.stringify(args);
|
||||
}
|
||||
return syncPost('/plugins/run', {name:'system_safe', func:method, args:_args});
|
||||
}
|
||||
|
||||
function ssPostCallbak(method, args, callback){
|
||||
var loadT = layer.msg('正在获取...', { icon: 16, time: 0, shade: 0.3 });
|
||||
|
||||
var req_data = {};
|
||||
req_data['name'] = 'system_safe';
|
||||
req_data['func'] = method;
|
||||
req_data['script'] = 'system_safe';
|
||||
args['version'] = '1.0';
|
||||
|
||||
|
||||
if (typeof(args) == 'string'){
|
||||
req_data['args'] = JSON.stringify(toArrayObject(args));
|
||||
} else {
|
||||
req_data['args'] = JSON.stringify(args);
|
||||
}
|
||||
|
||||
$.post('/plugins/callback', req_data, function(data) {
|
||||
layer.close(loadT);
|
||||
if (!data.status){
|
||||
layer.msg(data.msg,{icon:0,time:2000,shade: [0.3, '#000']});
|
||||
return;
|
||||
}
|
||||
|
||||
if(typeof(callback) == 'function'){
|
||||
callback(data);
|
||||
}
|
||||
},'json');
|
||||
}
|
||||
|
||||
function getSafeConfigPathList(tag){
|
||||
ssPost('get_safe_data', {tag:tag}, function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
var slist = rdata.data.paths;
|
||||
|
||||
var body = '';
|
||||
for (var i = 0; i < slist.length; i++) {
|
||||
body += "<tr>";
|
||||
body += "<td>"+slist[i]['path']+"</td>";
|
||||
|
||||
if (slist[i]['chattr'] == 'i'){
|
||||
body += "<td>只读</td>";
|
||||
} else if (slist[i]['chattr'] == 'a'){
|
||||
body += "<td>追加</td>";
|
||||
} else{
|
||||
body += "<td>只读</td>";
|
||||
}
|
||||
|
||||
if (rdata.msg['open']){
|
||||
body += "<td>"+slist[i]['d_mode']+"</td>";
|
||||
body += "<td><a class='btlink'>已保护</a></td>";
|
||||
} else {
|
||||
body += "<td>"+slist[i]['s_mode']+"</td>";
|
||||
body += "<td><a style='color:red;'>未保护</a></td>";
|
||||
}
|
||||
body += "<td style='text-align: right;'><a class='btlink safe_path_delete' row='"+i+"'>删除</a></td>";
|
||||
body += "</tr>";
|
||||
}
|
||||
|
||||
$('#safe-file-table tbody').html(body);
|
||||
$('.safe_path_delete').click(function(){
|
||||
var id = $(this).attr('row');
|
||||
ssPost('del_safe_path',{tag:tag,index:id}, function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
showMsg(rdata.msg, function(){
|
||||
getSafeConfigPathList(tag);
|
||||
},{icon:rdata.status?1:2,shade: [0.3, '#000']},2000);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function setSafeConfigPath(tag, alist){
|
||||
|
||||
layer.open({
|
||||
type: 1,
|
||||
area: ['700px','535px'],
|
||||
title: '配置【'+alist['name']+'】',
|
||||
content: "<form class='bt-form pd20'>\
|
||||
<div style='border-bottom:#ccc 1px solid;margin-bottom:10px;padding-bottom:10px'>\
|
||||
<input class='bt-input-text' name='s_path' id='s_path' type='text' value='' style='width:370px;margin-right:5px;' placeholder='被保护的文件或目录完整路径'>\
|
||||
<a class='glyphicon cursor glyphicon-folder-open' onclick='changePath(\"s_path\")' style='color:#edca5c;margin-right:20px;font-size:16px'></a>\
|
||||
<select class='bt-input-text' name='chattr'>\
|
||||
<option value='i'>只读</option>\
|
||||
<option value='a'>追加</option>\
|
||||
</select>\
|
||||
<input class='bt-input-text mr5' name='d_mode' type='text' style='width:120px;' placeholder='权限'>\
|
||||
<button type='button' class='btn btn-success btn-sm va0 pull-right add_safe_config'>添加</button>\
|
||||
</div>\
|
||||
<div class='divtable'>\
|
||||
<div id='safe-file-table' class='table_head_fix' style='max-height:300px;overflow:auto;border:#ddd 1px solid'>\
|
||||
<table class='table table-hover' style='border:none'>\
|
||||
<thead>\
|
||||
<tr>\
|
||||
<th width='360'>路径</th>\
|
||||
<th>模式</th>\
|
||||
<th>权限</th>\
|
||||
<th>状态</th>\
|
||||
<th style='text-align: right;'>操作</th>\
|
||||
</tr>\
|
||||
</thead>\
|
||||
<tbody></tbody>\
|
||||
</table>\
|
||||
</div>\
|
||||
</div>\
|
||||
<ul class='help-info-text c7 ptb10' style='margin-top: 5px;'>\
|
||||
<li>【只读】无法修改、创建、删除文件和目录</li>\
|
||||
<li>【追加】只能追加内容,不能删除或修改原有内容</li>\
|
||||
<li>【权限】设置文件或目录在受保护状态下的权限(非继承),关闭保护后权限自动还原</li>\
|
||||
<li>【如何填写权限】请填写Linux权限代号,如:644、755、600、555等,如果不填写,则使用文件原来的权限</li>\
|
||||
</ul>\
|
||||
</form>",
|
||||
success:function(){
|
||||
|
||||
$('.add_safe_config').click(function(){
|
||||
var path = $('input[name="s_path"]').val();
|
||||
var chattr = $('select[name="chattr"]').val();
|
||||
var d_mode = $('input[name="d_mode"]').val();
|
||||
ssPost('add_safe_path',{tag:tag,path:path,chattr:chattr,d_mode:d_mode}, function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
showMsg(rdata.msg, function(){
|
||||
getSafeConfigPathList(tag);
|
||||
},{icon:rdata.status?1:2,shade: [0.3, '#000']},2000);
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
getSafeConfigPathList(tag);
|
||||
|
||||
|
||||
}
|
||||
|
||||
function setSafeConfigSsh(tag, alist){
|
||||
|
||||
|
||||
function setSafeConfigSshData(){
|
||||
ssPost('get_ssh_data', {}, function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
var info = rdata.data;
|
||||
|
||||
$('input[name="s_cycle"]').val(info['cycle']);
|
||||
$('input[name="s_limit_count"]').val(info['limit_count']);
|
||||
$('input[name="s_limit"]').val(info['limit']);
|
||||
});
|
||||
}
|
||||
layer.open({
|
||||
type: 1,
|
||||
area: ['700px','210px'],
|
||||
title: '配置【'+alist['name']+'】',
|
||||
content: "<form class='bt-form pd20'>\
|
||||
<div style='border-bottom:#ccc 1px solid;margin-bottom:10px;padding-bottom:10px'>\
|
||||
在(检测周期)\
|
||||
<input class='bt-input-text' min='30' max='1800' name='s_cycle' type='number' value='120' style='width:80px;margin-right:5px;'>\
|
||||
秒内,登录错误(检测阈值)\
|
||||
<input class='bt-input-text' min='30' max='1800' name='s_limit_count' type='number' value='120' style='width:80px;margin-right:5px;'>\
|
||||
次,封锁(封锁时间)\
|
||||
<input min='60' class='bt-input-text' name='s_limit' type='number' value='3600' style='width:80px;margin-right:12px;'>\
|
||||
<button type='button' class='btn btn-success btn-sm va0 pull-right save_safe_ssh'>保存</button>\
|
||||
</div>\
|
||||
<ul class='help-info-text c7 ptb10' style='margin-top: 5px;'>\
|
||||
<li>触发以上策略后,客户端IP将被封锁一段时间</li>\
|
||||
<li>请在面板日志或操作日志中查看封锁记录</li>\
|
||||
<li>请在面板日志或操作日志中查看SSH成功登录的记录</li>\
|
||||
</ul>\
|
||||
</form>",
|
||||
success:function(){
|
||||
setSafeConfigSshData();
|
||||
|
||||
$('.save_safe_ssh').click(function(){
|
||||
var cycle = $('input[name="s_cycle"]').val();
|
||||
var limit_count = $('input[name="s_limit_count"]').val();
|
||||
var limit = $('input[name="s_limit"]').val();
|
||||
ssPost('save_safe_ssh',{cycle:cycle,limit_count:limit_count,limit:limit}, function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
showMsg(rdata.msg, function(){
|
||||
setSafeConfigSshData();
|
||||
},{icon:rdata.status?1:2,shade: [0.3, '#000']},2000);
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
function setSafeConfigProcessList(tag){
|
||||
ssPost('get_process_data', {}, function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
var slist = rdata.data.process_white;
|
||||
|
||||
var body = '';
|
||||
for (var i = 0; i < slist.length; i++) {
|
||||
body += "<tr>\
|
||||
<td>"+slist[i]+"</td>\
|
||||
<td style='text-align: right;'><a class='btlink safe_path_delete' row='"+i+"'>删除</a></td>\
|
||||
</tr>";
|
||||
}
|
||||
|
||||
$('#safe-file-table tbody').html(body);
|
||||
$('.safe_path_delete').click(function(){
|
||||
var id = $(this).attr('row');
|
||||
ssPost('del_safe_proccess_name',{tag:tag,index:id}, function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
showMsg(rdata.msg, function(){
|
||||
setSafeConfigProcessList(tag);
|
||||
},{icon:rdata.status?1:2,shade: [0.3, '#000']},2000);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function setSafeConfigProcess(tag, alist){
|
||||
layer.open({
|
||||
type: 1,
|
||||
area: ['700px','535px'],
|
||||
title: '配置【进程白名单】',
|
||||
content: "<form class='bt-form pd20'>\
|
||||
<div style='border-bottom:#ccc 1px solid;margin-bottom:10px;padding-bottom:10px'>\
|
||||
<input class='bt-input-text' name='s_name' id='s_name' type='text' value='' style='width:370px;margin-right:5px;' placeholder='完整的进程名'>\
|
||||
<button type='button' class='btn btn-success btn-sm va0 pull-right add_process_white'>添加</button>\
|
||||
</div>\
|
||||
<div class='divtable'>\
|
||||
<div id='safe-file-table' class='table_head_fix' style='max-height:300px;overflow:auto;border:#ddd 1px solid'>\
|
||||
<table class='table table-hover' style='border:none'>\
|
||||
<thead>\
|
||||
<tr>\
|
||||
<th width='360'>进程名称</th>\
|
||||
<th style='text-align: right;'>操作</th>\
|
||||
</tr>\
|
||||
</thead>\
|
||||
<tbody></tbody>\
|
||||
</table>\
|
||||
</div>\
|
||||
</div>\
|
||||
<ul class='help-info-text c7 ptb10' style='margin-top: 5px;'>\
|
||||
<li>【进程名称】请填写完整的进程名称,如: mysqld</li>\
|
||||
<li>【说明】在白名单列表中的进程将不再检测范围,建议将常用软件的进程添加进白名单</li>\
|
||||
</ul>\
|
||||
</form>",
|
||||
success:function(){
|
||||
$('.add_process_white').click(function(){
|
||||
var process_name = $('input[name="s_name"]').val();
|
||||
ssPost('add_process_white',{process_name:process_name}, function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
showMsg(rdata.msg, function(){
|
||||
setSafeConfigProcessList(tag);
|
||||
},{icon:rdata.status?1:2,shade: [0.3, '#000']},2000);
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
setSafeConfigProcessList(tag);
|
||||
|
||||
|
||||
}
|
||||
|
||||
function setSafeConfig(tag, alist){
|
||||
|
||||
if ($.inArray(tag, ['bin', 'service', 'home', 'user', 'bin', 'cron'])>-1){
|
||||
setSafeConfigPath(tag,alist);
|
||||
}
|
||||
|
||||
if ($.inArray(tag, ['ssh'])>-1){
|
||||
setSafeConfigSsh(tag,alist);
|
||||
}
|
||||
|
||||
if ($.inArray(tag, ['process'])>-1){
|
||||
setSafeConfigProcess(tag,alist);
|
||||
}
|
||||
}
|
||||
|
||||
//设置安全状态
|
||||
function setSafeStatus(obj,tag){
|
||||
var o = $(obj).prev();
|
||||
var status = $(o).prop('checked');
|
||||
ssPost('set_safe_status', {tag:tag,status:!status}, function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
|
||||
if (!rdata.status){
|
||||
layer.msg(rdata.msg,{icon:0,time:2000,shade: [0.3, '#000']});
|
||||
$(o).prop('checked',status);
|
||||
return;
|
||||
}
|
||||
layer.msg("配置成功!",{icon:1,time:2000,shade: [0.3, '#000']});
|
||||
});
|
||||
}
|
||||
|
||||
function ssConfigList(){
|
||||
|
||||
ssPost('conf',{},function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
var libs = rdata.data;
|
||||
// console.log(libs);
|
||||
var body = '';
|
||||
for (var i in libs) {
|
||||
|
||||
if (i == 'open'){
|
||||
continue;
|
||||
}
|
||||
|
||||
var checked = '';
|
||||
if (libs[i].open){
|
||||
checked = 'checked';
|
||||
}
|
||||
|
||||
body += '<tr>' +
|
||||
'<td>' + libs[i].name + '</td>' +
|
||||
'<td>' + libs[i].ps + '</td>' +
|
||||
'<td>\
|
||||
<div class="ssh-item">\
|
||||
<input class="btswitch btswitch-ios" id="sys_service_'+i +'" type="checkbox" '+checked+'>\
|
||||
<label class="btswitch-btn service_switch" for="sys_service_'+i+'" style="width: 2em; height: 1.1em;padding:1px;"></label>\
|
||||
</div>\
|
||||
</td>'+
|
||||
'<td style="text-align: right;"><a id="conf_sys_service_'+i+'" class="btlink set_safe_config">配置</a></td>' +
|
||||
'</tr>';
|
||||
}
|
||||
|
||||
var con = '<div class="divtable" id="system_safe_list" style="margin-right:10px;max-height: 320px; overflow: auto; margin-right: 0px;">' +
|
||||
'<table class="table table-hover" width="100%" cellspacing="0" cellpadding="0" border="0">' +
|
||||
'<thead>' +
|
||||
'<tr>' +
|
||||
'<th>名称</th>' +
|
||||
'<th>描述</th>' +
|
||||
'<th width="40">状态</th>' +
|
||||
'<th style="text-align: right;" width="50">操作</th>' +
|
||||
'</tr>' +
|
||||
'</thead>' +
|
||||
'<tbody>' + body + '</tbody>' +
|
||||
'</table>' +
|
||||
'</div>' +
|
||||
'<ul class="help-info-text c7 pull-left">\
|
||||
<li>开启系统加固功能后,一些如软件安装等敏感操作将被禁止</li>\
|
||||
<li>开启【SSH服务加固】之后,用户登录SSH的行为将受到监控,若连续多次登录失败,将采取封IP措施</li>\
|
||||
<li>【异常进程监控】与【SSH服务加固】会占用一定服务器开销</li>\
|
||||
<li><span style="color:red;">【注意】如果您需要安装软件或插件,请先将系统加固关闭!</span></li>\
|
||||
</ul>';
|
||||
|
||||
$('.soft-man-con').html(con);
|
||||
|
||||
$('#system_safe_list .service_switch').click(function(){
|
||||
var val = $(this).prev().attr('id');
|
||||
val = val.replace('sys_service_','');
|
||||
setSafeStatus(this,val);
|
||||
});
|
||||
|
||||
$('.set_safe_config').click(function(){
|
||||
var name = $(this).attr('id');
|
||||
// console.log(name);
|
||||
name = name.replace('conf_sys_service_','');
|
||||
setSafeConfig(name, libs[name]);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
function ssOpLogList(p){
|
||||
ssPost('op_log',{p:p},function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
var plist = rdata.data.data;
|
||||
|
||||
var body = '';
|
||||
for (var i = 0; i < plist.length; i++) {
|
||||
body += "<tr>\
|
||||
<td><em class='dlt-num'>" + plist[i].addtime + "</em></td>\
|
||||
<td>" + plist[i].log + "</td>\
|
||||
</tr>";
|
||||
}
|
||||
|
||||
$("#system_safe_log_list tbody").html(body);
|
||||
$("#system_safe_log_page").html(rdata.data.page);
|
||||
});
|
||||
}
|
||||
|
||||
function ssOpLog(){
|
||||
var con = '<div class="divtable" id="system_safe_log_list" style="margin-right:10px;max-height: 380px; overflow: auto; margin-right: 0px;">\
|
||||
<table class="table table-hover" width="100%" cellspacing="0" cellpadding="0" border="0">\
|
||||
<thead><tr><th style="width:135px;">时间</th><th>详情</th></tr></thead>\
|
||||
<tbody></tbody>\
|
||||
</table>\
|
||||
</div>\
|
||||
<div id="system_safe_log_page" class="dataTables_paginate paging_bootstrap page"></div>';
|
||||
$('.soft-man-con').html(con);
|
||||
ssOpLogList(1);
|
||||
}
|
||||
|
||||
|
||||
function ssLogAuditList(){
|
||||
ssPost('get_sys_logfiles',{},function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
var plist = rdata.data;
|
||||
var option = '';
|
||||
// console.log(plist);
|
||||
for (var i = 0; i < plist.length; i++) {
|
||||
option += '<option value="'+plist[i]['name']+'">'+plist[i]['name'] +' - '+plist[i]['title']+'</option>';
|
||||
}
|
||||
|
||||
$("#system_safe_log_audit").html(option);
|
||||
var log_name = $('#system_safe_log_audit option:first').val();
|
||||
ssLogAuditFile(log_name);
|
||||
|
||||
$('#system_safe_log_audit').change(function(){
|
||||
var log_name = $('#system_safe_log_audit option:selected').val();
|
||||
ssLogAuditFile(log_name);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function ssLogAuditFileRenderString(data){
|
||||
|
||||
var tbody = '<textarea style="margin: 0px;width: 100%;height: 380px;background-color: #333;color:#fff; padding:0 5px" id="system_safe_log_audit_str"></textarea>';
|
||||
$("#system_safe_log_audit_list").html(tbody);
|
||||
var ob = document.getElementById('system_safe_log_audit_str');
|
||||
ob.scrollTop = ob.scrollHeight;
|
||||
|
||||
$("#system_safe_log_audit_str").html(data);
|
||||
}
|
||||
|
||||
function ssLogAuditFileRenderObject(plist){
|
||||
|
||||
var pre_html = '<table class="table table-hover" width="100%" cellspacing="0" cellpadding="0" border="0">\
|
||||
<thead><tr><th>时间</th><th>角色</th><th>事件</th></tr></thead>\
|
||||
<tbody></tbody>\
|
||||
</table>';
|
||||
$("#system_safe_log_audit_list").html(pre_html);
|
||||
|
||||
if (plist.length>0){
|
||||
var tmp = plist[0];
|
||||
// console.log(tmp);
|
||||
var thead = '';
|
||||
tbody += '<tr>'
|
||||
for (var i in tmp) {
|
||||
tbody+='<th>'+ i + '</th>';
|
||||
}
|
||||
tbody += '</tr>';
|
||||
$("#system_safe_log_audit_list thead").html(tbody);
|
||||
}
|
||||
|
||||
|
||||
var tbody = '';
|
||||
for (var i = 0; i < plist.length; i++) {
|
||||
tbody += '<tr>';
|
||||
for (var vv in plist[i]) {
|
||||
tbody+= '<td>'+ plist[i][vv] + '</td>'
|
||||
}
|
||||
tbody += '</tr>';
|
||||
}
|
||||
|
||||
$("#system_safe_log_audit_list tbody").html(tbody);
|
||||
}
|
||||
|
||||
function ssLogAuditFile(log_name){
|
||||
// ssPost('get_sys_log',{log_name:log_name},function(rdata){
|
||||
// try{
|
||||
// var rdata = $.parseJSON(rdata.data);
|
||||
// if (typeof(rdata.data) == 'object'){
|
||||
|
||||
// if (!rdata.status){
|
||||
// layer.msg(rdata.msg,{icon:0,time:2000,shade: [0.3, '#000']});
|
||||
// return;
|
||||
// }
|
||||
// var plist = rdata.data;
|
||||
// ssLogAuditFileRenderObject(plist);
|
||||
// }
|
||||
// }catch(e){
|
||||
// if (typeof(rdata.data) == 'string'){
|
||||
// ssLogAuditFileRenderString(rdata.data);
|
||||
// }
|
||||
// }
|
||||
// });
|
||||
|
||||
ssPostCallbak('get_sys_log',{log_name:log_name},function(rdata){
|
||||
try{
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
if (typeof(rdata.data) == 'object'){
|
||||
if (!rdata.status){
|
||||
layer.msg(rdata.msg,{icon:0,time:2000,shade: [0.3, '#000']});
|
||||
return;
|
||||
}
|
||||
var plist = rdata.data;
|
||||
ssLogAuditFileRenderObject(plist);
|
||||
}
|
||||
}catch(e){
|
||||
if (typeof(rdata.data) == 'string'){
|
||||
ssLogAuditFileRenderString(rdata.data);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function ssLogAudit(){
|
||||
var con = '<select id="system_safe_log_audit" class="bt-input-text mr20" style="width:50%;margin-bottom: 3px;">\
|
||||
<option value="0">请选择</option>\
|
||||
</select>\
|
||||
<div class="divtable" id="system_safe_log_audit_list" style="margin-right:10px;height: 380px; overflow: auto; margin-right: 0px;"></div>';
|
||||
$('.soft-man-con').html(con);
|
||||
ssLogAuditList();
|
||||
}
|
||||
|
||||
function ssLockAddressList(){
|
||||
ssPost('get_ssh_limit_info',{},function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
var libs = rdata.data;
|
||||
var tbody = '';
|
||||
for (var i in libs) {
|
||||
var end_time = libs[i].end;
|
||||
var time_title = '手动解封';
|
||||
if (end_time != '0'){
|
||||
time_title = '自动解封时间:'+end_time;
|
||||
}
|
||||
tbody += '<tr>' +
|
||||
'<td style="width:100px;">' + libs[i].address + '</td>' +
|
||||
'<td style="width:100px;">'+time_title+'</td>' +
|
||||
'<td style="text-align: right;"><a ip="'+libs[i].address+'" class="btlink remove_ssh_limit">立即解封</a></td>' +
|
||||
'</tr>';
|
||||
}
|
||||
|
||||
$('#system_lock_address tbody').html(tbody);
|
||||
$('#system_lock_address .remove_ssh_limit').click(function(){
|
||||
var address = $(this).attr('ip');
|
||||
ssPost('remove_ssh_limit', {ip:address}, function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
showMsg(rdata.msg, function(){
|
||||
ssLockAddressList();
|
||||
},{icon:rdata.status?1:2,shade: [0.3, '#000']},2000);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function ssLockAddress(){
|
||||
|
||||
var con = '<div style="margin-bottom:10px;">\
|
||||
<input class="bt-input-text" name="s_address" type="text" value="" style="width:250px;margin-right:12px;" placeholder="IP地址">\
|
||||
<button class="btn btn-success btn-sm va0 add_lock_address">添加</button>\
|
||||
</div>\
|
||||
<div class="divtable" id="system_lock_address" style="margin-right:10px;max-height: 320px; overflow: auto; margin-right: 0px;">' +
|
||||
'<table class="table table-hover" width="100%" cellspacing="0" cellpadding="0" border="0">' +
|
||||
'<thead>' +
|
||||
'<tr>' +
|
||||
'<th>IP</th>' +
|
||||
'<th>解封时间</th>' +
|
||||
'<th style="text-align: right;" width="50">操作</th>' +
|
||||
'</tr>' +
|
||||
'</thead>' +
|
||||
'<tbody></tbody>' +
|
||||
'</table>' +
|
||||
'</div>' +
|
||||
'<ul class="help-info-text c7 pull-left">\
|
||||
<li>【封锁IP】此处封锁的IP仅针对SSH服务,即被封锁的IP将无法连接SSH</li>\
|
||||
<li>【添加】手动添加的IP封锁只能手动解封!</li>\
|
||||
</ul>';
|
||||
|
||||
$('.soft-man-con').html(con);
|
||||
|
||||
$('.add_lock_address').click(function(){
|
||||
var address = $('input[name="s_address"]').val();
|
||||
ssPost('add_ssh_limit', {ip:address}, function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
showMsg(rdata.msg, function(){
|
||||
ssLockAddressList();
|
||||
},{icon:rdata.status?1:2,shade: [0.3, '#000']},2000);
|
||||
});
|
||||
});
|
||||
ssLockAddressList();
|
||||
}
|
||||
Executable
+1140
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"open": true,
|
||||
"excludePath": [ "cache", "threadcache", "log", "logs", "config", "runtime", "temp","tmp","caches","tmps"],
|
||||
"protectExt": [ "php", "html", "htm", "shtml", "tpl", "js", "css", "jsp", "do" ]
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 556 B |
Executable
+1163
File diff suppressed because it is too large
Load Diff
Executable
+628
@@ -0,0 +1,628 @@
|
||||
# coding:utf-8
|
||||
|
||||
import sys
|
||||
import io
|
||||
import os
|
||||
import time
|
||||
import json
|
||||
import re
|
||||
import psutil
|
||||
from datetime import datetime
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
sys.path.append(os.getcwd() + "/class/core")
|
||||
import mw
|
||||
|
||||
app_debug = False
|
||||
if mw.isAppleSystem():
|
||||
app_debug = True
|
||||
|
||||
|
||||
class App:
|
||||
|
||||
__total = 'total.json'
|
||||
__sites = []
|
||||
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
def getPluginName(self):
|
||||
return 'tamper_proof_py'
|
||||
|
||||
def getPluginDir(self):
|
||||
return mw.getPluginDir() + '/' + self.getPluginName()
|
||||
|
||||
def getServerDir(self):
|
||||
return mw.getServerDir() + '/' + self.getPluginName()
|
||||
|
||||
def getInitDFile(self):
|
||||
if app_debug:
|
||||
return '/tmp/' + self.getPluginName()
|
||||
return '/etc/init.d/' + self.getPluginName()
|
||||
|
||||
def getInitDTpl(self):
|
||||
path = self.getPluginDir() + "/init.d/" + self.getPluginName() + ".tpl"
|
||||
return path
|
||||
|
||||
def getArgs(self):
|
||||
args = sys.argv[2:]
|
||||
tmp = {}
|
||||
args_len = len(args)
|
||||
|
||||
if args_len == 1:
|
||||
t = args[0].strip('{').strip('}')
|
||||
if t.strip() == '':
|
||||
tmp = []
|
||||
else:
|
||||
t = t.split(':')
|
||||
tmp[t[0]] = t[1]
|
||||
elif args_len > 1:
|
||||
for i in range(len(args)):
|
||||
t = args[i].split(':')
|
||||
tmp[t[0]] = t[1]
|
||||
return tmp
|
||||
|
||||
def checkArgs(self, data, ck=[]):
|
||||
for i in range(len(ck)):
|
||||
if not ck[i] in data:
|
||||
return (False, mw.returnJson(False, '参数:(' + ck[i] + ')没有!'))
|
||||
return (True, mw.returnJson(True, 'ok'))
|
||||
|
||||
def getTotal(self, siteName=None, day=None):
|
||||
defaultTotal = {"total": 0, "delete": 0,
|
||||
"create": 0, "modify": 0, "move": 0}
|
||||
if siteName:
|
||||
total = {}
|
||||
total_path = self.getServerDir() + '/sites/' + siteName + '/' + self.__total
|
||||
if not os.path.exists(total_path):
|
||||
total['site'] = defaultTotal
|
||||
else:
|
||||
total_data = mw.readFile(total_path)
|
||||
if total_data['site']:
|
||||
total['site'] = json.loads(total_data['site'])
|
||||
else:
|
||||
total['site'] = defaultTotal
|
||||
|
||||
if not day:
|
||||
day = time.strftime("%Y-%m-%d", time.localtime())
|
||||
total_day_path = self.getServerDir() + '/sites/' + siteName + '/day/total.json'
|
||||
if not os.path.exists(total_day_path):
|
||||
total['day'] = defaultTotal
|
||||
else:
|
||||
total['day'] = mw.readFile(total_day_path)
|
||||
if total['day']:
|
||||
total['day'] = json.loads(total['day'])
|
||||
else:
|
||||
total['day'] = defaultTotal
|
||||
else:
|
||||
filename = self.getServerDir() + '/sites/' + self.__total
|
||||
if os.path.exists(filename):
|
||||
total = json.loads(mw.readFile(filename))
|
||||
else:
|
||||
total = defaultTotal
|
||||
return total
|
||||
|
||||
def getSites(self):
|
||||
sites_path = self.getServerDir() + '/sites.json'
|
||||
t = mw.readFile(sites_path)
|
||||
if not os.path.exists(sites_path) or not t:
|
||||
mw.writeFile(sites_path, '[]')
|
||||
data = json.loads(mw.readFile(sites_path))
|
||||
|
||||
is_write = False
|
||||
rm_keys = ['lock', 'bak_open']
|
||||
for i in data:
|
||||
i_keys = i.keys()
|
||||
if not 'open' in i_keys:
|
||||
i['open'] = False
|
||||
for o in rm_keys:
|
||||
if o in i_keys:
|
||||
if i[o]:
|
||||
i['open'] = True
|
||||
i.pop(o)
|
||||
is_write = True
|
||||
if is_write:
|
||||
mw.writeFile(sites_path, json.dumps(data))
|
||||
|
||||
self.__sites = data
|
||||
return data
|
||||
|
||||
def writeSites(self, data):
|
||||
mw.writeFile(self.getServerDir() + '/sites.json', json.dumps(data))
|
||||
# mw.ExecShell('/etc/init.d/bt_tamper_proof reload')
|
||||
|
||||
def __getFind(self, siteName):
|
||||
data = self.getSites()
|
||||
for siteInfo in data:
|
||||
if siteName == siteInfo['siteName']:
|
||||
return siteInfo
|
||||
return None
|
||||
|
||||
def writeLog(self, log):
|
||||
mw.writeLog('防篡改程序', log)
|
||||
|
||||
def saveSiteConfig(self, siteInfo):
|
||||
data = self.getSites()
|
||||
for i in range(len(data)):
|
||||
if data[i]['siteName'] != siteInfo['siteName']:
|
||||
continue
|
||||
data[i] = siteInfo
|
||||
break
|
||||
self.writeSites(data)
|
||||
|
||||
def syncSites(self):
|
||||
data = self.getSites()
|
||||
sites = mw.M('sites').field('name,path').select()
|
||||
|
||||
config_path = self.getPluginDir() + '/conf/config.json'
|
||||
config = json.loads(mw.readFile(config_path))
|
||||
names = []
|
||||
n = 0
|
||||
|
||||
# print(config)
|
||||
for siteTmp in sites:
|
||||
names.append(siteTmp['name'])
|
||||
siteInfo = self.__getFind(siteTmp['name'])
|
||||
if siteInfo:
|
||||
if siteInfo['path'] != siteTmp['path']:
|
||||
siteInfo['path'] = siteTmp['path']
|
||||
self.saveSiteConfig(siteInfo)
|
||||
data = self.getSites()
|
||||
continue
|
||||
siteInfo = {}
|
||||
siteInfo['siteName'] = siteTmp['name']
|
||||
siteInfo['path'] = siteTmp['path']
|
||||
siteInfo['open'] = False
|
||||
siteInfo['excludePath'] = config['excludePath']
|
||||
siteInfo['protectExt'] = config['protectExt']
|
||||
data.append(siteInfo)
|
||||
n += 1
|
||||
|
||||
newData = []
|
||||
for siteInfoTmp in data:
|
||||
if siteInfoTmp['siteName'] in names:
|
||||
newData.append(siteInfoTmp)
|
||||
else:
|
||||
mw.execShell("rm -rf " + self.getServerDir() +
|
||||
'/sites/' + siteInfoTmp['siteName'])
|
||||
n += 1
|
||||
if n > 0:
|
||||
self.writeSites(newData)
|
||||
self.__sites = None
|
||||
|
||||
def initDreplace(self):
|
||||
file_tpl = self.getInitDTpl()
|
||||
service_path = self.getServerDir()
|
||||
|
||||
initD_path = service_path + '/init.d'
|
||||
if not os.path.exists(initD_path):
|
||||
os.mkdir(initD_path)
|
||||
|
||||
# init.d
|
||||
file_bin = initD_path + '/' + self.getPluginName()
|
||||
if not os.path.exists(file_bin):
|
||||
# initd replace
|
||||
content = mw.readFile(file_tpl)
|
||||
content = content.replace('{$SERVER_PATH}', service_path)
|
||||
mw.writeFile(file_bin, content)
|
||||
mw.execShell('chmod +x ' + file_bin)
|
||||
|
||||
# systemd
|
||||
# /usr/lib/systemd/system
|
||||
systemDir = mw.systemdCfgDir()
|
||||
systemService = systemDir + '/tamper_proof_py.service'
|
||||
systemServiceTpl = self.getPluginDir() + '/init.d/tamper_proof_py.service.tpl'
|
||||
if os.path.exists(systemDir) and not os.path.exists(systemService):
|
||||
se_content = mw.readFile(systemServiceTpl)
|
||||
se_content = se_content.replace('{$SERVER_PATH}', service_path)
|
||||
mw.writeFile(systemService, se_content)
|
||||
mw.execShell('systemctl daemon-reload')
|
||||
|
||||
return file_bin
|
||||
|
||||
def getDays(self, path):
|
||||
days = []
|
||||
if not os.path.exists(path):
|
||||
os.makedirs(path)
|
||||
for dirname in os.listdir(path):
|
||||
if dirname == '..' or dirname == '.' or dirname == 'total.json':
|
||||
continue
|
||||
if not os.path.isdir(path + '/' + dirname):
|
||||
continue
|
||||
days.append(dirname)
|
||||
days = sorted(days, reverse=True)
|
||||
return days
|
||||
|
||||
def status(self):
|
||||
'''
|
||||
状态
|
||||
'''
|
||||
initd_file = self.getServerDir() + '/init.d/' + self.getPluginName()
|
||||
if not os.path.exists(initd_file):
|
||||
return 'stop'
|
||||
cmd = initd_file + ' status|grep already'
|
||||
data = mw.execShell(cmd)
|
||||
if data[0] != '':
|
||||
return 'start'
|
||||
return 'stop'
|
||||
|
||||
def tpOp(self, method):
|
||||
file = self.initDreplace()
|
||||
if not mw.isAppleSystem():
|
||||
cmd = 'systemctl ' + method + ' ' + self.getPluginName()
|
||||
data = mw.execShell(cmd)
|
||||
if data[1] == '':
|
||||
return mw.returnJson(True, '操作成功')
|
||||
return mw.returnJson(False, '操作失败')
|
||||
|
||||
cmd = file + ' ' + method
|
||||
data = mw.execShell(cmd)
|
||||
if data[1] == '':
|
||||
return mw.returnJson(True, '操作成功')
|
||||
return mw.returnJson(False, '操作失败')
|
||||
|
||||
def start(self):
|
||||
return self.tpOp('start')
|
||||
|
||||
def restart(self):
|
||||
return self.tpOp('restart')
|
||||
|
||||
def service_admin(self):
|
||||
if mw.isAppleSystem():
|
||||
return mw.returnJson(False, '仅支持Linux!')
|
||||
|
||||
args = self.getArgs()
|
||||
check = self.checkArgs(args, ['serviceStatus'])
|
||||
if not check[0]:
|
||||
return check[1]
|
||||
|
||||
method = args['serviceStatus']
|
||||
return self.tpOp(method)
|
||||
|
||||
def initd_status(self):
|
||||
if mw.isAppleSystem():
|
||||
return "Apple Computer does not support"
|
||||
shell_cmd = 'systemctl status %s | grep loaded | grep "enabled;"' % (
|
||||
self.getPluginName())
|
||||
data = mw.execShell(shell_cmd)
|
||||
if data[0] == '':
|
||||
return 'fail'
|
||||
return 'ok'
|
||||
|
||||
def initd_install(self):
|
||||
if mw.isAppleSystem():
|
||||
return "Apple Computer does not support"
|
||||
|
||||
mw.execShell('systemctl enable ' + self.getPluginName())
|
||||
return 'ok'
|
||||
|
||||
def initd_uninstall(self):
|
||||
if mw.isAppleSystem():
|
||||
return "Apple Computer does not support"
|
||||
|
||||
mw.execShell('systemctl disable ' + self.getPluginName())
|
||||
return 'ok'
|
||||
|
||||
def set_site_status(self):
|
||||
args = self.getArgs()
|
||||
check = self.checkArgs(args, ['siteName'])
|
||||
if not check[0]:
|
||||
return check[1]
|
||||
|
||||
siteName = args['siteName']
|
||||
siteInfo = self.__getFind(siteName)
|
||||
if not siteInfo:
|
||||
return mw.returnJson(False, '指定站点不存在!')
|
||||
try:
|
||||
siteInfo['open'] = not siteInfo['open']
|
||||
except:
|
||||
siteInfo['open'] = not siteInfo['open']
|
||||
|
||||
m_logs = {True: '开启', False: '关闭'}
|
||||
self.writeLog('%s站点[%s]防篡改保护' %
|
||||
(m_logs[siteInfo['open']], siteInfo['siteName']))
|
||||
self.siteReload(siteInfo)
|
||||
self.saveSiteConfig(siteInfo)
|
||||
self.restart()
|
||||
return mw.returnJson(True, '设置成功!')
|
||||
|
||||
def get_run_logs(self):
|
||||
log_file = self.getServerDir() + '/service.log'
|
||||
return mw.returnJson(True, mw.getLastLine(log_file, 200))
|
||||
|
||||
# 取文件指定尾行数
|
||||
def getNumLines(self, path, num, p=1):
|
||||
pyVersion = sys.version_info[0]
|
||||
try:
|
||||
import cgi
|
||||
if not os.path.exists(path):
|
||||
return ""
|
||||
start_line = (p - 1) * num
|
||||
count = start_line + num
|
||||
fp = open(path, 'rb')
|
||||
buf = ""
|
||||
fp.seek(-1, 2)
|
||||
if fp.read(1) == "\n":
|
||||
fp.seek(-1, 2)
|
||||
data = []
|
||||
b = True
|
||||
n = 0
|
||||
for i in range(count):
|
||||
while True:
|
||||
newline_pos = str.rfind(str(buf), "\n")
|
||||
pos = fp.tell()
|
||||
if newline_pos != -1:
|
||||
if n >= start_line:
|
||||
line = buf[newline_pos + 1:]
|
||||
try:
|
||||
data.append(json.loads(cgi.escape(line)))
|
||||
except:
|
||||
pass
|
||||
buf = buf[:newline_pos]
|
||||
n += 1
|
||||
break
|
||||
else:
|
||||
if pos == 0:
|
||||
b = False
|
||||
break
|
||||
to_read = min(4096, pos)
|
||||
fp.seek(-to_read, 1)
|
||||
t_buf = fp.read(to_read)
|
||||
if pyVersion == 3:
|
||||
if type(t_buf) == bytes:
|
||||
t_buf = t_buf.decode('utf-8')
|
||||
buf = t_buf + buf
|
||||
fp.seek(-to_read, 1)
|
||||
if pos - to_read == 0:
|
||||
buf = "\n" + buf
|
||||
if not b:
|
||||
break
|
||||
fp.close()
|
||||
except:
|
||||
return []
|
||||
if len(data) >= 2000:
|
||||
arr = []
|
||||
for d in data:
|
||||
arr.insert(0, json.dumps(d))
|
||||
mw.writeFile(path, "\n".join(arr))
|
||||
return data
|
||||
|
||||
def get_safe_logs(self):
|
||||
|
||||
args = self.getArgs()
|
||||
check = self.checkArgs(args, ['siteName'])
|
||||
if not check[0]:
|
||||
return check[1]
|
||||
|
||||
siteName = args['siteName']
|
||||
|
||||
data = {}
|
||||
path = self.getPluginDir() + '/sites/' + siteName + '/day'
|
||||
data['days'] = self.getDays(path)
|
||||
|
||||
if not data['days']:
|
||||
data['logs'] = []
|
||||
else:
|
||||
p = 1
|
||||
if hasattr(args, 'p'):
|
||||
p = args['p']
|
||||
|
||||
day = data['days'][0]
|
||||
if hasattr(args, 'day'):
|
||||
day = args['day']
|
||||
data['get_day'] = day
|
||||
logs_path = path + '/' + day + '/logs.json'
|
||||
data['logs'] = self.getNumLines(logs_path, 2000, int(p))
|
||||
return mw.returnJson(True, 'ok', data)
|
||||
|
||||
def get_site_find(self):
|
||||
args = self.getArgs()
|
||||
check = self.checkArgs(args, ['siteName'])
|
||||
if not check[0]:
|
||||
return check[1]
|
||||
|
||||
siteName = args['siteName']
|
||||
data = self.__getFind(siteName)
|
||||
return mw.returnJson(True, 'ok', data)
|
||||
|
||||
def siteReload(self, siteInfo):
|
||||
cmd = "python3 {} {}".format(
|
||||
mw.getPluginDir() + '/tamper_proof_service.py unlock', siteInfo['path'])
|
||||
mw.execShell(cmd)
|
||||
tip_file = mw.getServerDir() + '/tips/' + siteInfo['siteName'] + '.pl'
|
||||
if os.path.exists(tip_file):
|
||||
os.remove(tip_file)
|
||||
|
||||
def remove_protect_ext(self):
|
||||
args = self.getArgs()
|
||||
check = self.checkArgs(args, ['siteName', 'protectExt'])
|
||||
if not check[0]:
|
||||
return check[1]
|
||||
|
||||
siteName = args['siteName']
|
||||
protectExt = args['protectExt'].strip()
|
||||
|
||||
siteInfo = self.__getFind(siteName)
|
||||
|
||||
if not siteInfo:
|
||||
return mw.returnJson(False, '指定站点不存在!')
|
||||
if not protectExt:
|
||||
return mw.returnJson(False, '被删除的保护列表不能为空')
|
||||
|
||||
for protectExt in protectExt.split(','):
|
||||
if not protectExt in siteInfo['protectExt']:
|
||||
continue
|
||||
siteInfo['protectExt'].remove(protectExt)
|
||||
self.writeLog('站点[%s]从受保护列表中删除[.%s]' %
|
||||
(siteInfo['siteName'], protectExt))
|
||||
self.siteReload(siteInfo)
|
||||
self.saveSiteConfig(siteInfo)
|
||||
return mw.returnJson(True, '删除成功!')
|
||||
|
||||
def add_protect_ext(self):
|
||||
args = self.getArgs()
|
||||
check = self.checkArgs(args, ['siteName', 'protectExt'])
|
||||
if not check[0]:
|
||||
return check[1]
|
||||
|
||||
siteName = args['siteName']
|
||||
protectExt = args['protectExt'].strip()
|
||||
|
||||
siteInfo = self.__getFind(siteName)
|
||||
if not siteInfo:
|
||||
return mw.returnJson(False, '指定站点不存在!')
|
||||
protectExt = protectExt.lower()
|
||||
for protectExt in protectExt.split("\n"):
|
||||
if protectExt[0] == '/':
|
||||
if os.path.isdir(protectExt):
|
||||
continue
|
||||
if protectExt in siteInfo['protectExt']:
|
||||
continue
|
||||
siteInfo['protectExt'].insert(0, protectExt)
|
||||
self.writeLog('站点[%s]添加文件类型或文件名[.%s]到受保护列表' %
|
||||
(siteInfo['siteName'], protectExt))
|
||||
self.siteReload(siteInfo)
|
||||
self.saveSiteConfig(siteInfo)
|
||||
return mw.returnJson(True, '添加成功!')
|
||||
|
||||
def add_excloud(self):
|
||||
args = self.getArgs()
|
||||
check = self.checkArgs(args, ['siteName', 'excludePath'])
|
||||
if not check[0]:
|
||||
return check[1]
|
||||
|
||||
siteName = args['siteName']
|
||||
excludePath = args['excludePath'].strip()
|
||||
siteInfo = self.__getFind(siteName)
|
||||
if not siteInfo:
|
||||
return mw.returnJson(False, '指定站点不存在!')
|
||||
|
||||
if not excludePath:
|
||||
return mw.returnJson(False, '排除内容不能为空')
|
||||
|
||||
for excludePath in excludePath.split('\n'):
|
||||
if not excludePath:
|
||||
continue
|
||||
if excludePath.find('/') != -1:
|
||||
if not os.path.exists(excludePath):
|
||||
continue
|
||||
excludePath = excludePath.lower()
|
||||
if excludePath[-1] == '/':
|
||||
excludePath = excludePath[:-1]
|
||||
if excludePath in siteInfo['excludePath']:
|
||||
continue
|
||||
siteInfo['excludePath'].insert(0, excludePath)
|
||||
self.writeLog('站点[%s]添加排除目录名[%s]到排除列表' %
|
||||
(siteInfo['siteName'], excludePath))
|
||||
|
||||
self.siteReload(siteInfo)
|
||||
self.saveSiteConfig(siteInfo)
|
||||
return mw.returnJson(True, '添加成功!')
|
||||
|
||||
def remove_excloud(self):
|
||||
args = self.getArgs()
|
||||
check = self.checkArgs(args, ['siteName', 'excludePath'])
|
||||
if not check[0]:
|
||||
return check[1]
|
||||
|
||||
siteName = args['siteName']
|
||||
siteInfo = self.__getFind(siteName)
|
||||
excludePath = args['excludePath'].strip()
|
||||
if excludePath == '':
|
||||
return mw.returnJson(False, '排除文件或目录不能为空')
|
||||
if not siteInfo:
|
||||
return mw.returnJson(False, '指定站点不存在!')
|
||||
|
||||
for excludePath in excludePath.split(','):
|
||||
if not excludePath:
|
||||
continue
|
||||
if not excludePath in siteInfo['excludePath']:
|
||||
continue
|
||||
siteInfo['excludePath'].remove(excludePath)
|
||||
self.writeLog('站点[%s]从排除列表中删除目录名[%s]' %
|
||||
(siteInfo['siteName'], excludePath))
|
||||
self.siteReload(siteInfo)
|
||||
self.saveSiteConfig(siteInfo)
|
||||
return mw.returnJson(True, '删除成功!')
|
||||
|
||||
def sim_test(self):
|
||||
args = self.getArgs()
|
||||
check = self.checkArgs(args, ['path'])
|
||||
if not check[0]:
|
||||
return check[1]
|
||||
|
||||
path = args['path'].strip()
|
||||
if not os.path.exists(path):
|
||||
return mw.returnJson(False, "此目录不存在")
|
||||
|
||||
# 判断是否安装php
|
||||
import site_api
|
||||
php_version = site_api.site_api().getPhpVersion()
|
||||
if not php_version:
|
||||
return mw.returnJson(False, "未安装PHP测试失败")
|
||||
|
||||
php_path = '/www/server/php/' + php_version[1]['version'] + '/bin/php'
|
||||
php_name = path + "/" + str(int(time.time())) + ".php"
|
||||
if os.path.exists(php_name):
|
||||
mw.execShell("rm -rf %s" % php_name)
|
||||
# 写入
|
||||
cmd = php_path + \
|
||||
" -r \"file_put_contents('{}','{}');\"".format(php_name, php_name)
|
||||
mw.execShell(cmd)
|
||||
time.sleep(0.5)
|
||||
if os.path.exists(php_name):
|
||||
if os.path.exists(php_name):
|
||||
mw.execShell("rm -rf %s" % php_name)
|
||||
return mw.returnJson(False, "拦截失败,可能未开启防篡改")
|
||||
return mw.returnJson(True, "拦截成功")
|
||||
|
||||
def set_site_status_all(self):
|
||||
args = self.getArgs()
|
||||
check = self.checkArgs(args, ['siteNames', 'siteState'])
|
||||
if not check[0]:
|
||||
return check[1]
|
||||
|
||||
sites = self.getSites()
|
||||
siteState = True if args['siteState'] == '1' else False
|
||||
siteNames = json.loads(args['siteNames'])
|
||||
m_logs = {True: '开启', False: '关闭'}
|
||||
for i in range(len(sites)):
|
||||
if sites[i]['siteName'] in siteNames:
|
||||
sites[i]['open'] = siteState
|
||||
self.writeLog('%s站点[%s]防篡改保护' %
|
||||
(m_logs[siteState], sites[i]['siteName']))
|
||||
self.writeSites(sites)
|
||||
return mw.returnJson(True, '批量设置成功')
|
||||
|
||||
def get_index(self):
|
||||
self.syncSites()
|
||||
args = self.getArgs()
|
||||
day = None
|
||||
if 'day' in args:
|
||||
day = args['day']
|
||||
|
||||
ser_status = self.status()
|
||||
ser_status_bool = False
|
||||
if ser_status == 'start':
|
||||
ser_status_bool = True
|
||||
data = {}
|
||||
data['open'] = ser_status_bool
|
||||
data['total'] = self.getTotal()
|
||||
data['sites'] = self.getSites()
|
||||
for i in range(len(data['sites'])):
|
||||
data['sites'][i]['total'] = self.getTotal(
|
||||
data['sites'][i]['siteName'], day)
|
||||
return mw.returnJson(True, 'ok', data)
|
||||
|
||||
def get_speed(self):
|
||||
print("12")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
func = sys.argv[1]
|
||||
classApp = App()
|
||||
try:
|
||||
data = eval("classApp." + func + "()")
|
||||
print(data)
|
||||
except Exception as e:
|
||||
print(mw.getTracebackInfo())
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"title": "网站防篡改程序[PY]",
|
||||
"tip": "lib",
|
||||
"name": "tamper_proof_py",
|
||||
"type": "soft",
|
||||
"ps": "事件型防篡改程序,可有效保护网站重要文件不被木马篡改",
|
||||
"versions": "1.0",
|
||||
"shell": "install.sh",
|
||||
"checks": "server/tamper_proof_py",
|
||||
"path": "server/tamper_proof_py",
|
||||
"author": "midoks",
|
||||
"home": "",
|
||||
"date":"2022-01-18",
|
||||
"pid":"4"
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
[Unit]
|
||||
Description=tamper_proof_py server daemon
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=forking
|
||||
ExecStart={$SERVER_PATH}/init.d/tamper_proof_py start
|
||||
ExecStop={$SERVER_PATH}/init.d/tamper_proof_py stop
|
||||
ExecReload={$SERVER_PATH}/init.d/tamper_proof_py reload
|
||||
ExecRestart={$SERVER_PATH}/init.d/tamper_proof_py restart
|
||||
KillMode=process
|
||||
Restart=on-failure
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,95 @@
|
||||
#!/bin/bash
|
||||
# chkconfig: 2345 55 25
|
||||
# description:tamper_proof_service
|
||||
|
||||
### BEGIN INIT INFO
|
||||
# Provides: tamper_proof_service
|
||||
# Required-Start: $all
|
||||
# Required-Stop: $all
|
||||
# Default-Start: 2 3 4 5
|
||||
# Default-Stop: 0 1 6
|
||||
# Short-Description: starts tamper_proof_service
|
||||
# Description: starts the tamper_proof_service
|
||||
### END INIT INFO
|
||||
|
||||
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
|
||||
mw_path={$SERVER_PATH}
|
||||
rootPath=$(dirname "$mw_path")
|
||||
PATH=$PATH:$mw_path/bin
|
||||
|
||||
if [ -f $rootPath/mdserver-web/bin/activate ];then
|
||||
source $rootPath/mdserver-web/bin/activate
|
||||
fi
|
||||
|
||||
# cd /www/server/mdserver-web && python3 plugins/tamper_proof_py/tamper_proof_service.py start
|
||||
sys_start()
|
||||
{
|
||||
isStart=$(ps aux |grep -E "(tamper_proof_service)"|grep -v grep |grep -v 'tamper_proof_py/tamper_proof_service.py start' | grep -v 'tamper_proof_py/tamper_proof_service.py reload' | grep -v 'tamper_proof_py/tamper_proof_service.py restart' | grep -v systemctl | grep -v '/bin/sh' | grep -v '/bin/bash' | awk '{print $2}'|xargs)
|
||||
if [ "$isStart" == '' ];then
|
||||
echo -e "Starting tamper_proof_service... \c"
|
||||
cd $rootPath/mdserver-web
|
||||
nohup python3 plugins/tamper_proof_py/tamper_proof_service.py start &> $mw_path/service.log &
|
||||
sleep 0.5
|
||||
isStart=$(ps aux |grep -E "(tamper_proof_service)"|grep -v grep|awk '{print $2}'|xargs)
|
||||
if [ "$isStart" == '' ];then
|
||||
echo -e "\033[31mfailed\033[0m"
|
||||
echo '------------------------------------------------------'
|
||||
cat $mw_path/service.log
|
||||
echo '------------------------------------------------------'
|
||||
echo -e "\033[31mError: tamper_proof_service startup failed.\033[0m"
|
||||
return;
|
||||
fi
|
||||
echo -e "\033[32mdone\033[0m"
|
||||
else
|
||||
echo "Starting tamper_proof_service (pid $isStart) already running"
|
||||
fi
|
||||
}
|
||||
|
||||
sys_stop()
|
||||
{
|
||||
echo -e "Stopping tamper_proof_service... \c";
|
||||
pids=$(ps aux |grep -E "(tamper_proof_service)"|grep -v grep|grep -v '/bin/bash'|grep -v systemctl | grep -v 'tamper_proof_py/tamper_proof_service.py stop' | grep -v 'tamper_proof_py/tamper_proof_service.py reload' | grep -v 'tamper_proof_py/tamper_proof_service.py restart' |awk '{print $2}'|xargs)
|
||||
arr=($pids)
|
||||
for p in ${arr[@]}
|
||||
do
|
||||
kill -9 $p
|
||||
done
|
||||
cd $rootPath/mdserver-web
|
||||
python3 plugins/tamper_proof_py/tamper_proof_service.py stop
|
||||
echo -e "\033[32mdone\033[0m"
|
||||
}
|
||||
|
||||
sys_status()
|
||||
{
|
||||
isStart=$(ps aux |grep -E "(tamper_proof_service)"|grep -v grep|grep -v "init.d/tamper_proof_py"|grep -v systemctl|awk '{print $2}'|xargs)
|
||||
if [ "$isStart" != '' ];then
|
||||
echo -e "\033[32mtamper_proof_service (pid $isStart) already running\033[0m"
|
||||
else
|
||||
echo -e "\033[32mtamper_proof_service not running\033[0m"
|
||||
fi
|
||||
}
|
||||
|
||||
case "$1" in
|
||||
'start')
|
||||
sys_start
|
||||
;;
|
||||
'stop')
|
||||
sys_stop
|
||||
;;
|
||||
'restart')
|
||||
sys_stop
|
||||
sleep 0.2
|
||||
sys_start
|
||||
;;
|
||||
'reload')
|
||||
sys_stop
|
||||
sleep 0.2
|
||||
sys_start
|
||||
;;
|
||||
'status')
|
||||
sys_status
|
||||
;;
|
||||
*)
|
||||
echo "Usage: systemctl {start|stop|restart|reload} tamper_proof_service"
|
||||
;;
|
||||
esac
|
||||
Executable
+52
@@ -0,0 +1,52 @@
|
||||
#!/bin/bash
|
||||
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
|
||||
export PATH
|
||||
|
||||
curPath=`pwd`
|
||||
rootPath=$(dirname "$curPath")
|
||||
rootPath=$(dirname "$rootPath")
|
||||
serverPath=$(dirname "$rootPath")
|
||||
|
||||
pip install pyinotify
|
||||
if [ -f ${rootPath}/bin/activate ];then
|
||||
source ${rootPath}/bin/activate
|
||||
fi
|
||||
pip install pyinotify
|
||||
|
||||
install_tmp=${rootPath}/tmp/mw_install.pl
|
||||
SYSOS=`uname`
|
||||
VERSION=$2
|
||||
APP_NAME=tamper_proof_py
|
||||
|
||||
Install_App()
|
||||
{
|
||||
echo '正在安装脚本文件...' > $install_tmp
|
||||
mkdir -p $serverPath/tamper_proof_py
|
||||
echo "$VERSION" > $serverPath/tamper_proof_py/version.pl
|
||||
echo 'install complete' > $install_tmp
|
||||
|
||||
#初始化
|
||||
cd ${serverPath}/mdserver-web && python3 plugins/tamper_proof_py/index.py start $VERSION
|
||||
cd ${serverPath}/mdserver-web && python3 plugins/tamper_proof_py/index.py initd_install $VERSION
|
||||
}
|
||||
|
||||
Uninstall_App()
|
||||
{
|
||||
if [ -f /usr/lib/systemd/system/${APP_NAME}.service ] || [ -f /lib/systemd/system/${APP_NAME}.service ] ;then
|
||||
systemctl stop ${APP_NAME}
|
||||
systemctl disable ${APP_NAME}
|
||||
rm -rf /usr/lib/systemd/system/${APP_NAME}.service
|
||||
rm -rf /lib/systemd/system/${APP_NAME}.service
|
||||
systemctl daemon-reload
|
||||
fi
|
||||
|
||||
rm -rf $serverPath/tamper_proof_py
|
||||
echo "uninstall completed" > $install_tmp
|
||||
}
|
||||
|
||||
action=$1
|
||||
if [ "${1}" == 'install' ];then
|
||||
Install_App
|
||||
else
|
||||
Uninstall_App
|
||||
fi
|
||||
@@ -0,0 +1,552 @@
|
||||
|
||||
# +--------------------------------------------------------------------
|
||||
# | 事件型防篡改
|
||||
# +--------------------------------------------------------------------
|
||||
import sys
|
||||
import os
|
||||
import pyinotify
|
||||
import json
|
||||
import shutil
|
||||
import time
|
||||
import psutil
|
||||
import threading
|
||||
import datetime
|
||||
|
||||
sys.path.append(os.getcwd() + "/class/core")
|
||||
import mw
|
||||
|
||||
|
||||
class MyEventHandler(pyinotify.ProcessEvent):
|
||||
_PLUGIN_PATH = '/www/server/tamper_proof_py'
|
||||
_CONFIG = '/config.json'
|
||||
_SITES = '/sites.json'
|
||||
_SITES_DATA = None
|
||||
_CONFIG_DATA = None
|
||||
_DONE_FILE = None
|
||||
bakcupChirdPath = []
|
||||
|
||||
def __init__(self):
|
||||
self._PLUGIN_PATH = self.getServerDir()
|
||||
|
||||
def getPluginName(self):
|
||||
return 'tamper_proof_py'
|
||||
|
||||
def getPluginDir(self):
|
||||
return mw.getPluginDir() + '/' + self.getPluginName()
|
||||
|
||||
def getServerDir(self):
|
||||
return mw.getServerDir() + '/' + self.getPluginName()
|
||||
|
||||
def rmdir(self, filename):
|
||||
try:
|
||||
shutil.rmtree(filename)
|
||||
except:
|
||||
pass
|
||||
|
||||
def check_site_logs(self, Stiename, datetime_time):
|
||||
ret = []
|
||||
cur_month = datetime_time.month
|
||||
cur_day = datetime_time.day
|
||||
cur_year = datetime_time.year
|
||||
cur_hour = datetime_time.hour
|
||||
cur_minute = datetime_time.minute
|
||||
cur_second = int(datetime_time.second)
|
||||
months = {'Jan': '01', 'Feb': '02', 'Mar': '03', 'Apr': '04', 'May': '05', 'Jun': '06', 'Jul': '07',
|
||||
'Aug': '08', 'Sep': '09', 'Oct': '10', 'Nov': '11', 'Dec': '12'}
|
||||
logs_data = self.get_site_logs(Stiename)
|
||||
if not logs_data:
|
||||
return False
|
||||
for i2 in logs_data:
|
||||
try:
|
||||
i = i2.split()
|
||||
# 判断状态码是否为200
|
||||
if int(i[8]) not in [200, 500]:
|
||||
continue
|
||||
# 判断是否为POST
|
||||
day_time = i[3].split('/')[0].split('[')[1]
|
||||
if int(cur_day) != int(day_time):
|
||||
continue
|
||||
month_time = i[3].split('/')[1]
|
||||
if int(months[month_time]) != int(cur_month):
|
||||
continue
|
||||
year_time = i[3].split('/')[2].split(':')[0]
|
||||
if int(year_time) != int(cur_year):
|
||||
continue
|
||||
hour_time = i[3].split('/')[2].split(':')[1]
|
||||
if int(hour_time) != int(cur_hour):
|
||||
continue
|
||||
minute_time = i[3].split('/')[2].split(':')[2]
|
||||
if int(minute_time) != int(cur_minute):
|
||||
continue
|
||||
second_time = int(i[3].split('/')[2].split(':')[3])
|
||||
if cur_second - second_time > 10:
|
||||
continue
|
||||
ret.append(i2)
|
||||
except:
|
||||
continue
|
||||
ret2 = []
|
||||
if len(ret) > 20:
|
||||
for i2 in logs_data:
|
||||
try:
|
||||
i = i2.split()
|
||||
if i[6] != 'POST':
|
||||
continue
|
||||
if int(i[8]) not in [200, 500]:
|
||||
continue
|
||||
# 判断是否为POST
|
||||
day_time = i[3].split('/')[0].split('[')[1]
|
||||
if int(cur_day) != int(day_time):
|
||||
continue
|
||||
month_time = i[3].split('/')[1]
|
||||
if int(months[month_time]) != int(cur_month):
|
||||
continue
|
||||
year_time = i[3].split('/')[2].split(':')[0]
|
||||
if int(year_time) != int(cur_year):
|
||||
continue
|
||||
hour_time = i[3].split('/')[2].split(':')[1]
|
||||
if int(hour_time) != int(cur_hour):
|
||||
continue
|
||||
minute_time = i[3].split('/')[2].split(':')[2]
|
||||
if int(minute_time) != int(cur_minute):
|
||||
continue
|
||||
ret2.append(i2)
|
||||
except:
|
||||
continue
|
||||
if ret2:
|
||||
ret = ret2
|
||||
if len(ret) > 20:
|
||||
return ret[0:20]
|
||||
return ret
|
||||
|
||||
def get_site_logs(self, Stiename):
|
||||
try:
|
||||
pythonV = sys.version_info[0]
|
||||
path = '/www/wwwlogs/' + Stiename + '.log'
|
||||
num = 500
|
||||
if not os.path.exists(path):
|
||||
return []
|
||||
p = 1
|
||||
start_line = (p - 1) * num
|
||||
count = start_line + num
|
||||
fp = open(path, 'rb')
|
||||
buf = ""
|
||||
try:
|
||||
fp.seek(-1, 2)
|
||||
except:
|
||||
return []
|
||||
if fp.read(1) == "\n":
|
||||
fp.seek(-1, 2)
|
||||
data = []
|
||||
b = True
|
||||
n = 0
|
||||
c = 0
|
||||
while c < count:
|
||||
while True:
|
||||
newline_pos = str.rfind(buf, "\n")
|
||||
pos = fp.tell()
|
||||
if newline_pos != -1:
|
||||
if n >= start_line:
|
||||
line = buf[newline_pos + 1:]
|
||||
if line:
|
||||
try:
|
||||
data.append(line)
|
||||
except:
|
||||
c -= 1
|
||||
n -= 1
|
||||
pass
|
||||
else:
|
||||
c -= 1
|
||||
n -= 1
|
||||
buf = buf[:newline_pos]
|
||||
n += 1
|
||||
c += 1
|
||||
break
|
||||
else:
|
||||
if pos == 0:
|
||||
b = False
|
||||
break
|
||||
to_read = min(4096, pos)
|
||||
fp.seek(-to_read, 1)
|
||||
t_buf = fp.read(to_read)
|
||||
if pythonV == 3:
|
||||
t_buf = t_buf.decode('utf-8', errors="ignore")
|
||||
buf = t_buf + buf
|
||||
fp.seek(-to_read, 1)
|
||||
if pos - to_read == 0:
|
||||
buf = "\n" + buf
|
||||
if not b:
|
||||
break
|
||||
fp.close()
|
||||
except:
|
||||
data = []
|
||||
return data
|
||||
|
||||
def process_IN_CREATE(self, event):
|
||||
siteInfo = self.get_SITE_CONFIG(event.pathname)
|
||||
if not self.check_FILE(event, siteInfo, True):
|
||||
return False
|
||||
self._DONE_FILE = event.pathname
|
||||
if event.dir:
|
||||
if os.path.exists(event.pathname):
|
||||
self.rmdir(event.pathname)
|
||||
self.write_LOG('create', siteInfo[
|
||||
'siteName'], event.pathname, datetime.datetime.now())
|
||||
|
||||
else:
|
||||
if os.path.exists(event.pathname):
|
||||
try:
|
||||
src_path = os.path.dirname(event.pathname)
|
||||
os.system("chattr -a {}".format(src_path))
|
||||
os.remove(event.pathname)
|
||||
os.system("chattr +a {}".format(src_path))
|
||||
self.write_LOG('create', siteInfo[
|
||||
'siteName'], event.pathname, datetime.datetime.now())
|
||||
except:
|
||||
pass
|
||||
|
||||
def process_IN_MOVED_TO(self, event):
|
||||
# 检查是否受保护
|
||||
siteInfo = self.get_SITE_CONFIG(event.pathname)
|
||||
if not self.check_FILE(event, siteInfo):
|
||||
return False
|
||||
|
||||
if not getattr(event, 'src_pathname', None):
|
||||
if os.path.isdir(event.pathname):
|
||||
self.rmdir(event.pathname)
|
||||
else:
|
||||
os.remove(event.pathname)
|
||||
self.write_LOG('move', siteInfo[
|
||||
'siteName'], '未知 -> ' + event.pathname)
|
||||
return True
|
||||
|
||||
# 是否为标记文件
|
||||
if event.src_pathname == self._DONE_FILE:
|
||||
return False
|
||||
|
||||
if not os.path.exists(event.src_pathname):
|
||||
# 标记
|
||||
self._DONE_FILE = event.pathname
|
||||
# 还原
|
||||
os.renames(event.pathname, event.src_pathname)
|
||||
|
||||
# 记录日志
|
||||
self.write_LOG('move', siteInfo['siteName'],
|
||||
event.src_pathname + ' -> ' + event.pathname)
|
||||
|
||||
def check_FILE(self, event, siteInfo, create=False):
|
||||
if not siteInfo:
|
||||
return False
|
||||
if self.exclude_PATH(event.pathname):
|
||||
return False
|
||||
if event.dir and create:
|
||||
return True
|
||||
if not event.dir:
|
||||
if not self.protect_EXT(event.pathname):
|
||||
return False
|
||||
return True
|
||||
|
||||
def protect_EXT(self, pathname):
|
||||
if pathname.find('.') == -1:
|
||||
return False
|
||||
extName = pathname.split('.')[-1].lower()
|
||||
siteData = self.get_SITE_CONFIG(pathname)
|
||||
if siteData:
|
||||
if extName in siteData['protectExt']:
|
||||
return True
|
||||
return False
|
||||
|
||||
def exclude_PATH(self, pathname):
|
||||
if pathname.find('/') == -1:
|
||||
return False
|
||||
siteData = self.get_SITE_CONFIG(pathname)
|
||||
return self.exclude_PATH_OF_SITE(pathname, siteData['excludePath'])
|
||||
|
||||
def exclude_PATH_OF_SITE(self, pathname, excludePath):
|
||||
pathname = pathname.lower()
|
||||
dirNames = pathname.split('/')
|
||||
if excludePath:
|
||||
if pathname in excludePath:
|
||||
return True
|
||||
if pathname + '/' in excludePath:
|
||||
return True
|
||||
for ePath in excludePath:
|
||||
if ePath in dirNames:
|
||||
return True
|
||||
if pathname.find(ePath) == 0:
|
||||
return True
|
||||
return False
|
||||
|
||||
def get_SITE_CONFIG(self, pathname):
|
||||
if not self._SITES_DATA:
|
||||
self._SITES_DATA = json.loads(
|
||||
mw.readFile(self._PLUGIN_PATH + self._SITES))
|
||||
for site in self._SITES_DATA:
|
||||
length = len(site['path'])
|
||||
if len(pathname) < length:
|
||||
continue
|
||||
if site['path'] != pathname[:length]:
|
||||
continue
|
||||
return site
|
||||
return None
|
||||
|
||||
def get_CONFIG(self):
|
||||
if self._CONFIG_DATA:
|
||||
return self._CONFIG_DATA
|
||||
self._CONFIG_DATA = json.loads(
|
||||
mw.readFile(self._PLUGIN_PATH + self._CONFIG))
|
||||
|
||||
def list_DIR(self, path, siteInfo): # path 站点路径
|
||||
if not os.path.exists(path):
|
||||
return
|
||||
lock_files = []
|
||||
lock_dirs = []
|
||||
explode_a = ['log', 'logs', 'cache', 'templates', 'template', 'upload', 'img',
|
||||
'image', 'images', 'public', 'static', 'js', 'css', 'tmp', 'temp', 'update', 'data']
|
||||
for name in os.listdir(path):
|
||||
try:
|
||||
filename = "{}/{}".format(path, name).replace('//', '/')
|
||||
lower_name = name.lower()
|
||||
lower_filename = filename.lower()
|
||||
if os.path.isdir(filename): # 是否为目录
|
||||
if lower_name in siteInfo['excludePath']:
|
||||
continue # 是否为排除的文件名
|
||||
# 是否为排除目录
|
||||
if not self.exclude_PATH_OF_SITE(filename, siteInfo['excludePath']):
|
||||
if not lower_name in explode_a: # 是否为固定不锁定目录
|
||||
lock_dirs.append('"' + name + '"')
|
||||
self.list_DIR(filename, siteInfo)
|
||||
continue
|
||||
|
||||
# 是否为受保护的文件名或文件全路径
|
||||
if not lower_name in siteInfo['protectExt'] and not lower_filename in siteInfo['protectExt']:
|
||||
if not self.get_EXT_NAME(lower_name) in siteInfo['protectExt']:
|
||||
continue # 是否为受保护文件类型
|
||||
|
||||
if lower_filename in siteInfo['excludePath']:
|
||||
continue # 是否为排除文件
|
||||
if lower_name in siteInfo['excludePath']:
|
||||
continue # 是否为排除的文件名
|
||||
lock_files.append('"' + name + '"')
|
||||
except:
|
||||
print(mw.getTracebackInfo())
|
||||
if lock_files:
|
||||
self.thread_exec(lock_files, path, 'i')
|
||||
if lock_dirs:
|
||||
self.thread_exec(lock_dirs, path, 'a')
|
||||
|
||||
_thread_count = 0
|
||||
_thread_max = 2 * psutil.cpu_count()
|
||||
|
||||
def thread_exec(self, file_list, cwd, i='i'):
|
||||
while self._thread_count > self._thread_max:
|
||||
time.sleep(0.1)
|
||||
|
||||
self._thread_count += 1
|
||||
cmd = "cd {} && chattr +{} {} > /dev/null".format(
|
||||
cwd, i, ' '.join(file_list))
|
||||
p = threading.Thread(target=self.run_thread, args=(cmd,))
|
||||
p.start()
|
||||
|
||||
def run_thread(self, cmd):
|
||||
os.system(cmd)
|
||||
self._thread_count -= 1
|
||||
|
||||
def get_EXT_NAME(self, fileName):
|
||||
return fileName.split('.')[-1]
|
||||
|
||||
def write_LOG(self, eventType, siteName, pathname, datetime):
|
||||
# 获取网站时间的top100 记录
|
||||
site_log = '/www/wwwlogs/%s.log' % siteName
|
||||
logs_data = []
|
||||
if os.path.exists(site_log):
|
||||
logs_data = self.check_site_logs(siteName, datetime)
|
||||
dateDay = time.strftime("%Y-%m-%d", time.localtime())
|
||||
logPath = self._PLUGIN_PATH + '/sites/' + \
|
||||
siteName + '/day/' + dateDay
|
||||
if not os.path.exists(logPath):
|
||||
os.makedirs(logPath)
|
||||
logFile = os.path.join(logPath, 'logs.json')
|
||||
logVar = [int(time.time()), eventType, pathname, logs_data]
|
||||
fp = open(logFile, 'a+')
|
||||
fp.write(json.dumps(logVar) + "\n")
|
||||
fp.close()
|
||||
logFiles = [
|
||||
logPath + '/total.json',
|
||||
self._PLUGIN_PATH + '/sites/' + siteName + '/day/total.json',
|
||||
self._PLUGIN_PATH + '/sites/total.json'
|
||||
]
|
||||
|
||||
for totalLogFile in logFiles:
|
||||
if not os.path.exists(totalLogFile):
|
||||
totalData = {"total": 0, "delete": 0,
|
||||
"create": 0, "modify": 0, "move": 0}
|
||||
else:
|
||||
dataTmp = mw.readFile(totalLogFile)
|
||||
if dataTmp:
|
||||
totalData = json.loads(dataTmp)
|
||||
else:
|
||||
totalData = {"total": 0, "delete": 0,
|
||||
"create": 0, "modify": 0, "move": 0}
|
||||
|
||||
totalData['total'] += 1
|
||||
totalData[eventType] += 1
|
||||
mw.writeFile(totalLogFile, json.dumps(totalData))
|
||||
|
||||
# 设置.user.ini
|
||||
def set_user_ini(self, path, up=0):
|
||||
os.chdir(path)
|
||||
useriniPath = path + '/.user.ini'
|
||||
if os.path.exists(useriniPath):
|
||||
os.system('chattr +i ' + useriniPath)
|
||||
for p1 in os.listdir(path):
|
||||
try:
|
||||
npath = path + '/' + p1
|
||||
if not os.path.isdir(npath):
|
||||
continue
|
||||
useriniPath = npath + '/.user.ini'
|
||||
if os.path.exists(useriniPath):
|
||||
os.system('chattr +i ' + useriniPath)
|
||||
if up < 3:
|
||||
self.set_user_ini(npath, up + 1)
|
||||
except:
|
||||
continue
|
||||
return True
|
||||
|
||||
def unlock(self, path):
|
||||
os.system('chattr -R -i {} &> /dev/null'.format(path))
|
||||
os.system('chattr -R -a {} &> /dev/null'.format(path))
|
||||
self.set_user_ini(path)
|
||||
|
||||
def close(self, reload=False):
|
||||
# 解除锁定
|
||||
sites = self.get_sites()
|
||||
print("")
|
||||
print("=" * 60)
|
||||
print("【{}】正在关闭防篡改,请稍候...".format(mw.formatDate()))
|
||||
print("-" * 60)
|
||||
for siteInfo in sites:
|
||||
tip = self._PLUGIN_PATH + '/tips/' + siteInfo['siteName'] + '.pl'
|
||||
if not siteInfo['open'] and not os.path.exists(tip):
|
||||
continue
|
||||
if reload and siteInfo['open']:
|
||||
continue
|
||||
if sys.version_info[0] == 2:
|
||||
print(
|
||||
"【{}】|-解锁网站[{}]".format(mw.formatDate(), siteInfo['siteName'])),
|
||||
else:
|
||||
os.system(
|
||||
"echo -e '【{}】|-解锁网站[{}]\c'".format(mw.formatDate(), siteInfo['siteName']))
|
||||
#print("【{}】|-解锁网站[{}]".format(mw.format_date(),siteInfo['siteName']),end=" ")
|
||||
self.unlock(siteInfo['path'])
|
||||
if os.path.exists(tip):
|
||||
os.remove(tip)
|
||||
print("\t=> 完成")
|
||||
print("-" * 60)
|
||||
print('|-防篡改已关闭')
|
||||
print("=" * 60)
|
||||
print(">>>>>>>>>>END<<<<<<<<<<")
|
||||
|
||||
# 获取网站配置列表
|
||||
def get_sites(self):
|
||||
siteconf = self._PLUGIN_PATH + '/sites.json'
|
||||
d = mw.readFile(siteconf)
|
||||
if not os.path.exists(siteconf) or not d:
|
||||
mw.writeFile(siteconf, "[]")
|
||||
data = json.loads(mw.readFile(siteconf))
|
||||
|
||||
# 处理多余字段开始 >>>>>>>>>>
|
||||
is_write = False
|
||||
rm_keys = ['lock', 'bak_open']
|
||||
for i in data:
|
||||
i_keys = i.keys()
|
||||
if not 'open' in i_keys:
|
||||
i['open'] = False
|
||||
for o in rm_keys:
|
||||
if o in i_keys:
|
||||
if i[o]:
|
||||
i['open'] = True
|
||||
i.pop(o)
|
||||
is_write = True
|
||||
if is_write:
|
||||
mw.writeFile(siteconf, json.dumps(data))
|
||||
# 处理多余字段结束 <<<<<<<<<<<<<
|
||||
return data
|
||||
|
||||
def __enter__(self):
|
||||
self.close()
|
||||
|
||||
def __exit__(self, a, b, c):
|
||||
self.close()
|
||||
|
||||
|
||||
def run():
|
||||
# 初始化inotify对像
|
||||
event = MyEventHandler()
|
||||
watchManager = pyinotify.WatchManager()
|
||||
starttime = time.time()
|
||||
mode = pyinotify.IN_CREATE | pyinotify.IN_MOVED_TO
|
||||
|
||||
# 处理网站属性
|
||||
sites = event.get_sites()
|
||||
print("=" * 60)
|
||||
print("【{}】正在启动防篡改,请稍候...".format(mw.formatDate()))
|
||||
print("-" * 60)
|
||||
tip_path = event._PLUGIN_PATH + '/tips/'
|
||||
if not os.path.exists(tip_path):
|
||||
os.makedirs(tip_path)
|
||||
speed_file = event._PLUGIN_PATH + '/speed.pl'
|
||||
for siteInfo in sites:
|
||||
s = time.time()
|
||||
tip = tip_path + siteInfo['siteName'] + '.pl'
|
||||
if not siteInfo['open']:
|
||||
continue
|
||||
if sys.version_info[0] == 2:
|
||||
print("【{}】|-网站[{}]".format(mw.formatDate(),
|
||||
siteInfo['siteName'])),
|
||||
else:
|
||||
os.system(
|
||||
"echo -e '【{}】|-网站[{}]\c'".format(mw.formatDate(), siteInfo['siteName']))
|
||||
# print("【{}】|-网站[{}]".format(public.format_date(),siteInfo['siteName']),end=" ")
|
||||
mw.writeFile(speed_file, "正在处理网站[{}],请稍候...".format(
|
||||
siteInfo['siteName']))
|
||||
if not os.path.exists(tip):
|
||||
event.list_DIR(siteInfo['path'], siteInfo)
|
||||
try:
|
||||
watchManager.add_watch(
|
||||
siteInfo['path'], mode, auto_add=True, rec=True)
|
||||
except:
|
||||
print(mw.getTracebackInfo())
|
||||
tout = round(time.time() - s, 2)
|
||||
mw.writeFile(tip, '1')
|
||||
print("\t\t=> 完成,耗时 {} 秒".format(tout))
|
||||
|
||||
# 启动服务
|
||||
endtime = round(time.time() - starttime, 2)
|
||||
mw.writeLog('防篡改程序', "网站防篡改服务已成功启动,耗时[%s]秒" % endtime)
|
||||
notifier = pyinotify.Notifier(watchManager, event)
|
||||
print("-" * 60)
|
||||
print('|-防篡改服务已启动')
|
||||
print("=" * 60)
|
||||
end_tips = ">>>>>>>>>>END<<<<<<<<<<"
|
||||
print(end_tips)
|
||||
mw.writeFile(speed_file, end_tips)
|
||||
notifier.loop()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if len(sys.argv) > 1:
|
||||
if 'stop' in sys.argv:
|
||||
event = MyEventHandler()
|
||||
event.close()
|
||||
elif 'start' in sys.argv:
|
||||
run()
|
||||
elif 'unlock' in sys.argv:
|
||||
event = MyEventHandler()
|
||||
event.unlock(sys.argv[2])
|
||||
elif 'reload' in sys.argv:
|
||||
event = MyEventHandler()
|
||||
event.close(True)
|
||||
else:
|
||||
print('error')
|
||||
else:
|
||||
run()
|
||||
@@ -171,6 +171,12 @@ def reload():
|
||||
content = mw.readFile(tgbot_tpl)
|
||||
mw.writeFile(tgbot_dst, content)
|
||||
|
||||
tgpush_tpl = getPluginDir() + '/startup/tgpush.py'
|
||||
tgpush_dst = getServerDir() + '/tgpush.py'
|
||||
|
||||
content = mw.readFile(tgpush_tpl)
|
||||
mw.writeFile(tgpush_dst, content)
|
||||
|
||||
ext_src = getPluginDir() + '/startup/extend'
|
||||
ext_dst = getServerDir()
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
"install_pre_inspection":true,
|
||||
"uninstall_pre_inspection":true,
|
||||
"display": 1,
|
||||
"author": "midokos",
|
||||
"author": "midoks",
|
||||
"date": "2023-03-06",
|
||||
"home": "https://core.telegram.org/bots/api",
|
||||
"depend_doc1":"https://github.com/eternnoir/pyTelegramBotAPI",
|
||||
|
||||
@@ -33,6 +33,7 @@ tg_start(){
|
||||
echo -e "starting tgbot... \c"
|
||||
cd $mw_path
|
||||
python3 {$APP_PATH}/tgbot.py >> {$APP_PATH}/task.log &
|
||||
python3 {$APP_PATH}/tgpush.py >> {$APP_PATH}/push.log &
|
||||
isStart=""
|
||||
while [[ "$isStart" == "" ]];
|
||||
do
|
||||
@@ -64,6 +65,15 @@ tg_stop(){
|
||||
kill -9 $p > /dev/null 2>&1
|
||||
done
|
||||
echo -e "\033[32mdone\033[0m"
|
||||
|
||||
|
||||
echo -e "stopping tgpush ... \c";
|
||||
arr=`ps aux|grep 'tgpush.py'|grep -v grep|awk '{print $2}'`
|
||||
for p in ${arr[@]}
|
||||
do
|
||||
kill -9 $p > /dev/null 2>&1
|
||||
done
|
||||
echo -e "\033[32mdone\033[0m"
|
||||
}
|
||||
|
||||
case "$1" in
|
||||
|
||||
@@ -41,24 +41,34 @@ def send_msg(bot, tag='ad', trigger_time=300):
|
||||
mw.writeFile(lock_file, json.dumps(lock_data))
|
||||
# 信号只在一个周期内执行一次|end
|
||||
|
||||
# https://t.me/gjgzs2022 | 22/m
|
||||
# 代付支付宝微信❤️淘宝帮付/💰流量变现💰集团收量/🕵️♀️实名认证/接码✅过人脸👤 | 28/m
|
||||
# https://zhaoziyuan.la/ | 15/m | 2m | next,7/15
|
||||
# 香港高防CDN |9/m
|
||||
keyboard = [
|
||||
[
|
||||
types.InlineKeyboardButton(
|
||||
text="CK资源采集", url='https://ckzy1.com/')
|
||||
text="实卡接码🙎♂️代实名/过人脸🅾️开飞机会员", url='https://t.me/gjgzs2022')
|
||||
],
|
||||
[
|
||||
types.InlineKeyboardButton(
|
||||
text="♻️CMS导航网♻️", url='https://t.me/maccms_jccms')
|
||||
text="香港高防CDN、免实名、试用30天", url='https://www.100dun.com')
|
||||
],
|
||||
[
|
||||
types.InlineKeyboardButton(
|
||||
text="💰流量变现💰", url='https://t.me/taohaozhan')
|
||||
text="🕵️♀️实名认证/接码✅过人脸👤", url='https://t.me/zhanzhangyewu')
|
||||
],
|
||||
[
|
||||
types.InlineKeyboardButton(
|
||||
text="🙎♂️代实名🙍♀️过人脸🅾️国际阿里云腾讯云(赞助商)", url='https://t.me/gjgzs2022')
|
||||
text="代付支付宝微信❤️淘宝帮付", url='https://t.me/Uxuanzhenpin')
|
||||
],
|
||||
[
|
||||
types.InlineKeyboardButton(
|
||||
text="💰流量变现💰集团收量", url='https://t.me/taohaozhan')
|
||||
],
|
||||
[
|
||||
types.InlineKeyboardButton(
|
||||
text="官网", url='https://github.com/midoks/mdserver-web'),
|
||||
types.InlineKeyboardButton(
|
||||
text="💎DigitalVirt(赞助商)", url='https://digitalvirt.com/aff.php?aff=154')
|
||||
],
|
||||
@@ -68,7 +78,9 @@ def send_msg(bot, tag='ad', trigger_time=300):
|
||||
types.InlineKeyboardButton(
|
||||
text="搜索", url='https://bbs.midoks.me/search.php'),
|
||||
types.InlineKeyboardButton(
|
||||
text="@ME", url='tg://user?id=5568699210')
|
||||
text="@ME", url='tg://user?id=5568699210'),
|
||||
types.InlineKeyboardButton(
|
||||
text="100RMB/M", url='tg://user?id=5568699210')
|
||||
]
|
||||
]
|
||||
markup = types.InlineKeyboardMarkup(keyboard)
|
||||
|
||||
@@ -22,6 +22,16 @@ chat_id = -1001578009023
|
||||
# chat_id = 5568699210
|
||||
|
||||
|
||||
def writeLog(log_str):
|
||||
if __name__ == "__main__":
|
||||
print(log_str)
|
||||
|
||||
now = mw.getDateFromNow()
|
||||
log_file = mw.getServerDir() + '/tgbot/task.log'
|
||||
mw.writeFileLog(now + ':' + log_str, log_file, limit_size=5 * 1024)
|
||||
return True
|
||||
|
||||
|
||||
def get_newest_tid():
|
||||
|
||||
api_new = 'https://bbs.midoks.me/plugin.php?id=external_api&f=bbs_newest'
|
||||
@@ -86,7 +96,13 @@ def send_msg(bot, tag='ad', trigger_time=300):
|
||||
|
||||
|
||||
def run(bot):
|
||||
send_msg(bot, 'push_bbs_newest_tid', 300)
|
||||
|
||||
try:
|
||||
send_msg(bot, 'push_bbs_newest_tid', 300)
|
||||
except Exception as e:
|
||||
writeLog('-----push_bbs_newest_tid error start -------')
|
||||
print(mw.getTracebackInfo())
|
||||
writeLog('-----push_bbs_newest_tid error start -------')
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -22,6 +22,16 @@ chat_id = -1001578009023
|
||||
# chat_id = 5568699210
|
||||
|
||||
|
||||
def writeLog(log_str):
|
||||
if __name__ == "__main__":
|
||||
print(log_str)
|
||||
|
||||
now = mw.getDateFromNow()
|
||||
log_file = mw.getServerDir() + '/tgbot/task.log'
|
||||
mw.writeFileLog(now + ':' + log_str, log_file, limit_size=5 * 1024)
|
||||
return True
|
||||
|
||||
|
||||
def send_msg(bot, tag='ad', trigger_time=300):
|
||||
# 信号只在一个周期内执行一次|start
|
||||
lock_file = mw.getServerDir() + '/tgbot/lock.json'
|
||||
@@ -40,27 +50,33 @@ def send_msg(bot, tag='ad', trigger_time=300):
|
||||
mw.writeFile(lock_file, json.dumps(lock_data))
|
||||
# 信号只在一个周期内执行一次|end
|
||||
|
||||
# https://t.me/gjgzs2022 | 19/m
|
||||
# ♻️CMS导航网♻️/💰流量变现💰 | 28/m
|
||||
# CK资源采集 |29/m
|
||||
# https://t.me/gjgzs2022 | 22/m
|
||||
# 代付支付宝微信❤️淘宝帮付/💰流量变现💰集团收量/🕵️♀️实名认证/接码✅过人脸👤 | 28/m
|
||||
# 香港高防CDN |9/m
|
||||
keyboard = [
|
||||
[
|
||||
types.InlineKeyboardButton(
|
||||
text="CK资源采集", url='https://ckzy1.com/')
|
||||
text="实卡接码🙎♂️代实名/过人脸🅾️开飞机会员", url='https://t.me/gjgzs2022')
|
||||
],
|
||||
[
|
||||
types.InlineKeyboardButton(
|
||||
text="♻️CMS导航网♻️", url='https://t.me/maccms_jccms')
|
||||
text="香港高防CDN、免实名、试用30天", url='https://www.100dun.com')
|
||||
],
|
||||
[
|
||||
types.InlineKeyboardButton(
|
||||
text="💰流量变现💰", url='https://t.me/taohaozhan')
|
||||
text="🕵️♀️实名认证/接码✅过人脸👤", url='https://t.me/zhanzhangyewu')
|
||||
],
|
||||
[
|
||||
types.InlineKeyboardButton(
|
||||
text="🙎♂️代实名🙍♀️过人脸🅾️国际阿里云腾讯云(赞助商)", url='https://t.me/gjgzs2022')
|
||||
text="代付支付宝微信❤️淘宝帮付", url='https://t.me/Uxuanzhenpin')
|
||||
],
|
||||
[
|
||||
types.InlineKeyboardButton(
|
||||
text="💰流量变现💰集团收量", url='https://t.me/taohaozhan')
|
||||
],
|
||||
[
|
||||
types.InlineKeyboardButton(
|
||||
text="官网", url='https://github.com/midoks/mdserver-web'),
|
||||
types.InlineKeyboardButton(
|
||||
text="💎DigitalVirt(赞助商)", url='https://digitalvirt.com/aff.php?aff=154')
|
||||
],
|
||||
@@ -70,17 +86,19 @@ def send_msg(bot, tag='ad', trigger_time=300):
|
||||
types.InlineKeyboardButton(
|
||||
text="搜索", url='https://bbs.midoks.me/search.php'),
|
||||
types.InlineKeyboardButton(
|
||||
text="@ME", url='tg://user?id=5568699210')
|
||||
text="@ME", url='tg://user?id=5568699210'),
|
||||
types.InlineKeyboardButton(
|
||||
text="100RMB/M", url='tg://user?id=5568699210')
|
||||
]
|
||||
]
|
||||
markup = types.InlineKeyboardMarkup(keyboard)
|
||||
|
||||
msg_notice = "由于在解决的问题的时候,不给信息,无法了解情况。以后不再群里回答技术问题。全部去论坛提问。在解决问题的过程中,可能需要面板信息,和SSH信息,如无法提供请不要提问。为了让群里都知晓。轮播一年!\n"
|
||||
msg_notice += "为了不打扰双方,私聊解决问题先转100U,否则无视!"
|
||||
msg_notice += "为了不打扰双方,私聊解决问题先转100U,否则无视!\n"
|
||||
msg = bot.send_message(chat_id, msg_notice, reply_markup=markup)
|
||||
|
||||
# print(msg.message_id)
|
||||
time.sleep(60)
|
||||
time.sleep(90)
|
||||
try:
|
||||
bot.delete_message(
|
||||
chat_id=chat_id, message_id=msg.message_id)
|
||||
@@ -90,7 +108,7 @@ def send_msg(bot, tag='ad', trigger_time=300):
|
||||
|
||||
def run(bot):
|
||||
try:
|
||||
send_msg(bot, 'notice_msg', 180)
|
||||
send_msg(bot, 'notice_msg', 90)
|
||||
except Exception as e:
|
||||
writeLog('-----push_notice_msg error start -------')
|
||||
print(mw.getTracebackInfo())
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
# coding:utf-8
|
||||
|
||||
import sys
|
||||
@@ -96,15 +95,6 @@ for p in init_list:
|
||||
writeLog(mw.getTracebackInfo())
|
||||
writeLog('-----init error end -------')
|
||||
|
||||
# @bot.message_handler(commands=['start', 'help'])
|
||||
# def hanle_start_help(message):
|
||||
# bot.reply_to(message, "hello world")
|
||||
|
||||
|
||||
# @bot.message_handler(commands=['mw_echo'])
|
||||
# def hanle_mw_echo(message):
|
||||
# bot.reply_to(message, message.text)
|
||||
|
||||
|
||||
@bot.message_handler(commands=['chat_id'])
|
||||
def hanle_get_chat_id(message):
|
||||
@@ -137,49 +127,6 @@ def callback_query_handler(call):
|
||||
writeLog('-----callback_query_handler error end -------')
|
||||
|
||||
|
||||
def runBotPushTask():
|
||||
plist = getStartExtCfgByTag('push')
|
||||
for p in plist:
|
||||
try:
|
||||
script = p['name'].split('.')[0]
|
||||
__import__(script).run(bot)
|
||||
except Exception as e:
|
||||
writeLog('-----runBotPushTask error start -------')
|
||||
writeLog(mw.getTracebackInfo())
|
||||
writeLog('-----runBotPushTask error end -------')
|
||||
|
||||
|
||||
def botPush():
|
||||
while True:
|
||||
runBotPushTask()
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def runBotPushOtherTask():
|
||||
plist = getStartExtCfgByTag('other')
|
||||
for p in plist:
|
||||
try:
|
||||
script = p['name'].split('.')[0]
|
||||
__import__(script).run(bot)
|
||||
except Exception as e:
|
||||
writeLog('-----runBotPushOtherTask error start -------')
|
||||
writeLog(mw.getTracebackInfo())
|
||||
writeLog('-----runBotPushOtherTask error end -------')
|
||||
|
||||
|
||||
def botPushOther():
|
||||
while True:
|
||||
runBotPushOtherTask()
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def setDaemon(t):
|
||||
if sys.version_info.major == 3 and sys.version_info.minor >= 10:
|
||||
t.daemon = True
|
||||
else:
|
||||
t.setDaemon(True)
|
||||
|
||||
|
||||
def runBot(bot):
|
||||
try:
|
||||
bot.polling()
|
||||
@@ -192,14 +139,6 @@ def runBot(bot):
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
# 机器人推送任务
|
||||
botPushTask = threading.Thread(target=botPush)
|
||||
botPushTask.start()
|
||||
|
||||
# 机器人其他推送任务
|
||||
botPushOtherTask = threading.Thread(target=botPushOther)
|
||||
botPushOtherTask.start()
|
||||
|
||||
writeLog('启动成功')
|
||||
runBot(bot)
|
||||
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
# coding:utf-8
|
||||
|
||||
import sys
|
||||
import io
|
||||
import os
|
||||
import time
|
||||
import re
|
||||
import json
|
||||
import base64
|
||||
import threading
|
||||
|
||||
sys.path.append(os.getcwd() + "/class/core")
|
||||
import mw
|
||||
|
||||
import telebot
|
||||
|
||||
|
||||
def getPluginName():
|
||||
return 'tgbot'
|
||||
|
||||
|
||||
def getPluginDir():
|
||||
return mw.getPluginDir() + '/' + getPluginName()
|
||||
|
||||
|
||||
def getServerDir():
|
||||
return mw.getServerDir() + '/' + getPluginName()
|
||||
|
||||
|
||||
sys.path.append(getServerDir() + "/extend")
|
||||
|
||||
|
||||
def getConfigData():
|
||||
cfg_path = getServerDir() + "/data.cfg"
|
||||
if not os.path.exists(cfg_path):
|
||||
mw.writeFile(cfg_path, '{}')
|
||||
t = mw.readFile(cfg_path)
|
||||
return json.loads(t)
|
||||
|
||||
|
||||
def writeConf(data):
|
||||
cfg_path = getServerDir() + "/data.cfg"
|
||||
mw.writeFile(cfg_path, json.dumps(data))
|
||||
return True
|
||||
|
||||
|
||||
def getExtCfg():
|
||||
cfg_path = getServerDir() + "/extend.cfg"
|
||||
if not os.path.exists(cfg_path):
|
||||
mw.writeFile(cfg_path, '{}')
|
||||
t = mw.readFile(cfg_path)
|
||||
return json.loads(t)
|
||||
|
||||
|
||||
def getStartExtCfgByTag(tag='push'):
|
||||
# 获取开启的扩展
|
||||
elist = getExtCfg()
|
||||
rlist = []
|
||||
for x in elist:
|
||||
if x['tag'] == tag and x['status'] == 'start':
|
||||
rlist.append(x)
|
||||
return rlist
|
||||
|
||||
|
||||
def writeLog(log_str):
|
||||
if __name__ == "__main__":
|
||||
print(log_str)
|
||||
|
||||
now = mw.getDateFromNow()
|
||||
log_file = getServerDir() + '/push.log'
|
||||
mw.writeFileLog(now + ':' + log_str, log_file, limit_size=5 * 1024)
|
||||
return True
|
||||
|
||||
# start tgbot
|
||||
cfg = getConfigData()
|
||||
while True:
|
||||
cfg = getConfigData()
|
||||
if 'bot' in cfg and 'app_token' in cfg['bot']:
|
||||
if cfg['bot']['app_token'] != '' and cfg['bot']['app_token'] != 'app_token':
|
||||
break
|
||||
writeLog('等待输入配置,填写app_token')
|
||||
time.sleep(3)
|
||||
|
||||
|
||||
bot = telebot.TeleBot(cfg['bot']['app_token'])
|
||||
|
||||
|
||||
def runBotPushTask():
|
||||
plist = getStartExtCfgByTag('push')
|
||||
for p in plist:
|
||||
try:
|
||||
script = p['name'].split('.')[0]
|
||||
__import__(script).run(bot)
|
||||
except Exception as e:
|
||||
writeLog('-----runBotPushTask error start -------')
|
||||
writeLog(mw.getTracebackInfo())
|
||||
writeLog('-----runBotPushTask error end -------')
|
||||
|
||||
|
||||
def botPush():
|
||||
while True:
|
||||
runBotPushTask()
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def runBotPushOtherTask():
|
||||
plist = getStartExtCfgByTag('other')
|
||||
for p in plist:
|
||||
try:
|
||||
script = p['name'].split('.')[0]
|
||||
__import__(script).run(bot)
|
||||
except Exception as e:
|
||||
writeLog('-----runBotPushOtherTask error start -------')
|
||||
writeLog(mw.getTracebackInfo())
|
||||
writeLog('-----runBotPushOtherTask error end -------')
|
||||
|
||||
|
||||
def botPushOther():
|
||||
while True:
|
||||
runBotPushOtherTask()
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
# 机器人推送任务
|
||||
botPushTask = threading.Thread(target=botPush)
|
||||
botPushTask.start()
|
||||
|
||||
# 机器人其他推送任务
|
||||
botPushOtherTask = threading.Thread(target=botPushOther)
|
||||
botPushOtherTask.start()
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 974 B |
Executable
+27
@@ -0,0 +1,27 @@
|
||||
<div class="bt-form">
|
||||
<div class='plugin_version'></div>
|
||||
<div class="bt-w-main">
|
||||
<div class="bt-w-menu">
|
||||
<p class="bgw" onclick="pluginService('tgclient');">服务</p>
|
||||
<p onclick="pluginInitD('tgclient');">自启动</p>
|
||||
<p onclick="clientConf();">配置</p>
|
||||
<p onclick="botExtList();">扩展列表</p>
|
||||
<p onclick="pluginLogs('tgclient','','run_log');">日志</p>
|
||||
<p onclick="readme();">说明</p>
|
||||
</div>
|
||||
<div class="bt-w-con pd15">
|
||||
<div class="soft-man-con"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<style>
|
||||
.conf_p span{
|
||||
width: 70px;
|
||||
}
|
||||
</style>
|
||||
<script type="text/javascript">
|
||||
resetPluginWinHeight(350);
|
||||
$.getScript( "/plugins/file?name=tgclient&f=js/tgclient.js", function(){
|
||||
pluginService('tgclient');
|
||||
});
|
||||
</script>
|
||||
Executable
+371
@@ -0,0 +1,371 @@
|
||||
# coding:utf-8
|
||||
|
||||
import sys
|
||||
import io
|
||||
import os
|
||||
import time
|
||||
import re
|
||||
import json
|
||||
import base64
|
||||
|
||||
sys.path.append(os.getcwd() + "/class/core")
|
||||
import mw
|
||||
|
||||
app_debug = False
|
||||
if mw.isAppleSystem():
|
||||
app_debug = True
|
||||
|
||||
|
||||
def getPluginName():
|
||||
return 'tgclient'
|
||||
|
||||
|
||||
def getPluginDir():
|
||||
return mw.getPluginDir() + '/' + getPluginName()
|
||||
|
||||
|
||||
def getServerDir():
|
||||
return mw.getServerDir() + '/' + getPluginName()
|
||||
|
||||
|
||||
def getInitDFile():
|
||||
if app_debug:
|
||||
return '/tmp/' + getPluginName()
|
||||
return '/etc/init.d/' + getPluginName()
|
||||
|
||||
|
||||
def getConfigData():
|
||||
cfg_path = getServerDir() + "/data.cfg"
|
||||
if not os.path.exists(cfg_path):
|
||||
mw.writeFile(cfg_path, '{}')
|
||||
t = mw.readFile(cfg_path)
|
||||
return json.loads(t)
|
||||
|
||||
|
||||
def writeConf(data):
|
||||
cfg_path = getServerDir() + "/data.cfg"
|
||||
mw.writeFile(cfg_path, json.dumps(data))
|
||||
return True
|
||||
|
||||
|
||||
def getExtCfg():
|
||||
cfg_path = getServerDir() + "/extend.cfg"
|
||||
if not os.path.exists(cfg_path):
|
||||
mw.writeFile(cfg_path, '{}')
|
||||
t = mw.readFile(cfg_path)
|
||||
return json.loads(t)
|
||||
|
||||
|
||||
def writeExtCfg(data):
|
||||
cfg_path = getServerDir() + "/extend.cfg"
|
||||
return mw.writeFile(cfg_path, json.dumps(data))
|
||||
|
||||
|
||||
def getInitDTpl():
|
||||
path = getPluginDir() + "/init.d/" + getPluginName() + ".tpl"
|
||||
return path
|
||||
|
||||
|
||||
def getArgs():
|
||||
args = sys.argv[2:]
|
||||
tmp = {}
|
||||
args_len = len(args)
|
||||
if args_len == 1:
|
||||
t = args[0].strip('{').strip('}')
|
||||
if t.strip() == '':
|
||||
tmp = []
|
||||
else:
|
||||
t = t.split(':')
|
||||
tmp[t[0]] = t[1]
|
||||
tmp[t[0]] = t[1]
|
||||
elif args_len > 1:
|
||||
for i in range(len(args)):
|
||||
t = args[i].split(':')
|
||||
tmp[t[0]] = t[1]
|
||||
return tmp
|
||||
|
||||
|
||||
def checkArgs(data, ck=[]):
|
||||
for i in range(len(ck)):
|
||||
if not ck[i] in data:
|
||||
return (False, mw.returnJson(False, '参数:(' + ck[i] + ')没有!'))
|
||||
return (True, mw.returnJson(True, 'ok'))
|
||||
|
||||
|
||||
def status():
|
||||
data = mw.execShell(
|
||||
"ps -ef|grep tgclient |grep -v grep | grep -v mdserver-web | awk '{print $2}'")
|
||||
if data[0] == '':
|
||||
return 'stop'
|
||||
return 'start'
|
||||
|
||||
|
||||
def initDreplace():
|
||||
|
||||
file_tpl = getInitDTpl()
|
||||
service_path = mw.getServerDir()
|
||||
app_path = service_path + '/' + getPluginName()
|
||||
|
||||
initD_path = getServerDir() + '/init.d'
|
||||
if not os.path.exists(initD_path):
|
||||
os.mkdir(initD_path)
|
||||
file_bin = initD_path + '/' + getPluginName()
|
||||
|
||||
# initd replace
|
||||
# if not os.path.exists(file_bin):
|
||||
content = mw.readFile(file_tpl)
|
||||
content = content.replace('{$SERVER_PATH}', service_path + '/mdserver-web')
|
||||
content = content.replace('{$APP_PATH}', app_path)
|
||||
|
||||
mw.writeFile(file_bin, content)
|
||||
mw.execShell('chmod +x ' + file_bin)
|
||||
|
||||
pyMainTplContent = mw.readFile(getPluginDir() + '/startup/tgclient.py')
|
||||
toPyMainPath = mw.getServerDir() + '/tgclient.py'
|
||||
mw.writeFile(toPyMainPath, pyMainTplContent)
|
||||
|
||||
# systemd
|
||||
systemDir = mw.systemdCfgDir()
|
||||
systemService = systemDir + '/tgclient.service'
|
||||
systemServiceTpl = getPluginDir() + '/init.d/tgclient.service.tpl'
|
||||
if os.path.exists(systemDir) and not os.path.exists(systemService):
|
||||
service_path = mw.getServerDir()
|
||||
se_content = mw.readFile(systemServiceTpl)
|
||||
se_content = se_content.replace('{$APP_PATH}', app_path)
|
||||
mw.writeFile(systemService, se_content)
|
||||
mw.execShell('systemctl daemon-reload')
|
||||
|
||||
return file_bin
|
||||
|
||||
|
||||
def tbOp(method):
|
||||
file = initDreplace()
|
||||
|
||||
if not mw.isAppleSystem():
|
||||
data = mw.execShell('systemctl ' + method + ' ' + getPluginName())
|
||||
if data[1] == '':
|
||||
return 'ok'
|
||||
return data[1]
|
||||
|
||||
data = mw.execShell(file + ' ' + method)
|
||||
# print(data)
|
||||
if data[1] == '':
|
||||
return 'ok'
|
||||
return 'ok'
|
||||
|
||||
|
||||
def start():
|
||||
return tbOp('start')
|
||||
|
||||
|
||||
def stop():
|
||||
return tbOp('stop')
|
||||
|
||||
|
||||
def restart():
|
||||
status = tbOp('restart')
|
||||
return status
|
||||
|
||||
|
||||
def reload():
|
||||
|
||||
tgbot_tpl = getPluginDir() + '/startup/tgclient.py'
|
||||
tgbot_dst = getServerDir() + '/tgclient.py'
|
||||
|
||||
content = mw.readFile(tgbot_tpl)
|
||||
mw.writeFile(tgbot_dst, content)
|
||||
|
||||
ext_src = getPluginDir() + '/startup/extend'
|
||||
ext_dst = getServerDir()
|
||||
|
||||
mw.execShell('cp -rf ' + ext_src + ' ' + ext_dst)
|
||||
|
||||
return tbOp('restart')
|
||||
|
||||
|
||||
def initdStatus():
|
||||
if mw.isAppleSystem():
|
||||
return "Apple Computer does not support"
|
||||
|
||||
shell_cmd = 'systemctl status ' + \
|
||||
getPluginName() + ' | grep loaded | grep "enabled;"'
|
||||
data = mw.execShell(shell_cmd)
|
||||
if data[0] == '':
|
||||
return 'fail'
|
||||
return 'ok'
|
||||
|
||||
|
||||
def initdInstall():
|
||||
if mw.isAppleSystem():
|
||||
return "Apple Computer does not support"
|
||||
|
||||
mw.execShell('systemctl enable ' + getPluginName())
|
||||
return 'ok'
|
||||
|
||||
|
||||
def initdUinstall():
|
||||
if mw.isAppleSystem():
|
||||
return "Apple Computer does not support"
|
||||
|
||||
mw.execShell('systemctl disable ' + getPluginName())
|
||||
return 'ok'
|
||||
|
||||
|
||||
def getClientConf():
|
||||
data = getConfigData()
|
||||
if 'bot' in data:
|
||||
return mw.returnJson(True, 'ok', data['bot'])
|
||||
return mw.returnJson(False, 'ok', {})
|
||||
|
||||
|
||||
def setClientConf():
|
||||
args = getArgs()
|
||||
data_args = checkArgs(args, ['api_id', 'api_hash'])
|
||||
if not data_args[0]:
|
||||
return data_args[1]
|
||||
|
||||
data = getConfigData()
|
||||
args['api_id'] = base64.b64decode(args['api_id']).decode('ascii')
|
||||
args['api_hash'] = base64.b64decode(args['api_hash']).decode('ascii')
|
||||
data['bot'] = args
|
||||
writeConf(data)
|
||||
|
||||
return mw.returnJson(True, '保存成功!', [])
|
||||
|
||||
|
||||
def installPreInspection():
|
||||
i = sys.version_info
|
||||
if i[0] < 3 or i[1] < 7:
|
||||
return "telebot在python小于3.7无法正常使用"
|
||||
return 'ok'
|
||||
|
||||
|
||||
def uninstallPreInspection():
|
||||
stop()
|
||||
return "请手动删除<br/> rm -rf {}".format(getServerDir())
|
||||
|
||||
|
||||
def getExtCfgByName(name):
|
||||
elist = getExtCfg()
|
||||
for x in elist:
|
||||
if x['name'] == name:
|
||||
return x
|
||||
return None
|
||||
|
||||
|
||||
def clientExtList():
|
||||
|
||||
args = getArgs()
|
||||
data_args = checkArgs(args, ['p'])
|
||||
if not data_args[0]:
|
||||
return data_args[1]
|
||||
|
||||
ext_path = getServerDir() + '/extend'
|
||||
if not os.path.exists(ext_path):
|
||||
return mw.returnJson(False, 'ok', [])
|
||||
elist_source = os.listdir(ext_path)
|
||||
|
||||
elist = []
|
||||
for e in elist_source:
|
||||
if e.endswith('py'):
|
||||
elist.append(e)
|
||||
|
||||
page = int(args['p'])
|
||||
page_size = 5
|
||||
|
||||
make_ext_list = []
|
||||
for ex in elist:
|
||||
tmp = {}
|
||||
tmp['name'] = ex
|
||||
edata = getExtCfgByName(ex)
|
||||
if edata:
|
||||
tmp['status'] = edata['status']
|
||||
else:
|
||||
tmp['status'] = 'stop'
|
||||
|
||||
tmp['tag'] = ex.split('_')[0]
|
||||
make_ext_list.append(tmp)
|
||||
|
||||
writeExtCfg(make_ext_list)
|
||||
dlist_sum = len(make_ext_list)
|
||||
|
||||
page_start = int((page - 1) * page_size)
|
||||
page_end = page_start + page_size
|
||||
|
||||
if page_end >= dlist_sum:
|
||||
ret_data = make_ext_list[page_start:]
|
||||
else:
|
||||
ret_data = make_ext_list[page_start:page_end]
|
||||
|
||||
data = {}
|
||||
data['data'] = ret_data
|
||||
data['args'] = args
|
||||
data['list'] = mw.getPage(
|
||||
{'count': dlist_sum, 'p': page, 'row': page_size, 'tojs': 'botExtListP'})
|
||||
|
||||
return mw.returnJson(True, 'ok', data)
|
||||
|
||||
|
||||
def setExtStatus():
|
||||
args = getArgs()
|
||||
data_args = checkArgs(args, ['name', 'status'])
|
||||
if not data_args[0]:
|
||||
return data_args[1]
|
||||
|
||||
elist = getExtCfg()
|
||||
name = args['name']
|
||||
status = args['status']
|
||||
for x in range(len(elist)):
|
||||
if elist[x]['name'] == name:
|
||||
elist[x]['status'] = status
|
||||
break
|
||||
|
||||
writeExtCfg(elist)
|
||||
|
||||
action = '开启'
|
||||
if status == 'stop':
|
||||
action = '关闭'
|
||||
|
||||
return mw.returnJson(True, action + '[' + name + ']扩展成功')
|
||||
|
||||
|
||||
def runLog():
|
||||
p = getServerDir() + '/task.log'
|
||||
return p
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
func = sys.argv[1]
|
||||
if func == 'status':
|
||||
print(status())
|
||||
elif func == 'start':
|
||||
print(start())
|
||||
elif func == 'stop':
|
||||
print(stop())
|
||||
elif func == 'restart':
|
||||
print(restart())
|
||||
elif func == 'reload':
|
||||
print(reload())
|
||||
elif func == 'initd_status':
|
||||
print(initdStatus())
|
||||
elif func == 'initd_install':
|
||||
print(initdInstall())
|
||||
elif func == 'initd_uninstall':
|
||||
print(initdUinstall())
|
||||
elif func == 'install_pre_inspection':
|
||||
print(installPreInspection())
|
||||
elif func == 'uninstall_pre_inspection':
|
||||
print(uninstallPreInspection())
|
||||
elif func == 'get_client_conf':
|
||||
print(getClientConf())
|
||||
elif func == 'set_client_conf':
|
||||
print(setClientConf())
|
||||
elif func == 'client_ext_list':
|
||||
print(clientExtList())
|
||||
elif func == 'set_ext_status':
|
||||
print(setExtStatus())
|
||||
elif func == 'run_log':
|
||||
print(runLog())
|
||||
|
||||
else:
|
||||
print('error')
|
||||
Executable
+20
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"sort": 7,
|
||||
"ps": "简单Telegram客服端管理",
|
||||
"name": "tgclient",
|
||||
"title": "tgclient",
|
||||
"shell": "install.sh",
|
||||
"versions":["1.1"],
|
||||
"tip": "soft",
|
||||
"checks": "server/tgclient",
|
||||
"path": "server/tgclient",
|
||||
"install_pre_inspection":true,
|
||||
"uninstall_pre_inspection":true,
|
||||
"display": 1,
|
||||
"author": "midoks",
|
||||
"date": "2023-03-06",
|
||||
"home": "https://my.telegram.org/apps",
|
||||
"depend_doc1":"https://docs.telethon.dev/en/stable/basic/installation.html",
|
||||
"type": 0,
|
||||
"pid": "5"
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
[Unit]
|
||||
Description=Tgbot Service
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=forking
|
||||
ExecStart={$APP_PATH}/init.d/tgclient start
|
||||
ExecStop={$APP_PATH}/init.d/tgclient stop
|
||||
ExecReload={$APP_PATH}/init.d/tgclient reload
|
||||
KillMode=process
|
||||
Restart=on-failure
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,86 @@
|
||||
#!/bin/sh
|
||||
# chkconfig: 2345 55 25
|
||||
# description: Tgbot Service
|
||||
|
||||
### BEGIN INIT INFO
|
||||
# Provides: Tgbot
|
||||
# Required-Start: $all
|
||||
# Required-Stop: $all
|
||||
# Default-Start: 2 3 4 5
|
||||
# Default-Stop: 0 1 6
|
||||
# Short-Description: starts Tgbot
|
||||
# Description: starts the MDW-Web
|
||||
### END INIT INFO
|
||||
|
||||
# Simple Tgbot init.d script conceived to work on Linux systems
|
||||
# as it does use of the /proc filesystem.
|
||||
|
||||
PATH=/usr/local/bin:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
|
||||
export LANG=en_US.UTF-8
|
||||
|
||||
|
||||
mw_path={$SERVER_PATH}
|
||||
PATH=$PATH:$mw_path/bin
|
||||
|
||||
if [ -f $mw_path/bin/activate ];then
|
||||
source $mw_path/bin/activate
|
||||
fi
|
||||
|
||||
tg_start(){
|
||||
|
||||
isStart=`ps -ef|grep 'tgclient.py' |grep -v grep | awk '{print $2}'`
|
||||
if [ "$isStart" == '' ];then
|
||||
echo -e "starting tgclient... \c"
|
||||
cd $mw_path
|
||||
echo "python3 {$APP_PATH}/tgclient.py"
|
||||
python3 {$APP_PATH}/tgclient.py >> {$APP_PATH}/task.log &
|
||||
isStart=""
|
||||
while [[ "$isStart" == "" ]];
|
||||
do
|
||||
echo -e ".\c"
|
||||
sleep 0.5
|
||||
isStart=`ps -ef|grep 'tgclient.py' |grep -v grep | awk '{print $2}'`
|
||||
let n+=1
|
||||
if [ $n -gt 20 ];then
|
||||
break;
|
||||
fi
|
||||
done
|
||||
if [ "$isStart" == '' ];then
|
||||
echo -e "\033[31mfailed\033[0m"
|
||||
echo -e "\033[31mError: tgclient service startup failed.\033[0m"
|
||||
return;
|
||||
fi
|
||||
echo -e "\033[32mdone\033[0m"
|
||||
else
|
||||
echo "starting tgclient...(pid $(echo $isStart)) already running"
|
||||
fi
|
||||
}
|
||||
|
||||
|
||||
tg_stop(){
|
||||
echo -e "stopping tgclient ... \c";
|
||||
arr=`ps aux|grep 'tgclient.py'|grep -v grep|awk '{print $2}'`
|
||||
for p in ${arr[@]}
|
||||
do
|
||||
kill -9 $p > /dev/null 2>&1
|
||||
done
|
||||
echo -e "\033[32mdone\033[0m"
|
||||
}
|
||||
|
||||
case "$1" in
|
||||
start)
|
||||
tg_start
|
||||
;;
|
||||
stop)
|
||||
tg_stop
|
||||
;;
|
||||
restart|reload)
|
||||
tg_stop
|
||||
sleep 0.3
|
||||
tg_start
|
||||
;;
|
||||
*)
|
||||
echo "Please use start or stop as first argument"
|
||||
;;
|
||||
esac
|
||||
|
||||
Executable
+58
@@ -0,0 +1,58 @@
|
||||
#!/bin/bash
|
||||
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
|
||||
export PATH
|
||||
|
||||
curPath=`pwd`
|
||||
rootPath=$(dirname "$curPath")
|
||||
rootPath=$(dirname "$rootPath")
|
||||
serverPath=$(dirname "$rootPath")
|
||||
|
||||
|
||||
install_tmp=${rootPath}/tmp/mw_install.pl
|
||||
|
||||
VERSION=$2
|
||||
|
||||
# pip3 install ccxt
|
||||
if [ -f ${rootPath}/bin/activate ];then
|
||||
source ${rootPath}/bin/activate
|
||||
fi
|
||||
|
||||
pip3 install telethon
|
||||
|
||||
Install_App()
|
||||
{
|
||||
echo '正在安装脚本文件...' > $install_tmp
|
||||
mkdir -p $serverPath/source
|
||||
mkdir -p $serverPath/tgclient
|
||||
echo "${VERSION}" > $serverPath/tgclient/version.pl
|
||||
|
||||
cp -rf ${rootPath}/plugins/tgclient/startup/* $serverPath/tgclient
|
||||
|
||||
cd ${rootPath} && python3 ${rootPath}/plugins/tgclient/index.py start
|
||||
cd ${rootPath} && python3 ${rootPath}/plugins/tgclient/index.py initd_install
|
||||
echo '安装完成' > $install_tmp
|
||||
}
|
||||
|
||||
Uninstall_App()
|
||||
{
|
||||
if [ -f /usr/lib/systemd/system/tgclient.service ];then
|
||||
systemctl stop tgclient
|
||||
systemctl disable tgclient
|
||||
rm -rf /usr/lib/systemd/system/tgclient.service
|
||||
systemctl daemon-reload
|
||||
fi
|
||||
|
||||
if [ -f $serverPath/tgclient/initd/tgclient ];then
|
||||
$serverPath/tgclient/initd/tgclient stop
|
||||
fi
|
||||
|
||||
rm -rf $serverPath/tgclient
|
||||
echo "Uninstall_redis" > $install_tmp
|
||||
}
|
||||
|
||||
action=$1
|
||||
if [ "${1}" == 'install' ];then
|
||||
Install_App
|
||||
else
|
||||
Uninstall_App
|
||||
fi
|
||||
Executable
+163
@@ -0,0 +1,163 @@
|
||||
function readme(){
|
||||
var readme = '<ul class="help-info-text c7">';
|
||||
readme += '<li>在填写好配置信息好后,还要执行下面命令。进行手机号和短信码验证。再重启,即可正常使用</li>';
|
||||
readme += '<li>cd /www/server/mdserver-web && source bin/activate && python3 /www/server/tgclient/tgclient.py</li>';
|
||||
readme += '<li>https://my.telegram.org/auth</li>';
|
||||
readme += '</ul>';
|
||||
$('.soft-man-con').html(readme);
|
||||
}
|
||||
|
||||
function appPost(method, args,callback){
|
||||
var loadT = layer.msg('正在获取...', { icon: 16, time: 0, shade: 0.3 });
|
||||
|
||||
var req_data = {};
|
||||
req_data['name'] = 'tgclient';
|
||||
req_data['func'] = method;
|
||||
|
||||
if (typeof(args) == 'string'){
|
||||
req_data['args'] = JSON.stringify(toArrayObject(args));
|
||||
} else {
|
||||
req_data['args'] = JSON.stringify(args);
|
||||
}
|
||||
|
||||
$.post('/plugins/run', req_data, function(data) {
|
||||
layer.close(loadT);
|
||||
if(typeof(callback) == 'function'){
|
||||
callback(data);
|
||||
}
|
||||
},'json');
|
||||
}
|
||||
|
||||
function appPostCallbak(method, args,callback){
|
||||
var loadT = layer.msg('正在获取...', { icon: 16, time: 0, shade: 0.3 });
|
||||
|
||||
var req_data = {};
|
||||
req_data['name'] = 'tgclient';
|
||||
req_data['func'] = method;
|
||||
|
||||
if (typeof(args) == 'string'){
|
||||
req_data['args'] = JSON.stringify(toArrayObject(args));
|
||||
} else {
|
||||
req_data['args'] = JSON.stringify(args);
|
||||
}
|
||||
|
||||
$.post('/plugins/callback', req_data, function(data) {
|
||||
layer.close(loadT);
|
||||
if (!data.status){
|
||||
layer.msg(data.msg,{icon:0,time:2000,shade: [0.3, '#000']});
|
||||
return;
|
||||
}
|
||||
|
||||
if(typeof(callback) == 'function'){
|
||||
callback(data);
|
||||
}
|
||||
},'json');
|
||||
}
|
||||
|
||||
function clientConf(){
|
||||
appPost('get_client_conf','',function(data){
|
||||
var rdata = $.parseJSON(data.data);
|
||||
var api_id = 'api_id';
|
||||
var api_hash = 'api_hash';
|
||||
if(rdata['status']){
|
||||
db_data = rdata['data'];
|
||||
|
||||
// api_id, api_hash
|
||||
api_id = db_data['api_id'];
|
||||
api_hash = db_data['api_hash'];
|
||||
|
||||
}
|
||||
|
||||
var mlist = '';
|
||||
mlist += '<p><span>api_id</span><input style="width: 250px;" class="bt-input-text mr5" name="api_id" value="'+api_id+'" type="text"><font>必填写</font></p>';
|
||||
mlist += '<p><span>api_hash</span><input style="width: 250px;" class="bt-input-text mr5" name="api_hash" value="'+api_hash+'" type="text"><font>必填写</font></p>';
|
||||
var option = '<style>.conf_p p{margin-bottom: 2px}</style>\
|
||||
<div class="conf_p" style="margin-bottom:0">\
|
||||
' + mlist + '\
|
||||
<div style="margin-top:10px; padding-right:15px" class="text-right">\
|
||||
<button class="btn btn-success btn-sm" onclick="submitBotConf()">保存</button>\
|
||||
</div>\
|
||||
</div>';
|
||||
$(".soft-man-con").html(option);
|
||||
});
|
||||
}
|
||||
|
||||
function submitBotConf(){
|
||||
var pull_data = {};
|
||||
pull_data['api_id'] = base64_encode($('input[name="api_id"]').val());
|
||||
pull_data['api_hash'] = base64_encode($('input[name="api_hash"]').val());
|
||||
appPost('set_client_conf',pull_data,function(data){
|
||||
var rdata = $.parseJSON(data.data);
|
||||
layer.msg(rdata['msg'],{icon:rdata['status']?1:2,time:2000,shade: [0.3, '#000']});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function botExtList(){
|
||||
var body = '<div class="divtable mtb10">\
|
||||
<table class="table table-hover" width="100%" cellspacing="0" cellpadding="0" border="0">\
|
||||
<thead>\
|
||||
<tr>\
|
||||
<th width="20">脚本</th>\
|
||||
<th width="120">类型</th>\
|
||||
<th width="10">状态</th>\
|
||||
</tr>\
|
||||
</thead>\
|
||||
<tbody id="ext_list"></tbody>\
|
||||
</table>\
|
||||
<div class="dataTables_paginate paging_bootstrap pagination">\
|
||||
<ul id="ext_list_page" class="page"></ul>\
|
||||
</div>\
|
||||
</div>';
|
||||
$('.soft-man-con').html(body);
|
||||
botExtListP(1);
|
||||
}
|
||||
|
||||
function setBotExtStatus(name,status){
|
||||
appPost('set_ext_status',{'name':name,'status':status}, function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
layer.msg(rdata['msg'],);
|
||||
showMsg(rdata['msg'], function(){
|
||||
botExtListP(1);
|
||||
},{icon:rdata['status']?1:2,shade: [0.3, '#000']},2000);
|
||||
});
|
||||
}
|
||||
|
||||
function botExtListP(p=1){
|
||||
appPost('client_ext_list',{'p':p}, function(rdata){
|
||||
// console.log(rdata);
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
// console.log(rdata);
|
||||
var tBody = '';
|
||||
|
||||
if (!rdata.status && rdata.data.length == 0 ){
|
||||
var tBody = '<tr><td colspan="4"><div style="text-align:center;">无数据</div></td></tr>';
|
||||
} else{
|
||||
var ldata = rdata.data.data;
|
||||
for (var i = 0; i < ldata.length; i++) {
|
||||
tBody += '<tr data-name="'+ldata[i]['name']+'">'
|
||||
tBody += '<td>'+ldata[i]['name']+'</td>';
|
||||
tBody += '<td>'+ldata[i]['tag']+'</td>';
|
||||
|
||||
if (ldata[i]['status'] == 'start'){
|
||||
tBody += '<td><span style="color:#20a53a;cursor: pointer;" class="ext_status glyphicon glyphicon-play"></span></td>';
|
||||
} else{
|
||||
tBody += '<td><span style="color:red;cursor: pointer;" class="ext_status glyphicon glyphicon-pause"></span></td>';
|
||||
}
|
||||
tBody +='<tr>';
|
||||
}
|
||||
}
|
||||
|
||||
$('#ext_list').html(tBody);
|
||||
$('#ext_list_page').html(rdata.data.list);
|
||||
|
||||
$('#ext_list .ext_status').click(function(){
|
||||
var name = $(this).parent().parent().data('name');
|
||||
var status = 'stop';
|
||||
if ($(this).hasClass('glyphicon-pause')){
|
||||
status = 'start';
|
||||
}
|
||||
setBotExtStatus(name,status);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
# coding:utf-8
|
||||
|
||||
# func: 在其他发送推送AD
|
||||
# url: https://docs.telethon.dev/en/stable/modules/client.html
|
||||
import sys
|
||||
import io
|
||||
import os
|
||||
import time
|
||||
import re
|
||||
import json
|
||||
import base64
|
||||
import threading
|
||||
import asyncio
|
||||
|
||||
sys.path.append(os.getcwd() + "/class/core")
|
||||
import mw
|
||||
|
||||
from telethon import utils
|
||||
from telethon import functions, types
|
||||
from telethon.tl.functions.messages import AddChatUserRequest
|
||||
from telethon.tl.functions.channels import InviteToChannelRequest
|
||||
# 指定群ID
|
||||
chat_id_list = [-1001578009023]
|
||||
filter_g_id = [-1001771526434]
|
||||
|
||||
|
||||
msg_ad = "本人软件推广(10s)\n\n"
|
||||
msg_ad += "开源Linux面板【mdserver-web】,站长必备,无毒,源码为证。\n"
|
||||
msg_ad += "不收费,全靠TG乞讨! \n"
|
||||
msg_ad += "看个人简介,加入群聊,一起进步!\n"
|
||||
# msg_ad += "https://github.com/midoks/mdserver-web \n"
|
||||
# msg_ad += "\n"
|
||||
# msg_ad += "加入群聊,一起进步! \n"
|
||||
# msg_ad += "https://t.me/mdserver_web \n"
|
||||
# msg_ad += "不收费,无毒。源码为证。全靠TG乞讨!😭\n\n"
|
||||
# msg_ad += "捐赠地址 USDT(TRC20)\n"
|
||||
# msg_ad += "TVbNgrpeGBGZVm5gTLa21ADP7RpnPFhjya\n"
|
||||
# msg_ad += "日行一善,以后必定大富大贵\n"
|
||||
|
||||
|
||||
async def writeLog(log_str):
|
||||
if __name__ == "__main__":
|
||||
print(log_str)
|
||||
|
||||
now = mw.getDateFromNow()
|
||||
log_file = mw.getServerDir() + '/tgclient/task.log'
|
||||
mw.writeFileLog(now + ':' + log_str, log_file, limit_size=5 * 1024)
|
||||
return True
|
||||
|
||||
async def send_msg(client, chat_id, tag='ad', trigger_time=600):
|
||||
# 信号只在一个周期内执行一次|start
|
||||
lock_file = mw.getServerDir() + '/tgclient/lock.json'
|
||||
if not os.path.exists(lock_file):
|
||||
mw.writeFile(lock_file, '{}')
|
||||
|
||||
lock_data = json.loads(mw.readFile(lock_file))
|
||||
if tag in lock_data:
|
||||
diff_time = time.time() - lock_data[tag]['do_time']
|
||||
if diff_time >= trigger_time:
|
||||
lock_data[tag]['do_time'] = time.time()
|
||||
else:
|
||||
return False, 0, 0
|
||||
else:
|
||||
lock_data[tag] = {'do_time': time.time()}
|
||||
mw.writeFile(lock_file, json.dumps(lock_data))
|
||||
# 信号只在一个周期内执行一次|end
|
||||
|
||||
msg = await client.send_message(chat_id, msg_ad)
|
||||
await asyncio.sleep(10)
|
||||
await client.delete_messages(chat_id, msg)
|
||||
await asyncio.sleep(3)
|
||||
|
||||
async def run(client):
|
||||
client.parse_mode = 'html'
|
||||
# for chat_id in chat_id_list:
|
||||
# await send_msg(client, chat_id)
|
||||
# await asyncio.sleep(30)
|
||||
|
||||
info = await client.get_dialogs()
|
||||
for chat in info:
|
||||
if chat.is_group and not chat.id in filter_g_id:
|
||||
chat_id = str(chat.id)
|
||||
if chat_id[0:4] != '-100':
|
||||
continue
|
||||
|
||||
# print(chat)
|
||||
await writeLog('name:{0} id:{1} is_user:{2} is_channel:{3} is_group:{4}'.format(
|
||||
chat.name, chat.id, chat.is_user, chat.is_channel, chat.is_group))
|
||||
try:
|
||||
await send_msg(client, chat.id, 'ad_' + str(chat.id))
|
||||
except Exception as e:
|
||||
await writeLog(str(chat))
|
||||
await writeLog(str(e))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
pass
|
||||
@@ -0,0 +1,69 @@
|
||||
# coding:utf-8
|
||||
|
||||
# func: 自动检测已经注销群成员
|
||||
|
||||
import sys
|
||||
import io
|
||||
import os
|
||||
import time
|
||||
import re
|
||||
import json
|
||||
import base64
|
||||
import threading
|
||||
import asyncio
|
||||
|
||||
sys.path.append(os.getcwd() + "/class/core")
|
||||
import mw
|
||||
|
||||
import telebot
|
||||
from telebot import types
|
||||
from telebot.util import quick_markup
|
||||
|
||||
|
||||
# 指定群ID
|
||||
chat_id_list = [-1001979545570]
|
||||
# 别人群ID[有API调用限制]
|
||||
chat_id_list_other = [-1001578009023, -1001771526434]
|
||||
|
||||
async def writeLog(log_str):
|
||||
if __name__ == "__main__":
|
||||
print(log_str)
|
||||
|
||||
now = mw.getDateFromNow()
|
||||
log_file = mw.getServerDir() + '/tgclient/task.log'
|
||||
mw.writeFileLog(now + ':' + log_str, log_file, limit_size=5 * 1024)
|
||||
return True
|
||||
|
||||
async def run(client):
|
||||
for chat_id in chat_id_list:
|
||||
try:
|
||||
s = await client.send_message(chat_id, '开始自动检测已经注销群成员...')
|
||||
count = 0
|
||||
async for user in client.iter_participants(chat_id):
|
||||
if user.deleted:
|
||||
count += 1
|
||||
msg = await client.kick_participant(chat_id, user)
|
||||
|
||||
await client.edit_message(chat_id, s.id, '已经检测到有(%d)个账户已失效' % (count))
|
||||
await asyncio.sleep(3)
|
||||
await client.edit_message(chat_id, s.id, '自动检测已经注销群成员完毕!!!')
|
||||
await asyncio.sleep(3)
|
||||
await client.delete_messages(chat_id, s)
|
||||
except Exception as e:
|
||||
print(str(e))
|
||||
writeLog(str(e))
|
||||
|
||||
for chat_id in chat_id_list_other:
|
||||
try:
|
||||
async for user in client.iter_participants(chat_id):
|
||||
if user.deleted:
|
||||
msg = await client.kick_participant(chat_id, user)
|
||||
except Exception as e:
|
||||
print(str(e))
|
||||
writeLog(str(e))
|
||||
|
||||
await asyncio.sleep(300)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
pass
|
||||
@@ -0,0 +1,55 @@
|
||||
# coding:utf-8
|
||||
|
||||
# func: 自动邀请群成员
|
||||
|
||||
import sys
|
||||
import io
|
||||
import os
|
||||
import time
|
||||
import re
|
||||
import json
|
||||
import base64
|
||||
import threading
|
||||
import asyncio
|
||||
|
||||
sys.path.append(os.getcwd() + "/class/core")
|
||||
import mw
|
||||
|
||||
from telethon import utils
|
||||
from telethon import functions, types
|
||||
from telethon.tl.functions.messages import AddChatUserRequest
|
||||
from telethon.tl.functions.channels import InviteToChannelRequest
|
||||
# 指定群ID
|
||||
chat_id = -1001979545570
|
||||
filter_user_id = 5568699210
|
||||
filter_g_id = [-1001771526434]
|
||||
|
||||
|
||||
async def run(client):
|
||||
info = await client.get_dialogs()
|
||||
for chat in info:
|
||||
is_sleep = True
|
||||
print('name:{0} id:{1} is_user:{2} is_channel:{3} is_group:{4}'.format(
|
||||
chat.name, chat.id, chat.is_user, chat.is_channel, chat.is_group))
|
||||
if chat.is_group and chat.id != chat_id:
|
||||
list_user = []
|
||||
async for user in client.iter_participants(chat.id):
|
||||
if chat.id in filter_g_id:
|
||||
is_sleep = False
|
||||
continue
|
||||
|
||||
if filter_user_id != user.id and user.username != None and user.bot == False:
|
||||
list_user.append(user.username)
|
||||
print(list_user)
|
||||
try:
|
||||
await client(InviteToChannelRequest(
|
||||
channel=chat_id, # chat_id
|
||||
users=list_user, # 被邀请人id
|
||||
))
|
||||
except Exception as e:
|
||||
print(str(e))
|
||||
if is_sleep:
|
||||
await asyncio.sleep(90000)
|
||||
|
||||
if __name__ == "__main__":
|
||||
pass
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user