@@ -211,10 +218,12 @@ class SiteDirAuth:
conf = public.readFile(file)
if i == "apache":
if act == "create":
- rep = "combined(\n|.)+IncludeOptional.*\/dir_auth\/.*conf"
- rep1 = "combined"
- if not re.search(rep,conf):
- conf = conf.replace(rep1, rep1 + "\n\t#Directory protection rules, do not manually delete\n\tIncludeOptional {}".format(dir_auth_file))
+ rep = "IncludeOptional.*\/dir_auth\/.*conf(\n|.)+<\/VirtualHost>"
+ rep1 = ""
+ if not re.search(rep, conf):
+ conf = conf.replace(rep1,
+ "\n\t#Directory protection rules, do not manually delete\n\tIncludeOptional {}\n".format(
+ dir_auth_file))
else:
rep = "\n*#Directory protection rules, do not manually delete\n+\s+IncludeOptional[\s\w\/\.\*]+"
conf = re.sub(rep, '', conf)
@@ -240,7 +249,7 @@ class SiteDirAuth:
# for i in range(len(a_conf)-1,-1,-1):
# if site_name == a_conf[i]["sitename"] and a_conf[i]["proxyname"]:
# del a_conf[i]
- return public.returnMsg(False, 'ERROR: %s
' % public.GetMsg("CONFIG_ERROR") + isError.replace("\n",
+ return public.return_msg_gettext(False, 'ERROR: %s
' % public.get_msg_gettext('Configuration ERROR') + isError.replace("\n",
'
') + '')
# 删除密码保护
@@ -256,7 +265,7 @@ class SiteDirAuth:
site_name = site_info["site_name"]
conf = self._read_conf()
if site_name not in conf:
- return public.returnMsg(False,"The website does not exist in the configuration:{}".format(site_name))
+ return public.return_msg_gettext(False,"The website does not exist in the configuration:{}",(site_name,))
for i in range(len(conf[site_name])):
if name in conf[site_name][i].values():
print(conf[site_name][i])
@@ -275,7 +284,7 @@ class SiteDirAuth:
self.set_conf(site_name,"delete")
if not hasattr(get,'multiple'):
public.serviceReload()
- return public.returnMsg(True,"DEL_SUCCESS")
+ return public.return_msg_gettext(True,'Successfully deleted!')
# 修改目录保护密码
def modify_dir_auth_pass(self,get):
@@ -287,6 +296,14 @@ class SiteDirAuth:
:param get:
:return:
'''
+ # if not hasattr(get,"password") or not get.password or not hasattr(get,"username") or not get.username:
+ # return public.return_msg_gettext(False, 'Username or password cannot be less than 3 characters')
+ param = self.__check_param(get)
+ if not param['status']:
+ return param
+ param = param['msg']
+ password = param['password']
+ username = param['username']
name = get.name
site_info = self.get_site_info(get.id)
site_name = site_info["site_name"]
@@ -295,7 +312,7 @@ class SiteDirAuth:
auth_file = '{setup_path}/pass/{site_name}/{name}.pass'.format(setup_path=self.setup_path,site_name=site_name,name=name)
public.writeFile(auth_file,auth)
public.serviceReload()
- return public.returnMsg(True,"EDIT_SUCCESS")
+ return public.return_msg_gettext(True,'Setup successfully!')
# 获取目录保护列表
def get_dir_auth(self,get):
@@ -314,3 +331,39 @@ class SiteDirAuth:
if site_name in conf:
return {site_name:conf[site_name]}
return {}
+
+ def __check_param(self, get):
+ values = {}
+ if hasattr(get, "password"):
+ if not get.password:
+ return public.returnMsg(False, 'Please enter password!')
+ password = get.password.strip()
+ if len(password) < 3:
+ return public.returnMsg(False, 'Password cannot be less than 3 characters')
+ if re.search('\s', password):
+ return public.returnMsg(False, 'Password cannot contain spaces')
+ values['password'] = password
+
+ if hasattr(get, "username"):
+ if not get.username:
+ return public.returnMsg(False, 'Please enter username!')
+ username = get.username.strip()
+ if len(username) < 3:
+ return public.returnMsg(False, 'Username cannot be less than 3 characters')
+ if re.search('\s', username):
+ return public.returnMsg(False, 'Username cannot contain spaces')
+ values['username'] = username
+
+ if hasattr(get, "name"):
+ if not get.name:
+ return public.returnMsg(False, 'Please enter a name!')
+ name = get.name.strip()
+ if len(name) < 3:
+ return public.returnMsg(False, 'Name cannot be less than 3 characters')
+ if re.search('\s', name):
+ return public.returnMsg(False, 'Name cannot contain spaces')
+ if re.search('[\/\"\'\!@#$%^&*()+={}\[\]\:\;\?><,./\\\]+', name):
+ return public.returnMsg(False, 'Name format must be [ aaa_bbb ]')
+ values['name'] = name
+
+ return public.returnMsg(True, values)
\ No newline at end of file
diff --git a/class/sites.py b/class/sites.py
index 1e3b3bf6..300c5600 100644
--- a/class/sites.py
+++ b/class/sites.py
@@ -200,7 +200,7 @@ server
}],
"proxy": {
"open": False,
- "url": "http://www.bt.cn",
+ "url": "https://www.bt.cn",
"host": "www.bt.cn",
"subOpen": False,
"src": "",
diff --git a/class/ssh_authentication.py b/class/ssh_authentication.py
index 4c0c5665..6c19ea88 100644
--- a/class/ssh_authentication.py
+++ b/class/ssh_authentication.py
@@ -100,7 +100,7 @@ class ssh_authentication:
def install_pam_python(self,check):
so_path=check[2]
so_name=check[2].split('/')[-1]
- public.ExecShell('/usr/local/curl/bin/curl -o %s http://download.bt.cn/btwaf_rule/pam_python_so/%s'%(so_path,so_name))
+ public.ExecShell('/usr/local/curl/bin/curl -o %s https://download.bt.cn/btwaf_rule/pam_python_so/%s'%(so_path,so_name))
public.ExecShell("chmod 600 " + so_path)
return True
diff --git a/class/ssh_security.py b/class/ssh_security.py
index 0e648b6a..30e8876f 100644
--- a/class/ssh_security.py
+++ b/class/ssh_security.py
@@ -378,16 +378,28 @@ class ssh_security:
关闭key
无需参数传递
'''
- file = ['/root/.ssh/id_rsa.pub', '/root/.ssh/id_rsa', '/root/.ssh/authorized_keys']
- rec = '\n#?RSAAuthentication\s\w+'
- rec2 = '\n#?PubkeyAuthentication\s\w+'
- file = public.readFile(self.__SSH_CONFIG)
- file_ssh = re.sub(rec, '\nRSAAuthentication no', file)
- file_result = re.sub(rec2, '\nPubkeyAuthentication no', file_ssh)
- self.wirte(self.__SSH_CONFIG, file_result)
- self.set_password(get)
- self.restart_ssh()
- return public.returnMsg(True, 'Closed successfully')
+ is_ssh_status=public.get_sshd_status()
+ if is_ssh_status:
+ file = ['/root/.ssh/id_rsa.pub', '/root/.ssh/id_rsa', '/root/.ssh/authorized_keys']
+ rec = '\n#?RSAAuthentication\s\w+'
+ rec2 = '\n#?PubkeyAuthentication\s\w+'
+ file = public.readFile(self.__SSH_CONFIG)
+ file_ssh = re.sub(rec, '\nRSAAuthentication no', file)
+ file_result = re.sub(rec2, '\nPubkeyAuthentication no', file_ssh)
+ self.wirte(self.__SSH_CONFIG, file_result)
+ self.set_password(get)
+ self.restart_ssh()
+ return public.returnMsg(True, 'Closed successfully')
+ else:
+ file = ['/root/.ssh/id_rsa.pub', '/root/.ssh/id_rsa', '/root/.ssh/authorized_keys']
+ rec = '\n#?RSAAuthentication\s\w+'
+ rec2 = '\n#?PubkeyAuthentication\s\w+'
+ file = public.readFile(self.__SSH_CONFIG)
+ file_ssh = re.sub(rec, '\nRSAAuthentication no', file)
+ file_result = re.sub(rec2, '\nPubkeyAuthentication no', file_ssh)
+ self.wirte(self.__SSH_CONFIG, file_result)
+ #self.set_password(get)
+ return public.returnMsg(True, 'Closed successfully')
def get_config(self, get):
'''
@@ -514,6 +526,8 @@ if __name__ == '__main__':
try:
aa = ssh_security()
aa.login()
- except:pass
+ except:
+ print(111)
+ pass
else:
pass
diff --git a/class/ssh_terminal.py b/class/ssh_terminal.py
index 20763edb..9968da65 100644
--- a/class/ssh_terminal.py
+++ b/class/ssh_terminal.py
@@ -21,7 +21,7 @@ from io import BytesIO, StringIO
def returnMsg(status,msg,value=None):
if value:
- msg = public.getMsg(msg,value)
+ msg = public.get_msg_gettext(msg,value)
return {'status':status,'msg':msg}
import public
@@ -38,7 +38,7 @@ class ssh_terminal:
_ssh = None
_last_cmd = ""
_last_cmd_tip = 0
- _log_type = public.getMsg('TYPE_TERMINAL')
+ _log_type = public.get_msg_gettext('aaPanel terminal')
_history_len = 0
_client = ""
_rep_ssh_config = False
@@ -48,6 +48,8 @@ class ssh_terminal:
_old_conf = None
_debug_file = 'logs/terminal.log'
_s_code = None
+ _last_num = 0
+ _key_passwd = None
def connect(self):
'''
@@ -58,7 +60,7 @@ class ssh_terminal:
msg: string 详情
}
'''
- if not self._host: return returnMsg(False,'WRONG_CONN_ADDR')
+ if not self._host: return public.return_msg_gettext(False,'Wrong connection address')
if not self._user: self._user = 'root'
if not self._port: self._port = 22
@@ -71,7 +73,7 @@ class ssh_terminal:
while num < 5:
num +=1
try:
- self.debug(public.getMsg('RECONN_TIMES',(num,)))
+ self.debug(public.get_msg_gettext('Reconnection attempts:{}',(num,)))
if self._rep_ssh_config: time.sleep(0.1)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2 + num)
@@ -81,10 +83,10 @@ class ssh_terminal:
except Exception as e:
if num == 5:
self.set_sshd_config(True)
- self.debug(public.getMsg('RECONN_FAILED',(e,)))
+ self.debug(public.get_msg_gettext('Retry connection failed, {}',(e,)))
if self._host in ['127.0.0.1','localhost']:
- return returnMsg(False,'CONN_FAIL',("Authentication failed ," + self._user + "@" + self._host + ":" +str(self._port),))
- return returnMsg(False,'CONN_FAIL1',(self._host,self._port))
+ return returnMsg(False,'Connection failure: {}',("Authentication failed ," + self._user + "@" + self._host + ":" +str(self._port),))
+ return returnMsg(False,'Connection failure: {}',(self._host,self._port))
else:
time.sleep(0.2)
@@ -92,15 +94,15 @@ class ssh_terminal:
import paramiko
self._tp = paramiko.Transport(sock)
-
+ pkey = None
try:
self._tp.start_client()
if not self._pass and not self._pkey:
self.set_sshd_config(True)
- return public.returnMsg(False,'SSH_LOGIN_INFO_ERR',(self._host,str(self._port)))
+ return public.return_msg_gettext(False,'Password or private key cannot both be empty: {}:{}',(self._host,str(self._port)))
self._tp.banner_timeout=60
if self._pkey:
- self.debug(public.getMsg('AUTH_PRI_KEY'))
+ self.debug(public.get_msg_gettext('Authenticating private key'))
if sys.version_info[0] == 2:
try:
self._pkey = self._pkey.encode('utf-8')
@@ -110,18 +112,43 @@ class ssh_terminal:
else:
p_file = StringIO(self._pkey)
try:
- pkey = paramiko.RSAKey.from_private_key(p_file)
- except:
+ if self._key_passwd:
+ pkey = paramiko.RSAKey.from_private_key(p_file,password=self._key_passwd)
+ else:
+ pkey = paramiko.RSAKey.from_private_key(p_file)
+ self.debug("尝试使用RSA私钥认证")
+ except Exception as ex:
try:
p_file.seek(0)
- pkey = paramiko.Ed25519Key.from_private_key(p_file)
+ if self._key_passwd:
+ pkey = paramiko.Ed25519Key.from_private_key(p_file,password=self._key_passwd)
+ else:
+ pkey = paramiko.Ed25519Key.from_private_key(p_file)
+ self.debug("尝试使用Ed25519私钥认证")
except:
try:
p_file.seek(0)
- pkey = paramiko.ECDSAKey.from_private_key(p_file)
+ if self._key_passwd:
+ pkey = paramiko.ECDSAKey.from_private_key(p_file,password=self._key_passwd)
+ else:
+ pkey = paramiko.ECDSAKey.from_private_key(p_file)
+ self.debug("尝试使用ECDSA私钥认证")
except:
p_file.seek(0)
- pkey = paramiko.DSSKey.from_private_key(p_file)
+ if self._key_passwd:
+ try:
+ pkey = paramiko.DSSKey.from_private_key(p_file,password=self._key_passwd)
+ except Exception as ex:
+ ex = str(ex)
+ if ex.find('OpenSSH private key file checkints do not match') != -1:
+ return public.returnMsg(False,'Incorrect private key password: {}'.format(ex))
+ elif ex.find('encountered RSA key, expected DSA key') != -1:
+ pkey = paramiko.RSAKey.from_private_key(p_file,password=self._key_passwd)
+ else:
+ return public.returnMsg(False,'private key error: {}'.format(ex))
+ else:
+ pkey = paramiko.DSSKey.from_private_key(p_file)
+ if not pkey: return public.returnMsg(False,'Incorrect private key!')
self._tp.auth_publickey(username=self._user, key=pkey)
else:
try:
@@ -142,32 +169,43 @@ class ssh_terminal:
self._tp.close()
e = str(e)
if e.find('websocket error!') != -1:
- return returnMsg(True,'connection succeeded')
+ return public.return_msg_gettext(True,'connection succeeded')
if e.find('Authentication timeout') != -1:
self.debug("认证超时{}".format(e))
- return returnMsg(False,'Authentication timed out, please press enter to try again!{}'.format(e))
+ return public.return_msg_gettext(False,'Authentication timed out, please press enter to try again!{}',(e,))
if e.find('Authentication failed') != -1:
- self.debug(public.getMsg('AUTH_FAIL',(str(e),)))
- return returnMsg(False,'SSH_LOGIN_ERR1',(str(e + "," + self._user + "@" + self._host + ":" +str(self._port)),))
+ self.debug(public.get_msg_gettext('Authentication failed {}',(str(e),)))
+ if self._key_passwd:
+ sshd_config = public.readFile('/etc/ssh/sshd_config')
+ if sshd_config and sshd_config.find('ssh-dss') == -1:
+ return returnMsg(False,'The private key verification fails, the private key may be incorrect, or the ssh-dss private key authentication type may not be enabled in the /etc/ssh/sshd_config configuration file')
+ return returnMsg(False,'Authentication failed, please check whether the private key is correct: {}'.format(e + "," + self._user + "@" + self._host + ":" +str(self._port)))
+ return returnMsg(False,'account or password incorrect:{}'.format(e + "," + self._user + "@" + self._host + ":" +str(self._port)))
if e.find('Bad authentication type; allowed types') != -1:
- self.debug(public.getMsg('AUTH_FAIL',(str(e),)))
+ self.debug(public.get_msg_gettext('Authentication failed {}',(str(e),)))
if self._host in ['127.0.0.1','localhost'] and self._pass == 'none':
- return returnMsg(False,'USER_OR_PASSWD_ERR',(str("Authentication failed ," + self._user + "@" + self._host + ":" +str(self._port)),))
- return returnMsg(False,'SSH_LOGIN_ERR2',(str(e)))
+ return public.return_msg_gettext(False,'Username or Password incorrect: {}',(str("Authentication failed ," + self._user + "@" + self._host + ":" +str(self._port)),))
+ return public.return_msg_gettext(False,'Unsupported authentication type: {}',(str(e)))
if e.find('Connection reset by peer') != -1:
- self.debug(public.getMsg('SSH_LOGIN_ERR3'))
- return returnMsg(False,public.getMsg('SSH_LOGIN_ERR3'))
+ self.debug(public.get_msg_gettext('The target server actively refused the connection'))
+ return public.return_msg_gettext(False,public.get_msg_gettext('The target server actively refused the connection'))
if e.find('Error reading SSH protocol banner') != -1:
- self.debug('SSH_LOGIN_ERR10')
- return returnMsg(False,public.getMsg('SSH_LOGIN_ERR4',(str(e),)))
+ self.debug('The protocol header response timed out')
+ return public.return_msg_gettext(False,public.get_msg_gettext('The protocol header response timed out, and the network quality with the target server was too bad: {}',(str(e),)))
+ if e.find('encountered RSA key, expected DSA key') != -1:
+ self.debug('Private keys may require password access')
+ return public.return_msg_gettext(False,public.get_msg_gettext('Private keys may require password access: {}',(str(e),)))
+ if e.find('password and salt must not be empty') != -1:
+ self.debug('Private keys may require password access')
+ return public.return_msg_gettext(False,public.get_msg_gettext('Private keys may require password access: {}',(str(e),)))
if not e:
- self.debug('SSH_LOGIN_ERR11')
- return returnMsg(False,"SSH_LOGIN_ERR5")
+ self.debug('The SSH protocol handshake timed out')
+ return public.return_msg_gettext(False,"The SSH protocol handshake timed out, and the network quality with the target server is too bad")
err = public.get_error_info()
self.debug(err)
- return returnMsg(False,public.getMsg("SSH_LOGIN_ERR6",(str(err),)))
+ return public.return_msg_gettext(False,public.get_msg_gettext('unknown error: {}',(str(err),)))
- self.debug('SSH_LOGIN_INFO3')
+ self.debug(public.get_msg_gettext('The authentication is successful and the session channel is being constructed'))
self._ssh = self._tp.open_session()
self._ssh.get_pty(term='xterm', width=100, height=34)
self._ssh.invoke_shell()
@@ -175,11 +213,11 @@ class ssh_terminal:
self._last_send = []
from BTPanel import request
self._client = public.GetClientIp() +':' + str(request.environ.get('REMOTE_PORT'))
- public.WriteLog(self._log_type,'SSH_LOGIN',(self._host,str(self._port)))
- self.history_send("LOGIN_SUCCESS2")
+ public.write_log_gettext(self._log_type,'Successfully logged in to the SSH server [{}:{}]',(self._host,str(self._port)))
+ self.history_send(public.get_msg_gettext("Login success\n"))
self.set_sshd_config(True)
- self.debug('SSH_LOGIN_INFO2')
- return returnMsg(True,'CONNECTION_SUCCEEDED')
+ self.debug(public.get_msg_gettext('Login success'))
+ return public.return_msg_gettext(True,'connection succeeded')
def _auth_interactive(self):
self.debug('Verification Code')
@@ -216,6 +254,8 @@ class ssh_terminal:
self._tp.auth_interactive(self._user, handler)
+
+
def get_login_user(self):
'''
@name 获取本地登录用户
@@ -288,10 +328,15 @@ class ssh_terminal:
self._pass = ssh_info['password']
self._old_conf = True
return
-
+ ssh_key_type_file = '{}/data/ssh_key_type.pl'.format(public.get_panel_path())
+ ssh_key_type = ''
+ if os.path.exists(ssh_key_type_file):
+ ssh_key_type_new = public.readFile(ssh_key_type_file)
+ if ssh_key_type_new: ssh_key_type = ssh_key_type_new.strip()
login_user = self.get_login_user()
if self._user == 'root' and login_user == 'root':
- id_rsa_file = ['/root/.ssh/id_rsa','/root/.ssh/id_rsa_bt']
+ id_rsa_file = ['/root/.ssh/id_ed25519','/root/.ssh/id_ecdsa','/root/.ssh/id_rsa','/root/.ssh/id_rsa_bt']
+ if ssh_key_type: id_rsa_file.insert(0,'/root/.ssh/id_{}'.format(ssh_key_type))
for ifile in id_rsa_file:
if os.path.exists(ifile):
self._pkey = public.readFile(ifile)
@@ -301,12 +346,14 @@ class ssh_terminal:
return
+
if not self._pass or not self._pkey or not self._user:
home_path = '/home/' + login_user
if login_user == 'root':
home_path = '/root'
self._user = login_user
- id_rsa_file = [home_path + '/.ssh/id_rsa',home_path + '/.ssh/id_rsa_bt']
+ id_rsa_file = [home_path + '/.ssh/id_ed25519',home_path + '/.ssh/id_ecdsa',home_path + '/.ssh/id_rsa',home_path + '/.ssh/id_rsa_bt']
+ if ssh_key_type: id_rsa_file.insert(0,home_path + '/.ssh/id_{}'.format(ssh_key_type))
for ifile in id_rsa_file:
if os.path.exists(ifile):
self._pkey = public.readFile(ifile)
@@ -314,19 +361,6 @@ class ssh_terminal:
self._pass = 'none'
return
- # _ssh_ks = home_path + '/.ssh'
- # if not os.path.exists(_ssh_ks):
- # os.makedirs(_ssh_ks,384)
- # os.system("ssh-keygen -t rsa -P '' -f {}/.ssh/id_rsa |echo y".format(home_path))
- # pub_file = home_path + '/.ssh/id_rsa.pub'
- # az_file = home_path + '/.ssh/authorized_keys'
- # rsa_file = home_path + '/.ssh/id_rsa'
- # public.ExecShell('cat {} >> {} && chmod 600 {} {}'.format(pub_file, az_file, az_file,rsa_file))
- # os.remove(pub_file)
- # public.ExecShell("chown -R {}:{} {}".format(self._user,self._user,_ssh_ks))
- # public.ExecShell("chmod -R 600 {}".format(_ssh_ks))
- # self._pkey = public.readFile(rsa_file)
-
except:
return
@@ -416,6 +450,8 @@ class ssh_terminal:
self.restart_ssh()
return True
+
+
pin = r'^\s*PubkeyAuthentication\s+(yes|no)'
pubkey_status = re.findall(pin,sshd_config,re.I)
if pubkey_status:
@@ -491,12 +527,12 @@ class ssh_terminal:
'''
n = 0
try:
- while not self._ws.closed:
+ while self._ws.connected:
resp_line = self._ssh.recv(1024)
if not resp_line:
if not self._tp.is_active():
- self.debug(public.getMsg('SSH_LOGIN_ERR14'))
- self._ws.send(public.getMsg('RECONNECT_SSH'))
+ self.debug(public.get_msg_gettext('Channel disconnected'))
+ self._ws.send(public.get_msg_gettext('The connection is disconnected, press enter to try to reconnect!'))
self.close()
return
@@ -505,7 +541,7 @@ class ssh_terminal:
if n > 5: break
continue
n = 0
- if self._ws.closed:
+ if not self._ws.connected:
return
try:
result = resp_line.decode('utf-8','ignore')
@@ -517,16 +553,16 @@ class ssh_terminal:
self._ws.send(result)
- self.history_recv(result)
+ # self.history_recv(result)
except Exception as e:
e = str(e)
if e.find('closed') != -1:
- self.debug('SSH_LOGIN_INFO')
- elif not self._ws.closed:
- self.debug(public.getMsg('SSH_LOGIN_ERR15',(str(e),)))
+ self.debug(public.getMsg('SSH_LOGIN_INFO'))
+ elif self._ws.connected:
+ self.debug(public.get_msg_gettext('Error reading tty buffer data, {}',(str(e),)))
- if self._ws.closed:
- self.debug(public.getMsg('SSH_LOGIN_INFO1'))
+ if not self._ws.connected:
+ self.debug(public.get_msg_gettext('The client has actively disconnected'))
self.close()
def send(self):
@@ -536,12 +572,13 @@ class ssh_terminal:
@return void
'''
try:
- while not self._ws.closed:
+ while self._ws.connected:
if self._s_code:
time.sleep(0.1)
continue
client_data = self._ws.receive()
if not client_data: continue
+ if client_data == '{}': continue
if len(client_data) > 10:
if client_data.find('{"host":"') != -1:
continue
@@ -549,20 +586,21 @@ class ssh_terminal:
self.resize(client_data)
continue
self._ssh.send(client_data)
- self.history_send(client_data)
+ # self.history_send(client_data)
except Exception as ex:
ex = str(ex)
+
if ex.find('_io.BufferedReader') != -1:
- self.debug(public.getMsg('SSH_LOGIN_ERR16'))
+ self.debug(public.get_msg_gettext('An error occurred while reading data from websocket. Retrying'))
self.send()
return
elif ex.find('closed') != -1:
- self.debug('SSH_LOGIN_INFO')
+ self.debug(public.get_msg_gettext('SSH_LOGIN_INFO'))
else:
- self.debug(public.getMsg('SSH_LOGIN_ERR17',(str(ex),)))
+ self.debug(public.get_msg_gettext('An error occurred while writing data to the buffer: {}',(str(ex),)))
- if self._ws.closed:
- self.debug(public.getMsg('SSH_LOGIN_INFO1'))
+ if not self._ws.connected:
+ self.debug(public.get_msg_gettext('The client has actively disconnected'))
self.close()
@@ -576,7 +614,7 @@ class ssh_terminal:
#处理TAB补登
if self._last_cmd_tip == 1:
if not recv_data.startswith('\r\n'):
- self._last_cmd += recv_data.replace('\u0007','').strip()
+ self._last_cmd += recv_data.replace('\u0007','').replace("\x07","").strip()
self._last_cmd_tip = 0
#上下切换命令
@@ -601,32 +639,49 @@ class ssh_terminal:
self._last_cmd_tip = 2
return
+ #左移光标
+ if send_data in ["\x1b[C"]:
+ self._last_num -= 1
+ return
+
+ # 右移光标
+ if send_data in ["\x1b[D"]:
+ self._last_num += 1
+ return
+
#退格
if send_data == "\x7f":
self._last_cmd = self._last_cmd[:-1]
return
+
#过滤特殊符号
- if send_data in ["\x1b[C","\x1b[D","\x1b[K","\x07","\x08","\x03","\x01","\x02","\x04","\x05","\x06","\u0007"]:
+ if send_data in ["\x1b[C","\x1b[D","\x1b[K","\x07","\x08","\x03","\x01","\x02","\x04","\x05","\x06","\x1bOB","\x1bOA","\x1b[8P","\x1b","\x1b[4P","\x1b[6P","\x1b[5P"]:
return
#Tab补全处理
- if send_data == '\t':
+ if send_data == "\t":
self._last_cmd_tip = 1
return
+ if str(send_data).find("\x1b") != -1:
+ return
+
if send_data[-1] in ['\r','\n']:
if not self._last_cmd: return
his_shell = [int(time.time()),self._client,self._user,self._last_cmd]
public.writeFile(his_file, json.dumps(his_shell) + "\n","a+")
self._last_cmd = ""
- #超过5M则保留最新的200行
- if os.stat(his_file).st_size > 5242880:
- his_tmp = public.GetNumLines(his_file,200)
+ #超过50M则保留最新的20000行
+ if os.stat(his_file).st_size > 52428800:
+ his_tmp = public.GetNumLines(his_file,20000)
public.writeFile(his_file, his_tmp)
else:
- self._last_cmd += send_data
+ if self._last_num >= 0:
+ self._last_cmd += send_data
+ else:
+ self._last_cmd.insert(len(self._last_cmd) + self._last_num, send_data)
def close(self):
@@ -640,7 +695,7 @@ class ssh_terminal:
self._ssh.close()
if self._tp: # 关闭宿主服务
self._tp.close()
- if not self._ws.closed:
+ if self._ws.connected:
self._ws.close()
except:
pass
@@ -660,6 +715,8 @@ class ssh_terminal:
self._pkey = ssh_info['pkey']
if 'password' in ssh_info:
self._pass = ssh_info['password']
+ if 'pkey_passwd' in ssh_info:
+ self._key_passwd = ssh_info['pkey_passwd']
try:
result = self.connect()
except Exception as ex:
@@ -680,7 +737,7 @@ class ssh_terminal:
self._tp.send_ignore()
else:
break
- if not self._ws.closed:
+ if self._ws.connected:
self._ws.send("")
else:
break
@@ -692,6 +749,7 @@ class ssh_terminal:
@return void
'''
msg = "{} - {}:{} => {} \n".format(public.format_date(),self._host,self._port,msg)
+ self.history_send(msg)
public.writeFile(self._debug_file,msg,'a+')
def run(self,web_socket, ssh_info=None):
@@ -714,7 +772,8 @@ class ssh_terminal:
return
result = self.set_attr(ssh_info)
else:
- result = returnMsg(True,'ALREADY_CONNECTED')
+ result = public.get_msg_gettext(True,'ALREADY_CONNECTED')
+
if result['status']:
sendt = threading.Thread(target=self.send)
recvt = threading.Thread(target=self.recv)
@@ -728,6 +787,7 @@ class ssh_terminal:
self.close()
else:
self._ws.send(result['msg'])
+ self.close()
def __del__(self):
'''
@@ -746,6 +806,14 @@ class ssh_host_admin(ssh_terminal):
_pass_str = None
def __init__(self):
+ self.__create_aes_pass()
+
+ def __create_aes_pass(self):
+ '''
+ @name 创建AES密码
+ @author
+ @return string
+ '''
if not os.path.exists(self._save_path):
os.makedirs(self._save_path,384)
if not os.path.exists(self._pass_file):
@@ -753,6 +821,10 @@ class ssh_host_admin(ssh_terminal):
public.set_mode(self._pass_file,600)
if not self._pass_str:
self._pass_str = public.readFile(self._pass_file)
+ if not self._pass_str:
+ self._pass_str = public.GetRandomString(16)
+ public.writeFile(self._pass_file,self._pass_str)
+ public.set_mode(self._pass_file,600)
def get_host_list(self,args = None):
'''
@@ -766,12 +838,17 @@ class ssh_host_admin(ssh_terminal):
for name in os.listdir(self._save_path):
info_file = self._save_path + name +'/info.json'
if not os.path.exists(info_file): continue
- info_tmp = self.get_ssh_info(name)
- host_info = {}
- host_info['host'] = name
- host_info['port'] = info_tmp['port']
- host_info['ps'] = info_tmp['ps']
- host_info['sort'] = int(info_tmp['sort'])
+ try:
+ info_tmp = self.get_ssh_info(name)
+ host_info = {}
+ host_info['host'] = name
+ host_info['port'] = info_tmp['port']
+ host_info['ps'] = info_tmp['ps']
+ host_info['sort'] = int(info_tmp['sort'])
+ except:
+ if os.path.exists(info_file):
+ os.remove(info_file)
+ continue
host_list.append(host_info)
@@ -790,7 +867,7 @@ class ssh_host_admin(ssh_terminal):
args.host = args.host.strip()
info_file = self._save_path + args.host +'/info.json'
if not os.path.exists(info_file):
- return public.returnMsg(False,'SSH_LOGIN_ERR7')
+ return public.return_msg_gettext(False,'The specified SSH information does not exist!')
info_tmp = self.get_ssh_info(args.host)
host_info = {}
host_info['host'] = args.host
@@ -800,6 +877,9 @@ class ssh_host_admin(ssh_terminal):
host_info['username'] = info_tmp['username']
host_info['password'] = info_tmp['password']
host_info['pkey'] = info_tmp['pkey']
+ host_info['pkey_passwd'] = ''
+ if 'pkey_passwd' in info_tmp:
+ host_info['pkey_passwd'] = info_tmp['pkey_passwd']
return host_info
def modify_host(self,args):
@@ -815,6 +895,7 @@ class ssh_host_admin(ssh_terminal):
username: 用户名
password: 密码
pkey: 密钥(如果不为空,将使用密钥连接)
+ pkey_passwd: 密钥的密码
}
@return dict
'''
@@ -823,12 +904,12 @@ class ssh_host_admin(ssh_terminal):
if args.host != args.new_host:
info_file = self._save_path + args.new_host +'/info.json'
if os.path.exists(info_file):
- return public.returnMsg(False,'SSH_LOGIN_ERR8')
+ return public.return_msg_gettext(False,'The specified host address has been added to other SSH information!')
info_file = self._save_path + args.host +'/info.json'
if not os.path.exists(info_file):
- return public.returnMsg(False,'SSH_LOGIN_ERR7')
+ return public.return_msg_gettext(False,'The specified SSH information does not exist!')
if not 'sort' in args:
r_data = public.aes_decrypt(public.readFile(info_file),self._pass_str)
@@ -843,14 +924,18 @@ class ssh_host_admin(ssh_terminal):
host_info['username'] = args['username']
host_info['password'] = args['password']
host_info['pkey'] = args['pkey']
+ if 'pkey_passwd' in args:
+ host_info['pkey_passwd'] = args['pkey_passwd']
+ else:
+ host_info['pkey_passwd'] = ''
if not host_info['pkey']: host_info['pkey'] = ''
result = self.set_attr(host_info)
if not result['status']: return result
self.save_ssh_info(args.host,host_info)
if args.host != args.new_host:
public.ExecShell('mv {} {}'.format(self._save_path + args.host,self._save_path + args.new_host))
- public.WriteLog(self._log_type,'MODIFY_SSH_INFO',(args.host,))
- return public.returnMsg(True,'EDIT_SUCCESS')
+ public.write_log_gettext(self._log_type,'Modify the SSH information of HOST: {}',(args.host,))
+ return public.return_msg_gettext(True,'Setup successfully!')
def create_host(self,args):
'''
@@ -864,6 +949,7 @@ class ssh_host_admin(ssh_terminal):
username: 用户名
password: 密码
pkey: 密钥(如果不为空,将使用密钥连接)
+ pkey_passwd: 密钥的密码
}
@return dict
'''
@@ -886,11 +972,14 @@ class ssh_host_admin(ssh_terminal):
host_info['username'] = args['username']
host_info['password'] = args['password']
host_info['pkey'] = args['pkey']
+ host_info['pkey_passwd'] = ''
+ if 'pkey_passwd' in args:
+ host_info['pkey_passwd'] = args['pkey_passwd']
result = self.set_attr(host_info)
if not result['status']: return result
self.save_ssh_info(args.host,host_info)
- public.WriteLog(self._log_type,'ADD_SSH_INFO',(str(args.host),))
- return public.returnMsg(True,'SET_SUCCESS')
+ public.write_log_gettext(self._log_type,'Add the SSH information of HOST: {}',(str(args.host),))
+ return public.return_msg_gettext(True,'Setup successfully!')
def remove_host(self,args):
@@ -903,13 +992,13 @@ class ssh_host_admin(ssh_terminal):
@return dict
'''
args.host = args.host.strip()
- if not args.host: return public.returnMsg(False,'INIT_ARGS_ERR')
+ if not args.host: return public.return_msg_gettext(False,'Parameter ERROR!')
host_path = self._save_path + args.host
if not os.path.exists(host_path):
- return public.returnMsg(False,'SSH_LOGIN_ERR7!')
+ return public.return_msg_gettext(False,'The specified SSH information does not exist!')
public.ExecShell("rm -rf {}".format(host_path))
- public.WriteLog(self._log_type,'DEL_SSH_INFO',(str(args.host),))
- return public.returnMsg(True,'SET_SUCCESS')
+ public.write_log_gettext(self._log_type,'Delete the SSH information of HOST: {}',(str(args.host),))
+ return public.return_msg_gettext(True,'Setup successfully!')
def get_ssh_info(self,host):
@@ -921,7 +1010,15 @@ class ssh_host_admin(ssh_terminal):
'''
info_file = self._save_path + host + '/info.json'
if not os.path.exists(info_file): return False
- r_data = public.aes_decrypt(public.readFile(info_file),self._pass_str)
+ try:
+ r_data = public.aes_decrypt(public.readFile(info_file),self._pass_str)
+ except ValueError as ex:
+ if str(ex).find('Incorrect AES key length') != -1:
+ if os.path.exists(self._pass_file):
+ os.remove(self._pass_file)
+ self.__create_aes_pass()
+ r_data = public.aes_decrypt(public.readFile(info_file),self._pass_str)
+
return json.loads(r_data)
def save_ssh_info(self,host,host_info):
@@ -954,7 +1051,7 @@ class ssh_host_admin(ssh_terminal):
@return bool
'''
if not 'sort_list' in args:
- return public.returnMsg(False,'SSH_LOGIN_ERR9')
+ return public.return_msg_gettext(False,'Please pass in the [sort_list] field')
sort_list = json.loads(args.sort_list)
for name in sort_list.keys():
info_file = self._save_path + name + '/info.json'
@@ -963,7 +1060,7 @@ class ssh_host_admin(ssh_terminal):
ssh_info = self.get_ssh_info(name)
ssh_info['sort'] = int(sort_list[name])
self.save_ssh_info(name,ssh_info)
- return public.returnMsg(True,'SET_SUCCESS')
+ return public.return_msg_gettext(True,'Setup successfully!')
def get_command_list(self,args = None, user_cmd = False , sys_cmd = False):
'''
@@ -1028,7 +1125,7 @@ class ssh_host_admin(ssh_terminal):
command = self.get_command_list(sys_cmd=True)
if self.command_exists(command,args.title):
- return public.returnMsg(False,'COMMAND_NAME_EXIST')
+ return public.return_msg_gettext(False,'The specified command name already exists')
cmd = {
"title": args.title,
@@ -1037,8 +1134,8 @@ class ssh_host_admin(ssh_terminal):
command.append(cmd)
self.save_command(command)
- public.WriteLog(self._log_type,'ADD_COMMAND_COMMAND',(str(args.title),))
- return public.returnMsg(True,'SET_SUCCESS')
+ public.write_log_gettext(self._log_type,'Add common commands [{}]',(str(args.title),))
+ return public.return_msg_gettext(True,'Setup successfully!')
def get_command_find(self,args = None, title=None):
'''
@@ -1053,9 +1150,9 @@ class ssh_host_admin(ssh_terminal):
if args: title = args.title.strip()
command = self.get_command_list()
for cmd in command:
- if cmd['title'] == title:
+ if cmd['title'] == title or cmd['title'] == args.title:
return cmd
- return public.returnMsg(False,'COMMAND_NOTEXIST')
+ return public.return_msg_gettext(False,'The specified command does not exist')
def modify_command(self,args):
'''
@@ -1068,18 +1165,18 @@ class ssh_host_admin(ssh_terminal):
}
@return dict
'''
- args.title = args.title.strip()
+ title = args.title.strip()
command = self.get_command_list(sys_cmd=True)
if not self.command_exists(command,args.title):
- return public.returnMsg(False,'COMMAND_NOTEXIST')
+ return public.return_msg_gettext(False,'The specified command does not exist')
for i in range(len(command)):
- if command[i]['title'] == args.title:
- command[i]['title'] = args.new_title
+ if command[i]['title'] == args.title or command[i]['title'] == title:
+ command[i]['title'] = args.new_title.strip()
command[i]['shell'] = args.shell.strip()
break
self.save_command(command)
- public.WriteLog(self._log_type,'EDIT_COMMAND_COMMAND',(str(args.title),))
- return public.returnMsg(True,'SET_SUCCESS')
+ public.write_log_gettext(self._log_type,'Modify common commands [{}]',(str(args.title),))
+ return public.return_msg_gettext(True,'Setup successfully!')
def remove_command(self,args):
'''
@@ -1093,12 +1190,12 @@ class ssh_host_admin(ssh_terminal):
args.title = args.title.strip()
command = self.get_command_list(sys_cmd=True)
if not self.command_exists(command,args.title):
- return public.returnMsg(False,'COMMAND_NOTEXIST')
+ return public.return_msg_gettext(False,'The specified command does not exist')
for i in range(len(command)):
if command[i]['title'] == args.title:
del(command[i])
break
self.save_command(command)
- public.WriteLog(self._log_type,'DEL_COMMAND_COMMAND',(str(args.title),))
- return public.returnMsg(True,'SET_SUCCESS')
\ No newline at end of file
+ public.write_log_gettext(self._log_type,'Delete common commands [{}]',(str(args.title),))
+ return public.return_msg_gettext(True,'Setup successfully!')
\ No newline at end of file
diff --git a/class/system.py b/class/system.py
index 00a12d5e..16989e60 100644
--- a/class/system.py
+++ b/class/system.py
@@ -28,7 +28,7 @@ class system:
data = session['config']
data['webserver'] = public.get_webserver()
#PHP版本
- phpVersions = ('52','53','54','55','56','70','71','72','73','74')
+ phpVersions = public.get_php_versions()
data['php'] = []
@@ -120,7 +120,7 @@ class system:
tmp['type'] = data['webserver']
- tmp['version'] = public.readFile(self.setupPath + '/'+data['webserver']+'/version.pl');
+ tmp['version'] = public.xss_version(public.readFile(self.setupPath + '/'+data['webserver']+'/version.pl'))
tmp['status'] = False
result = public.ExecShell('/etc/init.d/' + serviceName + ' status')
if result[0].find('running') != -1: tmp['status'] = True
@@ -128,7 +128,7 @@ class system:
tmp = {}
vfile = self.setupPath + '/phpmyadmin/version.pl'
- tmp['version'] = public.readFile(vfile)
+ tmp['version'] = public.xss_version(public.readFile(vfile))
if tmp['version']: tmp['version'] = tmp['version'].strip()
tmp['setup'] = os.path.exists(vfile)
tmp['status'] = pstatus
@@ -141,12 +141,12 @@ class system:
tmp['setup'] = os.path.exists('/etc/init.d/tomcat')
tmp['status'] = tmp['setup']
#if public.ExecShell('ps -aux|grep tomcat|grep -v grep')[0] == "": tmp['status'] = False
- tmp['version'] = public.readFile(self.setupPath + '/tomcat/version.pl')
+ tmp['version'] = public.xss_version(public.readFile(self.setupPath + '/tomcat/version.pl'))
data['tomcat'] = tmp
tmp = {}
tmp['setup'] = os.path.exists(self.setupPath +'/mysql/bin/mysql')
- tmp['version'] = public.readFile(self.setupPath + '/mysql/version.pl')
+ tmp['version'] = public.xss_version(public.readFile(self.setupPath + '/mysql/version.pl'))
tmp['status'] = os.path.exists('/tmp/mysql.sock')
data['mysql'] = tmp
@@ -162,7 +162,7 @@ class system:
tmp = {}
tmp['setup'] = os.path.exists(self.setupPath +'/pure-ftpd/bin/pure-pw')
- tmp['version'] = public.readFile(self.setupPath + '/pure-ftpd/version.pl')
+ tmp['version'] = public.xss_version(public.readFile(self.setupPath + '/pure-ftpd/version.pl'))
tmp['status'] = os.path.exists('/var/run/pure-ftpd.pid')
data['pure-ftpd'] = tmp
data['panel'] = self.GetPanelInfo()
@@ -281,14 +281,7 @@ class system:
key = 'sys_version'
version = cache.get(key)
if version: return version
- import public
- version = public.readFile('/etc/redhat-release')
- if not version:
- version = public.readFile('/etc/issue').strip().split("\n")[0].replace('\\n','').replace('\l','').strip()
- else:
- version = version.replace('release ','').replace('Linux','').replace('(Core)','').strip()
- v_info = sys.version_info
- version = version + '(Py' + str(v_info.major) + '.' + str(v_info.minor) + '.' + str(v_info.micro) + ')'
+ version = public.get_os_version()
cache.set(key,version,600)
return version
@@ -396,13 +389,17 @@ class system:
diskInfo.append(tmp)
return diskInfo
- def GetDiskInfo2(self):
+ def GetDiskInfo2(self, human=True):
+
#取磁盘分区信息
key = 'sys_disk'
diskInfo = cache.get(key)
if diskInfo: return diskInfo
- temp = public.ExecShell("df -hT -P|grep '/'|grep -v tmpfs|grep -v 'snap/core'|grep -v udev")[0]
- tempInodes = public.ExecShell("df -i -P|grep '/'|grep -v tmpfs|grep -v 'snap/core'|grep -v udev")[0]
+ if human:
+ temp = public.ExecShell("df -hT -P|grep '/'|grep -v tmpfs|grep -v 'snap/core'|grep -v udev|grep -v overlay")[0]
+ else:
+ temp = public.ExecShell("df -T -P|grep '/'|grep -v tmpfs|grep -v 'snap/core'|grep -v udev|grep -v overlay")[0]
+ tempInodes = public.ExecShell("df -i -P|grep '/'|grep -v tmpfs|grep -v 'snap/core'|grep -v udev|grep -v overlay")[0]
temp1 = temp.split('\n')
tempInodes1 = tempInodes.split('\n')
diskInfo = []
@@ -432,7 +429,7 @@ class system:
arr['inodes'] = [inodes[1],inodes[2],inodes[3],inodes[4]]
diskInfo.append(arr)
except Exception as ex:
- public.WriteLog('GET_INFO',str(ex))
+ public.write_log_gettext('Get Info',str(ex))
continue
cache.set(key,diskInfo,10)
return diskInfo
@@ -809,7 +806,7 @@ class system:
import ajax
get.status = 'True'
ajax.ajax().setPHPMyAdmin(get)
- return public.returnMsg(True,'SYS_EXEC_SUCCESS')
+ return public.return_msg_gettext(True,'Executed successfully!')
if get.name == 'openlitespeed':
if get.type == 'stop':
@@ -818,12 +815,12 @@ class system:
public.ExecShell('rm -f /tmp/lshttpd/*.sock* && /usr/local/lsws/bin/lswsctrl start')
else:
public.ExecShell('rm -f /tmp/lshttpd/*.sock* && /usr/local/lsws/bin/lswsctrl restart')
- return public.returnMsg(True,'SYS_EXEC_SUCCESS')
+ return public.return_msg_gettext(True,'Executed successfully!')
#检查httpd配置文件
if get.name == 'apache' or get.name == 'httpd':
get.name = 'httpd'
- if not os.path.exists(self.setupPath+'/apache/bin/apachectl'): return public.returnMsg(True,'SYS_NOT_INSTALL_APACHE')
+ if not os.path.exists(self.setupPath+'/apache/bin/apachectl'): return public.return_msg_gettext(True,'Execution failed, check if Apache installed')
vhostPath = self.setupPath + '/panel/vhost/apache'
if not os.path.exists(vhostPath):
public.ExecShell('mkdir ' + vhostPath)
@@ -835,8 +832,8 @@ class system:
result = public.ExecShell('ulimit -n 8192 ; ' + self.setupPath+'/apache/bin/apachectl -t')
if result[1].find('Syntax OK') == -1:
- public.WriteLog("TYPE_SOFT",'SYS_EXEC_ERR', (str(result),))
- return public.returnMsg(False,'SYS_CONF_APACHE_ERR',(result[1].replace("\n",'
'),))
+ public.write_log_gettext("Software manager",'Execution failed: {}', (str(result),))
+ return public.return_msg_gettext(False,"Apache rule configuration error:
{}",(result[1].replace("\n",'
'),))
if get.type == 'restart':
public.ExecShell('pkill -9 httpd')
@@ -847,12 +844,14 @@ class system:
elif get.name == 'nginx':
vhostPath = self.setupPath + '/panel/vhost/rewrite'
if not os.path.exists(vhostPath): public.ExecShell('mkdir ' + vhostPath)
+ if not os.path.exists("/dev/shm/nginx-cache/wp"):
+ public.ExecShell('mkdir -p /dev/shm/nginx-cache/wp && chown -R www.www /dev/shm/nginx-cache')
vhostPath = self.setupPath + '/panel/vhost/nginx'
if not os.path.exists(vhostPath):
public.ExecShell('mkdir ' + vhostPath)
public.ExecShell('/etc/init.d/nginx start')
- result = public.ExecShell('ulimit -n 8192 ; nginx -t -c '+self.setupPath+'/nginx/conf/nginx.conf')
+ result = public.ExecShell('ulimit -n 8192 ; '+self.setupPath+'/nginx/sbin/nginx -t -c '+self.setupPath+'/nginx/conf/nginx.conf')
if result[1].find('perserver') != -1:
limit = self.setupPath + '/nginx/conf/nginx.conf'
nginxConf = public.readFile(limit)
@@ -860,18 +859,18 @@ class system:
nginxConf = nginxConf.replace("#limit_conn_zone $binary_remote_addr zone=perip:10m;",limitConf)
public.writeFile(limit,nginxConf)
public.ExecShell('/etc/init.d/nginx start')
- return public.returnMsg(True,'SYS_CONF_NGINX_REP')
+ return public.return_msg_gettext(True,'Configuration file mismatch caused by reinstalling Nginx fixed')
if result[1].find('proxy') != -1:
import panelSite
panelSite.panelSite().CheckProxy(get)
public.ExecShell('/etc/init.d/nginx start')
- return public.returnMsg(True,'SYS_CONF_NGINX_REP')
+ return public.return_msg_gettext(True,'Configuration file mismatch caused by reinstalling Nginx fixed')
#return result
if result[1].find('successful') == -1:
- public.WriteLog("TYPE_SOFT",'SYS_EXEC_ERR', (str(result),))
- return public.returnMsg(False,'SYS_CONF_NGINX_ERR',(result[1].replace("\n",'
'),))
+ public.write_log_gettext("Software manager",'Execution failed: {}', (str(result),))
+ return public.return_msg_gettext(False,"Nginx rule configuration error:
{}",(result[1].replace("\n",'
'),))
if get.type == 'start':
self.kill_port()
@@ -903,14 +902,14 @@ class system:
public.ExecShell('pkill -9 nginx && sleep 1')
public.ExecShell('/etc/init.d/nginx start')
if get.type != 'test':
- public.WriteLog("TYPE_SOFT", 'SYS_EXEC_SUCCESS',(execStr,))
- if len(result[1]) > 1 and get.name != 'pure-ftpd' and get.name != 'redis': return public.returnMsg(False, 'Warning message:
' + result[1].replace('\n','
'))
- return public.returnMsg(True,'SYS_EXEC_SUCCESS')
+ public.write_log_gettext("Software manager", 'Executed successfully!',(execStr,))
+ if len(result[1]) > 1 and get.name != 'pure-ftpd' and get.name != 'redis': return public.return_msg_gettext(False, '
Warning message:
' + result[1].replace('\n','
'))
+ return public.return_msg_gettext(True,'Executed successfully!')
def RestartServer(self,get):
- if not public.IsRestart(): return public.returnMsg(False,'EXEC_ERR_TASK')
+ if not public.IsRestart(): return public.return_msg_gettext(False,'Please run the program when all install tasks finished!')
public.ExecShell("sync && init 6 &")
- return public.returnMsg(True,'SYS_REBOOT')
+ return public.return_msg_gettext(True,'Command sent successfully!')
def kill_port(self):
public.ExecShell('pkill -9 httpd')
@@ -931,7 +930,7 @@ class system:
def ReWeb(self,get):
public.ExecShell("/etc/init.d/bt start")
public.writeFile('data/restart.pl','True')
- return public.returnMsg(True,'PANEL_WAS_RESTART')
+ return public.return_msg_gettext(True,'Panel restarted')
#修复面板
diff --git a/class/tomcat.py b/class/tomcat.py
index 8488ad52..4456e8bf 100644
--- a/class/tomcat.py
+++ b/class/tomcat.py
@@ -27,8 +27,11 @@ class tomcat:
self.__ENGINE = self.__TREE.findall('Service/Engine')[0];
#获取虚拟主机列表
- def GetVhosts(self):
- Hosts = self.__ENGINE.getchildren();
+ def GetVhosts(self):
+ try:
+ Hosts = self.__ENGINE.getchildren()
+ except:
+ Hosts = list(self.__ENGINE)
data = []
for host in Hosts:
if host.tag != 'Host': continue;
@@ -63,7 +66,10 @@ class tomcat:
#获取指定虚拟主机
def GetVhost(self,name):
- Hosts = self.__ENGINE.getchildren();
+ try:
+ Hosts = self.__ENGINE.getchildren()
+ except:
+ Hosts = list(self.__ENGINE)
for host in Hosts:
if host.tag != 'Host': continue;
if host.attrib['name'] == name:
diff --git a/class/tools.py b/class/tools.py
index d81767c9..d8358a18 100644
--- a/class/tools.py
+++ b/class/tools.py
@@ -65,8 +65,8 @@ def set_panel_pwd(password,ncli = False):
result = sql.table('users').where('id=?',(1,)).setField('password',public.md5(password))
username = sql.table('users').where('id=?',(1,)).getField('username')
if ncli:
- print("|-%s: " % public.GetMsg("USER_NAME") + username)
- print("|-%s: " % public.GetMsg("NEW_PASS") + password)
+ print("|-%s: " % public.get_msg_gettext('Username') + username)
+ print("|-%s: " % public.get_msg_gettext('New password') + password)
else:
print(username)
@@ -107,28 +107,28 @@ echo '---------------------------------------------------------------------'
#封装
def PackagePanel():
print('========================================================')
- print('|-%s...' % public.GetMsg("CLEARING_LOG")),
- public.M('logs').where('id!=?',(0,)).delete();
+ print('|-%s...' % public.get_msg_gettext('Clearing log info')),
+ public.M('logs').where('id!=?',(0,)).delete()
print('\t\t\033[1;32m[done]\033[0m')
- print('|-%s...' % public.GetMsg("CLEARING_TASK_HISTORY")),
- public.M('tasks').where('id!=?',(0,)).delete();
+ print('|-%s...' % public.get_msg_gettext('Clearing task history')),
+ public.M('tasks').where('id!=?',(0,)).delete()
print('\t\t\033[1;32m[done]\033[0m')
- print('|-%s...' % public.GetMsg("CLEARING_NET_MO")),
- public.M('network').dbfile('system').where('id!=?',(0,)).delete();
+ print('|-%s...' % public.get_msg_gettext('Clearing network monitoring records')),
+ public.M('network').dbfile('system').where('id!=?',(0,)).delete()
print('\t\033[1;32m[done]\033[0m')
- print('|-%s...' % public.GetMsg("CLEARING_CPU_MO")),
- public.M('cpuio').dbfile('system').where('id!=?',(0,)).delete();
+ print('|-%s...' % public.get_msg_gettext('Clearing CPU monitoring records')),
+ public.M('cpuio').dbfile('system').where('id!=?',(0,)).delete()
print('\t\033[1;32m[done]\033[0m')
- print('|-%s...' % public.GetMsg("CLEARING_DISK_MO")),
- public.M('diskio').dbfile('system').where('id!=?',(0,)).delete();
+ print('|-%s...' % public.get_msg_gettext('Clearing disk monitoring records')),
+ public.M('diskio').dbfile('system').where('id!=?',(0,)).delete()
print('\t\033[1;32m[done]\033[0m')
- print('|-%s...' % public.GetMsg('CLEARING_IP')),
+ print('|-%s...' % public.get_msg_gettext('Clearing IP info')),
os.system('rm -f /www/server/panel/data/iplist.txt')
os.system('rm -f /www/server/panel/data/address.pl')
os.system('rm -f /www/server/panel/data/*.login')
os.system('rm -f /www/server/panel/data/domain.conf')
print('\t\033[1;32m[done]\033[0m')
- print('|-%s...' % public.GetMsg("CLEARING_SYS_HISTORY")),
+ print('|-%s...' % public.get_msg_gettext('Clearing system history')),
command = '''cat /dev/null > /var/log/boot.log
cat /dev/null > /var/log/btmp
cat /dev/null > /var/log/cron
@@ -154,8 +154,8 @@ history -c
port = public.readFile('data/port.pl').strip();
public.M('config').where("id=?",('1',)).setField('status',0);
print('========================================================')
- print('\033[1;32m|-%s\033[0m' % public.GetMsg("PANEL_TIPS"))
- print('\033[1;41m|-%s: http://{SERVERIP}:' % public.GetMsg("PANEL_INIT_ADD")+port+'/install\033[0m')
+ print('\033[1;32m|-%s\033[0m' % public.get_msg_gettext('The panel is packaged successfully. Please do NOT log in to the panel to do any other operations!'))
+ print('\033[1;41m|-%s: http://{SERVERIP}:' % public.get_msg_gettext('Panel initialization address')+port+'/install\033[0m')
#清空正在执行的任务
def CloseTask():
@@ -163,7 +163,7 @@ def CloseTask():
os.system("kill `ps -ef |grep 'python panelSafe.pyc'|grep -v grep|grep -v panelExec|awk '{print $2}'`");
os.system("kill `ps -ef |grep 'install_soft.sh'|grep -v grep|grep -v panelExec|awk '{print $2}'`");
os.system('/etc/init.d/bt restart');
- print(public.GetMsg("CLEAR_TASK",(int(ncount),)))
+ print(public.get_msg_gettext('Successfully cleared {} tasks!',(int(ncount),)))
#自签证书
def CreateSSL():
@@ -217,7 +217,7 @@ def ClearSystem():
count += tmp_count;
total += tmp_total;
print('=======================================================================')
- print('\033[1;32m|-%s\033[0m' % public.GetMsg("CLEAR_RUBBISH",(str(count),ToSize(total))));
+ print('\033[1;32m|-%s\033[0m' % public.get_msg_gettext('System rubbish cleared, totally deleted [{}] files, freed disk space [{}]',(str(count),ToSize(total))));
#清理邮件日志
def ClearMail():
@@ -242,11 +242,11 @@ def ClearMail():
os.remove(filename)
print('\t\033[1;32m[OK]\033[0m')
num += 1
- print(public.GetMsg("CLEAR_RUBBISH1",(dpath,str(num),ToSize(size))))
+ print(public.get_msg_gettext('|-Cleared [{}], deleted [{}] files, freed disk space [{}]',(dpath,str(num),ToSize(size))))
total += size;
count += num;
print('=======================================================================')
- print(public.GetMsg('CLEAR_RUBBISH2',(str(count),ToSize(total))))
+ print(public.get_msg_gettext('|-Spool cleared, deleted [{}] files, freed disk space [{}]',(str(count),ToSize(total))))
return total,count
#清理php_session文件
@@ -254,7 +254,7 @@ def ClearSession():
spath = '/tmp'
total = count = 0;
import shutil
- print(public.GetMsg("CLEAR_PHP_SESSION"));
+ print(public.get_msg_gettext('|-Clearing PHP Session ...'));
for d in os.listdir(spath):
if d.find('sess_') == -1: continue;
filename = spath + '/' + d;
@@ -267,7 +267,7 @@ def ClearSession():
os.remove(filename)
print('\t\033[1;32m[OK]\033[0m')
count += 1;
- print(public.GetMsg("CLEAR_PHP_SESSION1",(str(count),ToSize(total))))
+ print(public.get_msg_gettext('|-PHP session cleared, deleted [{}] files, freed disk space [{}]',(str(count),ToSize(total))))
return total,count
#清空回收站
@@ -288,7 +288,7 @@ def ClearOther():
]
total = count = 0;
- print(public.GetMsg('CLEAR_RUBBISH3'));
+ print(public.get_msg_gettext('|-Clearing up temporary files and site logs...'));
for c in clearPath:
for d in os.listdir(c['path']):
if d.find(c['find']) == -1: continue;
@@ -304,7 +304,7 @@ def ClearOther():
count += 1;
public.serviceReload();
os.system('sleep 1 && /etc/init.d/bt reload > /dev/null &');
- print(public.GetMsg("CLEAR_RUBBISH4",(str(count),ToSize(total))))
+ print(public.get_msg_gettext('|-Temporary files and site logs cleared, deleted [{}] files, freed disk space [{}]',(str(count),ToSize(total))))
return total,count
#关闭普通日志
@@ -336,14 +336,14 @@ def set_panel_username(username = None):
sql = db.Sql()
if username:
if len(username) < 5:
- print(public.GetMsg("USER_NAME_LEN_ERR"))
+ print(public.get_msg_gettext('|-ERROR, username cannot be less than 5 characters'))
return;
if username in ['admin','root']:
- print(public.GetMsg("EASY_NAME"))
+ print(public.get_msg_gettext('|-ERROR, cannot use too simple username'))
return;
sql.table('users').where('id=?',(1,)).setField('username',username)
- print(public.GetMsg("NEW_NAME",(username,)))
+ print(public.get_msg_gettext('|-New username: {}',(username,)))
return;
username = sql.table('users').where('id=?',(1,)).getField('username')
@@ -365,14 +365,14 @@ def setup_idc():
pFile = panelPath + '/static/language/Simplified_Chinese/public.json'
pInfo = json.loads(public.readFile(pFile))
pInfo['BRAND'] = idcInfo['msg']['name']
- pInfo['PRODUCT'] = public.GetMsg("WITH_BT_CUSTOM_EDITION")
+ pInfo['PRODUCT'] = public.get_msg_gettext('Customized edition with aaPanel')
pInfo['NANE'] = pInfo['BRAND'] + pInfo['PRODUCT']
public.writeFile(pFile,json.dumps(pInfo))
tFile = panelPath + '/data/title.pl'
- titleNew = (pInfo['BRAND'] + public.GetMsg("PANEL")).encode('utf-8')
+ titleNew = (pInfo['BRAND'] + public.get_msg_gettext('Failed,cannot delete current port of the panel!')).encode('utf-8')
if os.path.exists(tFile):
title = public.readFile(tFile).strip()
- if title == public.GetMsg("NAME") or title == '': public.writeFile(tFile,titleNew)
+ if title == public.get_msg_gettext('aaPanel') or title == '': public.writeFile(tFile,titleNew)
else:
public.writeFile(tFile,titleNew)
return True
@@ -381,48 +381,48 @@ def setup_idc():
#将插件升级到6.0
def update_to6():
print("====================================================")
- print(public.GetMsg("PLUG_UPDATEING"))
+ print(public.get_msg_gettext('Updating plugin...'))
print("====================================================")
download_address = public.get_url()
exlodes = ['gitlab','pm2','mongodb','deployment_jd','logs','docker','beta','btyw']
for pname in os.listdir('plugin/'):
if not os.path.isdir('plugin/' + pname): continue
if pname in exlodes: continue
- print("|-正在升级【%s】..." % pname),
- download_url = download_address + '/install/plugin/' + pname + '/install.sh';
+ print(public.get_msg_gettext("|-Upgrading [{}]...",(pname,))),
+ download_url = download_address + '/install/plugin/' + pname + '/install.sh'
to_file = '/tmp/%s.sh' % pname
- public.downloadFile(download_url,to_file);
- os.system('/bin/bash ' + to_file + ' install &> /tmp/plugin_update.log 2>&1');
- print(" \033[32m[%s]\033[0m" % public.GetMsg("SUCCESS"))
+ public.downloadFile(download_url,to_file)
+ os.system('/bin/bash ' + to_file + ' install &> /tmp/plugin_update.log 2>&1')
+ print(" \033[32m[%s]\033[0m" % public.get_msg_gettext('Login succeeded, loading...'))
print("====================================================")
- print("\033[32m%s\033[0m" % public.GetMsg("PLUG_UPDATE_TO_6"))
+ print("\033[32m%s\033[0m" % public.get_msg_gettext('All plugins successfully updated to 6.0 compatible!'))
print("====================================================")
#命令行菜单
def bt_cli():
raw_tip = "==============================================="
- print("===============%s==================" % public.GetMsg("PANEL_SHELL"))
- print("(01) %s (08) %s" % (public.GetMsg("RESTART_PANEL"),public.GetMsg("CHANGE_PANEL_PORT")))
- print("(02) %s (09) %s" % (public.GetMsg("STOP_PANEL"),public.GetMsg("CLEAR_PANEL_CACHE")))
- print("(03) %s (10) %s" % (public.GetMsg("START_PANEL"),public.GetMsg("CLEAR_PANEL_LIMIT")))
- print("(04) %s (11) %s" % (public.GetMsg("RELOAD_PANEL"),public.GetMsg("CANCEL_ENTRY")))
- print("(05) %s (12) %s" % (public.GetMsg("CHANGE_PANEL_PASS"),public.GetMsg("CANCEL_DOMAIN_BIND")))
- print("(06) %s (13) %s" % (public.GetMsg("CHANGE_PANEL_USER"),public.GetMsg("CANCEL_IP_LIMIT")))
- print("(07) %s (14) %s" % (public.GetMsg("CHANGE_MYSQL_PASS_FORCE"),public.GetMsg("GET_PANEL_DEFAULT_MSG")))
- print("(00) %s (15) %s" % (public.GetMsg("CANCEL"),public.GetMsg("CLEAR_SYS_RUBBISH")))
+ print("===============%s==================" % public.get_msg_gettext('aaPanel CLI'))
+ print("(01) %s (08) %s" % (public.get_msg_gettext('Restart panel'),public.get_msg_gettext('Change panel port')))
+ print("(02) %s (09) %s" % (public.get_msg_gettext('Stop panel'),public.get_msg_gettext('Clear panel cache')))
+ print("(03) %s (10) %s" % (public.get_msg_gettext('Restart panel'),public.get_msg_gettext('Clear login limit')))
+ print("(04) %s (11) %s" % (public.get_msg_gettext('Reload panel'),public.get_msg_gettext('Cancel entrance limit')))
+ print("(05) %s (12) %s" % (public.get_msg_gettext('Change panel password'),public.get_msg_gettext('Cancel domain binding limit')))
+ print("(06) %s (13) %s" % (public.get_msg_gettext('Change panel username'),public.get_msg_gettext('Cacel IP access limit')))
+ print("(07) %s (14) %s" % (public.get_msg_gettext('Forcibly change MySQL root password'),public.get_msg_gettext('View panel default info')))
+ print("(00) %s (15) %s" % (public.get_msg_gettext('Task cancelled!'),public.get_msg_gettext('Clear system rubbish')))
print(raw_tip)
try:
- u_input = input(public.GetMsg("INPUT_CMD_NUM"))
+ u_input = input(public.get_msg_gettext('Pls enter command number:'))
if sys.version_info[0] == 3: u_input = int(u_input)
except: u_input = 0
nums = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
if not u_input in nums:
print(raw_tip)
- print(public.GetMsg("CANCELLED"))
+ print(public.get_msg_gettext('Cacelled!'))
exit()
print(raw_tip)
- print(public.GetMsg("EXECUTING",(u_input,)))
+ print(public.get_msg_gettext('Executing ({})...',(u_input,)))
print(raw_tip)
if u_input == 1:
@@ -435,55 +435,55 @@ def bt_cli():
os.system("/etc/init.d/bt reload")
elif u_input == 5:
if sys.version_info[0] == 2:
- input_pwd = raw_input(public.GetMsg("INPUT_NEW_PASS"))
+ input_pwd = raw_input(public.get_msg_gettext('Pls enter new password: '))
else:
- input_pwd = input(public.GetMsg("INPUT_NEW_PASS"))
+ input_pwd = input(public.get_msg_gettext('Pls enter new password: '))
set_panel_pwd(input_pwd.strip(),True)
elif u_input == 6:
if sys.version_info[0] == 2:
- input_user = raw_input(public.GetMsg("INPUT_NEW_USER"))
+ input_user = raw_input(public.get_msg_gettext('Pls enter new username(>5 characters): '))
else:
- input_user = input(public.GetMsg("INPUT_NEW_USER"))
+ input_user = input(public.get_msg_gettext('Pls enter new username(>5 characters): '))
set_panel_username(input_user.strip())
elif u_input == 7:
if sys.version_info[0] == 2:
- input_mysql = raw_input(public.GetMsg("INPUT_NEW_MYSQL_PASS"))
+ input_mysql = raw_input(public.get_msg_gettext('Pls enter new MySQL root password:'))
else:
- input_mysql = input(public.GetMsg("INPUT_NEW_MYSQL_PASS"))
+ input_mysql = input(public.get_msg_gettext('Pls enter new MySQL root password:'))
if not input_mysql:
- print(public.GetMsg("PASS_NOT_EMPTY"))
- return;
+ print(public.get_msg_gettext('|-ERROR, password cannot be empty'))
+ return
if len(input_mysql) < 8:
- print(public.GetMsg("PASS_LEN_ERR"))
- return;
+ print(public.get_msg_gettext('|-ERROR, password cannot be less than 8 characters'))
+ return
import re
rep = "^[\w@\._]+$"
if not re.match(rep, input_mysql):
- print(public.GetMsg("PASS_SPECIAL_CHARACTRES_ERR"))
- return;
+ print(public.get_msg_gettext('|-ERROR, password cannot contain special characters'))
+ return
print(input_mysql)
set_mysql_root(input_mysql.strip())
elif u_input == 8:
- input_port = input(public.GetMsg("INPUT_NEW_PANEL_PORT"))
+ input_port = input(public.get_msg_gettext('Pls enter new panel port: '))
if sys.version_info[0] == 3: input_port = int(input_port)
if not input_port:
- print(public.GetMsg("INPUT_PANEL_PORT_ERR"))
- return;
+ print(public.get_msg_gettext('|-ERROR, no valid port entered'))
+ return
if input_port in [80,443,21,20,22]:
- print(public.GetMsg("CANT_USE_USUALLY_PORT_ERR"))
- return;
+ print(public.get_msg_gettext('|-ERROR, pls do NOT use the common port as panel port'))
+ return
old_port = int(public.readFile('data/port.pl'))
if old_port == input_port:
- print(public.GetMsg("NEW_PORT_SAMEAS_OLD"))
- return;
+ print(public.get_msg_gettext('|-ERROR, new port is the same as current panel port, no need to change'))
+ return
is_exists = public.ExecShell("lsof -i:%s" % input_port)
if len(is_exists[0]) > 5:
- print(public.GetMsg("PORT_ALREADY_IN_USE"))
- return;
+ print(public.get_msg_gettext('|-ERROR, specified port is already in use'))
+ return
public.writeFile('data/port.pl',str(input_port))
if os.path.exists("/usr/bin/firewall-cmd"):
@@ -507,17 +507,17 @@ def bt_cli():
auth_file = 'data/admin_path.pl'
if os.path.exists(auth_file): os.remove(auth_file)
os.system("/etc/init.d/bt reload")
- print(public.GetMsg("CHANGE_LIMITED_CANCEL"))
+ print(public.get_msg_gettext('|-Entrance limit cancelled'))
elif u_input == 12:
auth_file = 'data/domain.conf'
if os.path.exists(auth_file): os.remove(auth_file)
os.system("/etc/init.d/bt reload")
- print(public.GetMsg("CHANGE_DOMAIN_CANCEL"))
+ print(public.get_msg_gettext('|-Domain limit cancelled'))
elif u_input == 13:
auth_file = 'data/limitip.conf'
if os.path.exists(auth_file): os.remove(auth_file)
os.system("/etc/init.d/bt reload")
- print(public.GetMsg("CHANGE_IP_CANCEL"))
+ print(public.get_msg_gettext('|-IP access limit cancelled'))
elif u_input == 14:
os.system("/etc/init.d/bt default")
elif u_input == 15:
diff --git a/class/userlogin.py b/class/userlogin.py
index 8d05ced4..740288fa 100644
--- a/class/userlogin.py
+++ b/class/userlogin.py
@@ -12,43 +12,74 @@ from BTPanel import session,cache,json_header
from flask import request,redirect,g
class userlogin:
-
+ limit_expire_time = 0
def request_post(self,post):
if not hasattr(post, 'username') or not hasattr(post, 'password'):
- return public.returnJson(False,'LOGIN_USER_EMPTY'),json_header
+ return public.returnJson(False,'User name or password cannot be empty!'),json_header
self.error_num(False)
- if self.limit_address('?') < 1: return public.returnJson(False,'LOGIN_ERR_LIMIT'),json_header
+ if self.limit_address('?') < 1: return public.returnJson(False,'You have failed to log in many times。 Please wait for {} seconds and try again!'.format(int(self.limit_expire_time - time.time()))),json_header
+ # if self.limit_address('?') < 1: return public.returnJson(False,'You cannot login now because login failed too many times!'),json_header
post.username = post.username.strip()
+ # 核验用户名密码格式
+ if len(post.username) != 32: return public.return_msg_gettext(False,'Disk inode has been exhausted, the panel has attempted to release the inode. Please try again ...'),json_header
+ if len(post.password) != 32: return public.return_msg_gettext(False,'Disk inode has been exhausted, the panel has attempted to release the inode. Please try again ...'),json_header
+ if not re.match(r"^\w+$",post.username): return public.return_msg_gettext(False,'Disk inode has been exhausted, the panel has attempted to release the inode. Please try again ...'),json_header
+ if not re.match(r"^\w+$",post.password): return public.return_msg_gettext(False,'Disk inode has been exhausted, the panel has attempted to release the inode. Please try again ...'),json_header
+ last_login_token = session.get('last_login_token',None)
+ if not last_login_token:
+ public.write_log_gettext('Login','Verification code error, account number: {}, verification code: {}, login IP: {}',('****','****',public.GetClientIp()))
+ return public.returnJson(False,"Verification failed, please refresh the page and log in again!"),json_header
+
public.chdck_salt()
sql = db.Sql()
- user_list = sql.table('users').field('id,username,password,salt').select()
userInfo = None
- for u_info in user_list:
- if public.md5(u_info['username']) == post.username:
- userInfo = u_info
+ user_plugin_file = '{}/users_main.py'.format(public.get_plugin_path('users'))
+ if os.path.exists(user_plugin_file):
+ user_list = sql.table('users').field('id,username,password,salt').select()
+ for u_info in user_list:
+ if public.md5(public.md5(u_info['username'] + last_login_token)) == post.username:
+ userInfo = u_info
+ else:
+ userInfo = sql.table('users').where('id=?',1).field('id,username,password,salt').find()
+
+
if 'code' in session:
if session['code'] and not 'is_verify_password' in session:
if not hasattr(post, 'code'): return public.returnJson(False,'Verification code can not be empty!'),json_header
+ if not re.match(r"^\w+$",post.code): return public.returnJson(False,'Verification code is incorrect, please try again!'),json_header
if not public.checkCode(post.code):
- public.WriteLog('TYPE_LOGIN','LOGIN_ERR_CODE',('****','****',public.GetClientIp()))
- return public.returnJson(False,'CODE_ERR'),json_header
+ public.write_log_gettext('Login','Verification code is incorrect, Username:{}, Verification Code:{}, Login IP:{}',('****','****',public.GetClientIp()))
+ return public.returnJson(False,'Verification code is incorrect, please try again!'),json_header
try:
- if not userInfo['salt']:
+ if not userInfo:
+ public.write_log_gettext('Login','Wrong password, account: {}, password: {}, login IP: {}',('****','******',public.GetClientIp()))
+ num = self.limit_address('+')
+ if not num: return public.returnJson(False,'You have failed to log in many times, please wait {} seconds and try again!'.format(int(self.limit_expire_time - time.time()))),json_header
+ return public.returnJson(False,'Username or password is wrong, Please refresh the page and try again, you can try again [{}] times'.format(num)),json_header
+
+ if userInfo and not userInfo['salt']:
public.chdck_salt()
userInfo = sql.table('users').where('id=?',(userInfo['id'],)).field('id,username,password,salt').find()
password = public.md5(post.password.strip() + userInfo['salt'])
- if public.md5(userInfo['username']) != post.username or userInfo['password'] != password:
- public.WriteLog('TYPE_LOGIN','LOGIN_ERR_PASS',('****','******',public.GetClientIp()))
+ s_username = public.md5(public.md5(userInfo['username'] + last_login_token))
+ if s_username != post.username or userInfo['password'] != password:
+ public.write_log_gettext('Login','Password is incorrect, Username:{}, Password:{}, Login IP:{}',('****','******',public.GetClientIp()))
num = self.limit_address('+')
- return public.returnJson(False,'LOGIN_USER_ERR',(str(num),)),json_header
+ if not num: return public.returnJson(False,'You have failed to log in many times, please wait {} seconds and try again!'.format(int(self.limit_expire_time - time.time()))),json_header
+ return public.returnJson(False,'Invalid username or password. You have [{}] times left to try!',(str(num),)),json_header
_key_file = "/www/server/panel/data/two_step_auth.txt"
- #登陆告警
- public.run_thread(public.login_send_body,("Userinfo",userInfo['username'],public.GetClientIp(),str(request.environ.get('REMOTE_PORT'))))
+
+ # 密码过期检测
+ if sys.path[0] != 'class/': sys.path.insert(0,'class/')
+ if not public.password_expire_check():
+ session['password_expire'] = True
+
# public.login_send_body("Userinfo",userInfo['username'],public.GetClientIp(),str(request.environ.get('REMOTE_PORT')))
if hasattr(post,'vcode'):
+ if not re.match(r"^\d+$",post.vcode): return public.returnJson(False,'Incorrect format of verification code'),json_header
if self.limit_address('?',v="vcode") < 1: return public.returnJson(False,'You have failed verification many times, forbidden for 10 minutes'),json_header
import pyotp
secret_key = public.readFile(_key_file)
@@ -62,6 +93,7 @@ class userlogin:
num = self.limit_address('++',v="vcode")
return public.returnJson(False, 'Invalid Verification code. You have [{}] times left to try!'.format(num)), json_header
now = int(time.time())
+ # public.run_thread(public.login_send_body,("account",userInfo['username'],public.GetClientIp(),str(int(request.environ.get('REMOTE_PORT')))))
public.writeFile("/www/server/panel/data/dont_vcode_ip.txt",json.dumps({"client_ip":public.GetClientIp(),"add_time":now}))
self.limit_address('--',v="vcode")
self.set_cdn_host(post)
@@ -70,6 +102,7 @@ class userlogin:
acc_client_ip = self.check_two_step_auth()
if not os.path.exists(_key_file) or acc_client_ip:
+ # public.run_thread(public.login_send_body,("account",userInfo['username'],public.GetClientIp(),str(int(request.environ.get('REMOTE_PORT')))))
self.set_cdn_host(post)
return self._set_login_session(userInfo)
self.limit_address('-')
@@ -82,28 +115,30 @@ class userlogin:
public.ExecShell("rm -f /www/wwwlogs/*log")
public.ServiceReload()
return public.returnJson(False,'USER_INODE_ERR'),json_header
- public.WriteLog('TYPE_LOGIN','LOGIN_ERR_PASS',('****','******',public.GetClientIp()))
+ public.write_log_gettext('Login','Password is incorrect, Username:{}, Password:{}, Login IP:{}',('****','******',public.GetClientIp()))
num = self.limit_address('+')
- return public.returnJson(False,'LOGIN_USER_ERR',(str(num),)),json_header
+ if not num: return public.returnJson(False,'You have failed to log in many times, please wait {} seconds and try again!'.format(int(self.limit_expire_time - time.time()))),json_header
+ return public.returnJson(False,'Invalid username or password. You have [{}] times left to try!',(str(num),)),json_header
def request_tmp(self,get):
try:
- if not hasattr(get,'tmp_token'): return public.returnJson(False,'INIT_ARGS_ERR'),json_header
+ if not hasattr(get,'tmp_token'): return public.returnJson(False,'Parameter ERROR!'),json_header
if len(get.tmp_token) == 48:
return self.request_temp(get)
- if len(get.tmp_token) != 64: return public.returnJson(False,'INIT_ARGS_ERR'),json_header
- if not re.match(r"^\w+$",get.tmp_token):return public.returnJson(False,'INIT_ARGS_ERR'),json_header
+ if len(get.tmp_token) != 64: return public.returnJson(False,'Parameter ERROR!'),json_header
+ if not re.match(r"^\w+$",get.tmp_token):return public.returnJson(False,'Parameter ERROR!'),json_header
save_path = '/www/server/panel/config/api.json'
data = json.loads(public.ReadFile(save_path))
- if not 'tmp_token' in data or not 'tmp_time' in data: return public.returnJson(False,'VERIFICATION_FAILED'),json_header
- if (time.time() - data['tmp_time']) > 120: return public.returnJson(False,'EXPIRED_TOKEN'),json_header
- if get.tmp_token != data['tmp_token']: return public.returnJson(False,'INIT_TOKEN_ERR'),json_header
+ if not 'tmp_token' in data or not 'tmp_time' in data: return public.returnJson(False,'Verification failed'),json_header
+ if (time.time() - data['tmp_time']) > 120: return public.returnJson(False,'Expired Token'),json_header
+ if get.tmp_token != data['tmp_token']: return public.returnJson(False,'Invalid Token!'),json_header
userInfo = public.M('users').where("id=?",(1,)).field('id,username').find()
session['login'] = True
session['username'] = userInfo['username']
session['tmp_login'] = True
session['uid'] = userInfo['id']
- public.WriteLog('TYPE_LOGIN','LOGIN_SUCCESS',(userInfo['username'],public.GetClientIp()+ ":" + str(request.environ.get('REMOTE_PORT'))))
+ ids = public.write_log_gettext('Login','Login success',(userInfo['username'],public.GetClientIp()+ ":" + str(request.environ.get('REMOTE_PORT'))))
+ public.cache_set(public.GetClientIp() + ":" + str(request.environ.get('REMOTE_PORT')), ids)
self.limit_address('-')
cache.delete('panelNum')
cache.delete('dologin')
@@ -121,28 +156,32 @@ class userlogin:
def request_temp(self,get):
try:
- if len(get.__dict__.keys()) > 2: return public.getMsg('INIT_ARGS_ERR')
- if not hasattr(get,'tmp_token'): return public.getMsg('INIT_ARGS_ERR')
- if len(get.tmp_token) != 48: return public.getMsg('INIT_ARGS_ERR')
- if not re.match(r"^\w+$",get.tmp_token):return public.getMsg('INIT_ARGS_ERR')
+ if len(get.__dict__.keys()) > 2: return public.get_msg_gettext('Parameter ERROR!')
+ if not hasattr(get,'tmp_token'): return public.get_msg_gettext('Parameter ERROR!')
+ if len(get.tmp_token) != 48: return public.get_msg_gettext('Parameter ERROR!')
+ if not re.match(r"^\w+$",get.tmp_token):return public.get_msg_gettext('Parameter ERROR!')
skey = public.GetClientIp() + '_temp_login'
- if not public.get_error_num(skey,10): return public.getMsg('AUTH_FAILED')
+ if not public.get_error_num(skey,10): return public.get_msg_gettext('10 consecutive authentication failures are prohibited for 1 hour')
s_time = int(time.time())
+ if public.M('temp_login').where('state=? and expire>?',(0,s_time)).field('id,token,salt,expire').count()==0:
+ public.set_error_num(skey)
+ return public.get_msg_gettext('Verification failed')
+
data = public.M('temp_login').where('state=? and expire>?',(0,s_time)).field('id,token,salt,expire').find()
if not data:
public.set_error_num(skey)
- return public.getMsg('VERIFICATION_FAILED')
+ return public.get_msg_gettext('Verification failed')
if not isinstance(data,dict):
public.set_error_num(skey)
- return public.getMsg('VERIFICATION_FAILED')
+ return public.get_msg_gettext('Verification failed')
r_token = public.md5(get.tmp_token + data['salt'])
if r_token != data['token']:
public.set_error_num(skey)
- return public.getMsg('VERIFICATION_FAILED')
+ return public.get_msg_gettext('Verification failed')
public.set_error_num(skey,True)
userInfo = public.M('users').where("id=?",(1,)).field('id,username').find()
session['login'] = True
- session['username'] = public.getMsg('TEMPORARY_ID',(data['id'],))
+ session['username'] = public.get_msg_gettext('TEMPORARY_ID',(data['id'],))
session['tmp_login'] = True
session['tmp_login_id'] = str(data['id'])
session['tmp_login_expire'] = time.time() + 3600
@@ -152,7 +191,8 @@ class userlogin:
os.makedirs(sess_path,384)
public.writeFile(sess_path + '/' + str(data['id']),'')
login_addr = public.GetClientIp()+ ":" + str(request.environ.get('REMOTE_PORT'))
- public.WriteLog('TYPE_LOGIN','LOGIN_SUCCESS',(userInfo['username'],login_addr))
+ ids = public.write_log_gettext('Login','Login succeed, Username: {}, Login IP: {}',(userInfo['username'],login_addr))
+ public.cache_set(public.GetClientIp()+ ":" + str(request.environ.get('REMOTE_PORT')),ids)
public.M('temp_login').where('id=?',(data['id'],)).update({"login_time":s_time,'state':1,'login_addr':login_addr})
self.limit_address('-')
cache.delete('panelNum')
@@ -161,10 +201,10 @@ class userlogin:
self.set_request_token()
self.login_token()
self.set_cdn_host(get)
- public.login_send_body("Temporary authorization",userInfo['username'],public.GetClientIp(),str(request.environ.get('REMOTE_PORT')))
+ public.run_thread(public.login_send_body("Temporary authorization",userInfo['username'],public.GetClientIp(),str(request.environ.get('REMOTE_PORT'))))
return redirect('/')
except:
- return public.getMsg('LOGIN_FAIL')
+ return public.get_msg_gettext('Login failed')
def login_token(self):
@@ -172,40 +212,40 @@ class userlogin:
config.config().reload_session()
def request_get(self,get):
- #if os.path.exists('/www/server/panel/install.pl'): raise redirect('/install');
+ '''
+ @name 验证登录页面请求权限
+ @author hwliang
+ @return False | Response
+ '''
+ # 获取标题
if not 'title' in session: session['title'] = public.getMsg('NAME')
- domain = public.readFile('data/domain.conf')
-
- if domain:
- if(public.GetHost().lower() != domain.strip().lower()):
- return 404
- # errorStr = public.ReadFile('./BTPanel/templates/' + public.GetConfigValue('template') + '/error2.html')
- # try:
- # errorStr = errorStr.format(public.getMsg('PAGE_ERR_TITLE'),public.getMsg('PAGE_ERR_DOMAIN_H1'),public.getMsg('PAGE_ERR_DOMAIN_P1'),public.getMsg('PAGE_ERR_DOMAIN_P2'),public.getMsg('PAGE_ERR_DOMAIN_P3'),public.getMsg('NAME'),public.getMsg('PAGE_ERR_HELP'))
- # except IndexError:pass
- # return errorStr
- if os.path.exists('data/limitip.conf'):
- iplist = public.readFile('data/limitip.conf')
- if iplist:
- iplist = iplist.strip()
- if not public.GetClientIp() in iplist.split(','):
- errorStr = public.ReadFile('./BTPanel/templates/' + public.GetConfigValue('template') + '/error2.html')
- try:
- errorStr = errorStr.format(public.getMsg('PAGE_ERR_TITLE'),public.getMsg('PAGE_ERR_IP_H1'),public.getMsg('PAGE_ERR_IP_P1',(public.GetClientIp(),)),public.getMsg('PAGE_ERR_IP_P2'),public.getMsg('PAGE_ERR_IP_P3'),public.getMsg('NAME'),public.getMsg('PAGE_ERR_HELP'))
- except IndexError:pass
- return errorStr
+ # 验证是否使用限制的域名访问
+ domain_check = public.check_domain_panel()
+ if domain_check: return domain_check
+
+ # 验证是否使用限制的IP地址访问
+ ip_check = public.check_ip_panel()
+ if ip_check: return ip_check
+
+ # 验证是否已经登录
if 'login' in session:
if session['login'] == True:
return redirect('/')
+ # 复位验证码
if not 'code' in session:
session['code'] = False
+
+ # 记录错误次数
self.error_num(False)
#生成request_token
def set_request_token(self):
- session['request_token_head'] = public.GetRandomString(48)
+ html_token_key = public.get_csrf_html_token_key()
+ session[html_token_key] = public.GetRandomString(48)
+ session[html_token_key.replace("https_","")] = public.GetRandomString(48)
+
def set_cdn_host(self,get):
try:
@@ -227,21 +267,22 @@ class userlogin:
num = 1
if s: cache.inc(nKey,1)
if num > 6: session['code'] = True
-
+
#IP限制
def limit_address(self,type,v=""):
- import time
clientIp = public.GetClientIp()
numKey = 'limitIpNum_' + v + clientIp
- limit = 6
- outTime = 600
+ limit = 5
+ outTime = 300
try:
#初始化
num1 = cache.get(numKey)
if not num1:
- cache.set(numKey,1,outTime)
- num1 = 1
-
+ cache.set(numKey,0,outTime)
+ num1 = 0
+
+ self.limit_expire_time = cache.get_expire_time(numKey)
+
#计数
if type == '+':
cache.inc(numKey,1)
@@ -278,27 +319,36 @@ class userlogin:
session['username'] = userInfo['username']
session['uid'] = userInfo['id']
session['login_user_agent'] = public.md5(request.headers.get('User-Agent',''))
- public.WriteLog('TYPE_LOGIN','LOGIN_SUCCESS',(userInfo['username'],public.GetClientIp()+ ":" + str(request.environ.get('REMOTE_PORT'))))
+ ids = public.write_log_gettext('Login','Login succeed, Username: {}, Login IP: {}',(userInfo['username'],public.GetClientIp()+ ":" + str(request.environ.get('REMOTE_PORT'))))
+ public.cache_set(public.GetClientIp()+ ":" + str(request.environ.get('REMOTE_PORT')),ids)
self.limit_address('-')
cache.delete('panelNum')
cache.delete('dologin')
session['session_timeout'] = time.time() + public.get_session_timeout()
+ if 'last_login_token' in session: del(session['last_login_token'])
self.set_request_token()
self.login_token()
login_type = 'data/app_login.pl'
if os.path.exists(login_type):
os.remove(login_type)
- return public.returnJson(True,'LOGIN_SUCCESS'),json_header
+ try:
+ default_pl = "{}/default.pl".format(public.get_panel_path())
+ public.writeFile(default_pl,"********")
+ public.run_thread(public.login_send_body, (
+ "Userinfo", userInfo['username'], public.GetClientIp(), str(request.environ.get('REMOTE_PORT'))))
+ except:
+ pass
+ return public.returnJson(True,'Login succeeded, loading...'),json_header
except Exception as ex:
stringEx = str(ex)
if stringEx.find('unsupported') != -1 or stringEx.find('-1') != -1:
public.ExecShell("rm -f /tmp/sess_*")
public.ExecShell("rm -f /www/wwwlogs/*log")
public.ServiceReload()
- return public.returnJson(False,'USER_INODE_ERR'),json_header
- public.WriteLog('TYPE_LOGIN','LOGIN_ERR_PASS',('****','******',public.GetClientIp()))
+ return public.returnJson(False,'Disk inode has been exhausted, the panel has attempted to release the inode. Please try again ...'),json_header
+ public.write_log_gettext('Login','Password is incorrect, Username:{}, Password:{}, Login IP:{}',('****','******',public.GetClientIp()))
num = self.limit_address('+')
- return public.returnJson(False,'LOGIN_USER_ERR',(str(num),)),json_header
+ return public.returnJson(False,'Invalid username or password. You have [{}] times left to try!',(str(num),)),json_header
# 检查是否需要进行二次验证
diff --git a/class/userlogin.py.baiduyun.uploading.cfg b/class/userlogin.py.baiduyun.uploading.cfg
deleted file mode 100644
index 195c60de..00000000
Binary files a/class/userlogin.py.baiduyun.uploading.cfg and /dev/null differ
diff --git a/class/wxapp.py b/class/wxapp.py
index fe68f043..11b0d16e 100644
--- a/class/wxapp.py
+++ b/class/wxapp.py
@@ -13,6 +13,7 @@ if not 'class/' in sys.path:
import public
import json
import time
+import uuid
from BTPanel import session,cache,request
class wxapp():
@@ -24,24 +25,28 @@ class wxapp():
def _check(self, get):
if get['fun'] in ['set_login', 'is_scan_ok', 'login_qrcode']:
return True
- return public.returnMsg(False, 'UNAUTHORIZED')
+ return public.returnMsg(False, 'Unauthorized')
# 验证是否扫码成功
def is_scan_ok(self, get):
if os.path.exists(self.app_path+"app_login_check.pl"):
- key, init_time = public.readFile(self.app_path+'app_login_check.pl').split(':')
- if time.time() - float(init_time) > 60:
- return public.returnMsg(False, 'QRCORE_EXPIRE')
- session_id = public.get_session_id()
- if cache.get(session_id) == 'True':
- return public.returnMsg(True, 'Scan QRCORE successfully')
+ try:
+ key, init_time, tid, status = public.readFile(self.app_path+'app_login_check.pl').split(':')
+ if time.time() - float(init_time) > 60:
+ return public.returnMsg(False, 'QR code expired')
+ session_id = public.get_session_id()
+ if cache.get(session_id) == public.md5(uuid.UUID(int=uuid.getnode()).hex):
+ return public.returnMsg(True, 'Scan QRCORE successfully')
+ except:
+ os.remove(self.app_path + "app_login_check.pl")
+ return public.returnMsg(False, '')
return public.returnMsg(False, '')
# 返回二维码地址
def login_qrcode(self, get):
- tid = public.GetRandomString(12)
+ tid = public.GetRandomString(32)
qrcode_str = 'https://app.bt.cn/app.html?&panel_url='+public.getPanelAddr()+'&v=' + public.GetRandomString(3)+'?login&tid=' + tid
- data = public.get_session_id() + ':' + str(time.time())
+ data = public.get_session_id() + ':' + str(time.time()) + ':' + tid + ':' + tid
public.writeFile(self.app_path + "app_login_check.pl", data)
cache.set(tid,public.get_session_id(),360)
cache.set(public.get_session_id(),tid,360)
@@ -50,15 +55,20 @@ class wxapp():
# 设置登录状态
def set_login(self, get):
session_id = public.get_session_id()
- if cache.get(session_id) == 'True':
- return self.check_app_login(get)
+ if cache.get(session_id):
+ if cache.get(session_id) == public.md5(uuid.UUID(int=uuid.getnode()).hex):
+ return self.check_app_login(get)
+ else:
+ cache.delete(cache.get(session_id))
+ cache.delete(session_id)
+ return public.returnMsg(False, 'Login failed 2')
return public.returnMsg(False, 'Login failed 1')
#验证APP是否登录成功
def check_app_login(self,get):
#判断是否存在绑定
btapp_info = json.loads(public.readFile('/www/server/panel/config/api.json'))
- if not btapp_info:return public.returnMsg(False,'Unbound')
+ if not btapp_info:return public.returnMsg(False,'Unbound!')
if not btapp_info['open']:return public.returnMsg(False,'API is not turned on')
if not 'apps' in btapp_info:return public.returnMsg(False,'Unbound phone')
if not btapp_info['apps']:return public.returnMsg(False,'Unbound phone')
@@ -67,19 +77,22 @@ class wxapp():
if not os.path.exists(self.app_path+'app_login_check.pl'):return public.returnMsg(False,'Waiting for APP scan code login 1')
data = public.readFile(self.app_path+'app_login_check.pl')
public.ExecShell('rm ' + self.app_path+"app_login_check.pl")
- secret_key, init_time = data.split(':')
+ secret_key, init_time, tid, status = data.split(':')
if len(session_id)!=64:return public.returnMsg(False,'Waiting for APP scan code login 2')
if len(secret_key)!=64:return public.returnMsg(False,'Waiting for APP scan code login 2')
+ if session_id != secret_key:
+ return public.returnMsg(False,'QR code expired')
if time.time() - float(init_time) > 60:
return public.returnMsg(False,'Waiting for APP scan code login')
- if session_id != secret_key:
- return public.returnMsg(False,'Waiting for APP scan code login')
+ import uuid
+ if status != uuid.UUID(int=uuid.getnode()).hex[-12:]: return public.returnMsg(False, '当前二维码失效222')
cache.delete(session_id)
+ cache.delete(tid)
userInfo = public.M('users').where("id=?",(1,)).field('id,username').find()
session['login'] = True
session['username'] = userInfo['username']
session['tmp_login'] = True
- public.WriteLog('TYPE_LOGIN','APP scan code login, account: {}, login IP: {}'.format(userInfo['username'],public.GetClientIp()+ ":" + str(request.environ.get('REMOTE_PORT'))))
+ public.WriteLog('Login','APP scan code login, account: {}, login IP: {}'.format(userInfo['username'],public.GetClientIp()+ ":" + str(request.environ.get('REMOTE_PORT'))))
cache.delete('panelNum')
cache.delete('dologin')
session['session_timeout'] = time.time() + public.get_session_timeout()
diff --git a/config/menu.json b/config/menu.json
index 8959d033..c5b85bf5 100644
--- a/config/menu.json
+++ b/config/menu.json
@@ -26,41 +26,55 @@
"class": "menu_data",
"id": "memuAdatabase",
"sort": 4
+ },
+ {
+ "title": "Docker",
+ "href": "/docker",
+ "class": "menu_docker",
+ "id": "memuDocker",
+ "sort": 5
},
{
"title": "Monitor",
"href": "/control",
"class": "menu_control",
"id": "memuAcontrol",
- "sort": 5
+ "sort": 6
},
{
"title": "Security",
"href": "/firewall",
"class": "menu_firewall",
"id": "memuAfirewall",
- "sort": 6
+ "sort": 7
+ },
+ {
+ "title": "WAF",
+ "href": "/btwaf/index",
+ "class": "menu_btwaf",
+ "id": "memu_btwaf",
+ "sort": 8
},
{
"title": "Files",
"href": "/files",
"class": "menu_folder",
"id": "memuAfiles",
- "sort": 7
+ "sort": 9
},
{
"title": "Terminal",
"href": "/xterm",
"class": "menu_xterm",
"id": "memuAxterm",
- "sort": 8
+ "sort": 10
},
{
"title": "Cron",
"href": "/crontab",
"class": "menu_day",
"id": "memuAcrontab",
- "sort": 9
+ "sort": 11
},
{
@@ -68,20 +82,20 @@
"href": "/soft",
"class": "menu_soft",
"id": "memuAsoft",
- "sort": 10
+ "sort": 12
},
{
"title": "Settings",
"href": "/config",
"class": "menu_set",
"id": "memuAconfig",
- "sort": 11
+ "sort": 13
},
{
"title": "Log out",
"href": "/login?dologin=True",
"class": "menu_exit",
"id": "dologin",
- "sort": 12
+ "sort": 14
}
]
\ No newline at end of file
diff --git a/data/default.sql b/data/default.sql
deleted file mode 100644
index 42de4208..00000000
--- a/data/default.sql
+++ /dev/null
@@ -1,131 +0,0 @@
-
-CREATE TABLE IF NOT EXISTS `backup` (
- `id` INTEGER PRIMARY KEY AUTOINCREMENT,
- `type` INTEGER,
- `name` TEXT,
- `pid` INTEGER,
- `filename` TEXT,
- `size` INTEGER,
- `addtime` TEXT
-);
-
-CREATE TABLE IF NOT EXISTS `binding` (
- `id` INTEGER PRIMARY KEY AUTOINCREMENT,
- `pid` INTEGER,
- `domain` TEXT,
- `path` TEXT,
- `port` INTEGER,
- `addtime` TEXT
-);
-
-
-CREATE TABLE IF NOT EXISTS `config` (
- `id` INTEGER PRIMARY KEY AUTOINCREMENT,
- `webserver` TEXT,
- `backup_path` TEXT,
- `sites_path` TEXT,
- `status` INTEGER,
- `mysql_root` TEXT
-);
-
-INSERT INTO `config` (`id`, `webserver`, `backup_path`, `sites_path`, `status`, `mysql_root`) VALUES
-(1, 'nginx', '/www/backup', '/www/wwwroot', 0, 'admin');
-
-
-CREATE TABLE IF NOT EXISTS `crontab` (
- `id` INTEGER PRIMARY KEY AUTOINCREMENT,
- `name` TEXT,
- `type` TEXT,
- `where1` TEXT,
- `where_hour` INTEGER,
- `where_minute` INTEGER,
- `echo` TEXT,
- `addtime` TEXT
-);
-
-CREATE TABLE IF NOT EXISTS `databases` (
- `id` INTEGER PRIMARY KEY AUTOINCREMENT,
- `pid` INTEGER,
- `name` TEXT,
- `username` TEXT,
- `password` TEXT,
- `accept` TEXT,
- `ps` TEXT,
- `addtime` TEXT
-);
-
-CREATE TABLE IF NOT EXISTS `firewall` (
- `id` INTEGER PRIMARY KEY AUTOINCREMENT,
- `port` TEXT,
- `ps` TEXT,
- `addtime` TEXT
-);
-
-INSERT INTO `firewall` (`id`, `port`, `ps`, `addtime`) VALUES
-(2, '80', '网站默认端口', '0000-00-00 00:00:00'),
-(3, '8888', 'WEB面板', '0000-00-00 00:00:00'),
-(4, '21', 'FTP服务', '0000-00-00 00:00:00'),
-(5, '22', 'SSH远程管理服务', '0000-00-00 00:00:00');
-
-
-CREATE TABLE IF NOT EXISTS `ftps` (
- `id` INTEGER PRIMARY KEY AUTOINCREMENT,
- `pid` INTEGER,
- `name` TEXT,
- `password` TEXT,
- `path` TEXT,
- `status` TEXT,
- `ps` TEXT,
- `addtime` TEXT
-);
-
-
-CREATE TABLE IF NOT EXISTS `logs` (
- `id` INTEGER PRIMARY KEY AUTOINCREMENT,
- `type` TEXT,
- `log` TEXT,
- `addtime` TEXT
-);
-
-CREATE TABLE IF NOT EXISTS `sites` (
- `id` INTEGER PRIMARY KEY AUTOINCREMENT,
- `name` TEXT,
- `path` TEXT,
- `status` TEXT,
- `index` TEXT,
- `ps` TEXT,
- `addtime` TEXT
-);
-
-CREATE TABLE IF NOT EXISTS `domain` (
- `id` INTEGER PRIMARY KEY AUTOINCREMENT,
- `pid` INTEGER,
- `name` TEXT,
- `port` INTEGER,
- `addtime` TEXT
-);
-
-CREATE TABLE IF NOT EXISTS `users` (
- `id` INTEGER PRIMARY KEY AUTOINCREMENT,
- `username` TEXT,
- `password` TEXT,
- `login_ip` TEXT,
- `login_time` TEXT,
- `phone` TEXT,
- `email` TEXT
-);
-
-INSERT INTO `users` (`id`, `username`, `password`, `login_ip`, `login_time`, `phone`, `email`) VALUES
-(1, 'admin', '21232f297a57a5a743894a0e4a801fc3', '192.168.0.10', '2016-12-10 15:12:56', 0, '287962566@qq.com');
-
-
-CREATE TABLE IF NOT EXISTS `tasks` (
- `id` INTEGER PRIMARY KEY AUTOINCREMENT,
- `name` TEXT,
- `type` TEXT,
- `status` TEXT,
- `addtime` TEXT,
- `start` INTEGER,
- `end` INTEGER,
- `execstr` TEXT
-);
diff --git a/data/libList.conf b/data/libList.conf
index 382f70ba..99226d05 100644
--- a/data/libList.conf
+++ b/data/libList.conf
@@ -1,5 +1,5 @@
[{
- "name":"FTP storage",
+ "name":"FTP Storage",
"type":"Cron job",
"ps":"Package the website or database back to the FTP storage space.",
"status":false,
diff --git a/data/node.json b/data/node.json
index 756e86f2..b4a598e0 100644
--- a/data/node.json
+++ b/data/node.json
@@ -1,30 +1,18 @@
[
{
- "protocol": "http://",
+ "protocol": "https://",
"address": "node.aapanel.com",
"port": "80",
"ping": 500
},
{
- "protocol": "http://",
- "address": "128.1.164.196",
- "port": "80",
- "ping": 500
- },
- {
- "protocol": "http://",
- "address": "45.76.53.20",
- "port": "80",
- "ping": 500
- },
- {
- "protocol": "http://",
+ "protocol": "https://",
"address": "dg2.bt.cn",
"port": "80",
"ping": 500
},
{
- "protocol": "http://",
+ "protocol": "https://",
"address": "dg1.bt.cn",
"port": "80",
"ping": 500
diff --git a/data/o.pl b/data/o.pl
deleted file mode 100644
index 8ba7e15f..00000000
--- a/data/o.pl
+++ /dev/null
@@ -1 +0,0 @@
-github
\ No newline at end of file
diff --git a/init.sh b/init.sh
index 23ab81df..64302a2a 100644
--- a/init.sh
+++ b/init.sh
@@ -65,7 +65,6 @@ panel_start()
get_panel_pids
if [ "$isStart" == '' ];then
rm -f $pidfile
- panel_port_check
echo -e "Starting Bt-Panel...\c"
nohup $panel_path/BT-Panel >> $log_file 2>&1 &
isStart=""
@@ -81,6 +80,7 @@ panel_start()
fi
done
if [ "$isStart" == '' ];then
+ panel_port_check
echo -e "\033[31mfailed\033[0m"
echo '------------------------------------------------------'
tail -n 20 $log_file
@@ -231,7 +231,6 @@ panel_reload()
kill -9 $p
done
rm -f $pidfile
- panel_port_check
echo -e "Reload Bt-Panel.\c";
nohup $panel_path/BT-Panel >> $log_file 2>&1 &
isStart=""
@@ -247,6 +246,7 @@ panel_reload()
fi
done
if [ "$isStart" == '' ];then
+ panel_port_check
echo -e "\033[31mfailed\033[0m"
echo '------------------------------------------------------'
tail -n 20 $log_file
@@ -331,7 +331,7 @@ case "$1" in
echo -e "password: $password"
echo -e "\033[33mWarning:\033[0m"
echo -e "\033[33mIf you cannot access the panel, \033[0m"
- echo -e "\033[33mrelease the following port (7800|888|80|443|20|21) in the security group\033[0m"
+ echo -e "\033[33mrelease the following port (8888|888|80|443|20|21) in the security group\033[0m"
echo -e "=================================================================="
;;
*)
diff --git a/install/install_soft.sh b/install/install_soft.sh
index e4c13ddc..1bb4dc98 100644
--- a/install/install_soft.sh
+++ b/install/install_soft.sh
@@ -1,24 +1,37 @@
#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
+
+#CN='125.88.182.172'
+#HK='download.bt.cn'
+#HK2='103.224.251.67'
+#US='128.1.164.196'
+#sleep 0.5;
+#CN_PING=`ping -c 1 -w 1 $CN|grep time=|awk '{print $7}'|sed "s/time=//"`
+#HK_PING=`ping -c 1 -w 1 $HK|grep time=|awk '{print $7}'|sed "s/time=//"`
+#HK2_PING=`ping -c 1 -w 1 $HK2|grep time=|awk '{print $7}'|sed "s/time=//"`
+#US_PING=`ping -c 1 -w 1 $US|grep time=|awk '{print $7}'|sed "s/time=//"`
+
+#echo "$HK_PING $HK" > ping.pl
+#echo "$HK2_PING $HK2" >> ping.pl
+#echo "$US_PING $US" >> ping.pl
+#echo "$CN_PING $CN" >> ping.pl
+nodeAddr=`sort -V ping.pl|sed -n '1p'|awk '{print $2}'`
+#if [ "$nodeAddr" == "" ];then
+# nodeAddr=$HK2
+#fi
+#serverUrl=http://$nodeAddr:5880/install
+serverUrl=https://node.aapanel.com/install
mtype=$1
actionType=$2
name=$3
version=$4
-. /www/server/panel/install/public.sh
-serverUrl=$NODE_URL/install
if [ ! -f 'lib.sh' ];then
- wget -O lib.sh $serverUrl/$mtype/lib.sh
+ wget -O lib.sh $serverUrl/$mtype/lib.sh --no-check-certificate
fi
-
-libNull=`cat lib.sh`
-if [ "$libNull" == '' ];then
- wget -O lib.sh $serverUrl/$mtype/lib.sh
-fi
-
-wget -O $name.sh $serverUrl/$mtype/$name.sh
+wget -O $name.sh $serverUrl/$mtype/$name.sh --no-check-certificate
if [ "$actionType" == 'install' ];then
- bash lib.sh
+ sh lib.sh
fi
-bash $name.sh $actionType $version
+sh $name.sh $actionType $version
diff --git a/install/public.sh b/install/public.sh
index 584e5f1f..146a9f22 100644
--- a/install/public.sh
+++ b/install/public.sh
@@ -1,48 +1,58 @@
#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
+pyenv_bin=/www/server/panel/pyenv/bin
+rep_path=${pyenv_bin}:$PATH
+if [ -d "$pyenv_bin" ];then
+ PATH=$rep_path
+fi
export PATH
export LANG=en_US.UTF-8
export LANGUAGE=en_US:en
get_node_url(){
- nodes=(http://183.235.223.101:3389 http://125.88.182.172:5880 http://128.1.164.196 http://103.224.251.67:5880 http://download.bt.cn);
- i=1;
- for node in ${nodes[@]};
- do
- start=`date +%s.%N`
- result=`curl -sS --connect-timeout 3 -m 60 $node/check.txt`
- if [ "$result" = 'True' ];then
- end=`date +%s.%N`
- start_s=`echo $start | cut -d '.' -f 1`
- start_ns=`echo $start | cut -d '.' -f 2`
- end_s=`echo $end | cut -d '.' -f 1`
- end_ns=`echo $end | cut -d '.' -f 2`
- time_micro=$(( (10#$end_s-10#$start_s)*1000000 + (10#$end_ns/1000 - 10#$start_ns/1000) ))
- time_ms=$(($time_micro/1000))
- values[$i]=$time_ms;
- urls[$time_ms]=$node
- i=$(($i+1))
- if [ $time_ms -lt 50 ];then
- break;
- fi
- fi
- done
- j=5000
- for n in ${values[@]};
- do
- if [ $j -gt $n ];then
- j=$n
- fi
- if [ $j -lt 50 ];then
- break;
- fi
- done
- if [ $j = 5000 ];then
- NODE_URL='http://download.bt.cn';
- else
- NODE_URL=${urls[$j]}
- fi
-
+ NODE_URL='https://node.aapanel.com';
+ #nodes=(http://dg2.bt.cn http://dg1.bt.cn http://36.133.1.8:5880 http://123.129.198.197 http://38.34.185.130 http://116.213.43.206:5880 http://128.1.164.196);
+ #tmp_file1=/dev/shm/net_test1.pl
+ #tmp_file2=/dev/shm/net_test2.pl
+ #[ -f "${tmp_file1}" ] && rm -f ${tmp_file1}
+ #[ -f "${tmp_file2}" ] && rm -f ${tmp_file2}
+ #touch $tmp_file1
+ #touch $tmp_file2
+ #for node in ${nodes[@]};
+ #do
+ # NODE_CHECK=$(curl --connect-timeout 3 -m 3 2>/dev/null -w "%{http_code} %{time_total}" ${node}/net_test|xargs)
+ # RES=$(echo ${NODE_CHECK}|awk '{print $1}')
+ # NODE_STATUS=$(echo ${NODE_CHECK}|awk '{print $2}')
+ # TIME_TOTAL=$(echo ${NODE_CHECK}|awk '{print $3 * 1000 - 500 }'|cut -d '.' -f 1)
+ # if [ "${NODE_STATUS}" == "200" ];then
+ # if [ $TIME_TOTAL -lt 100 ];then
+ # if [ $RES -ge 1500 ];then
+ # echo "$RES $node" >> $tmp_file1
+ # fi
+ # else
+ # if [ $RES -ge 1500 ];then
+ # echo "$TIME_TOTAL $node" >> $tmp_file2
+ # fi
+ # fi
+#
+# i=$(($i+1))
+# if [ $TIME_TOTAL -lt 100 ];then
+# if [ $RES -ge 3000 ];then
+# break;
+# fi
+# fi
+# fi
+# done
+
+# NODE_URL=$(cat $tmp_file1|sort -r -g -t " " -k 1|head -n 1|awk '{print $2}')
+# if [ -z "$NODE_URL" ];then
+# NODE_URL=$(cat $tmp_file2|sort -g -t " " -k 1|head -n 1|awk '{print $2}')
+# if [ -z "$NODE_URL" ];then
+# NODE_URL='http://download.bt.cn';
+# fi
+# fi
+# rm -f $tmp_file1
+# rm -f $tmp_file2
}
GetCpuStat(){
@@ -70,6 +80,51 @@ GetPackManager(){
PM="apt-get"
fi
}
+
+bt_check(){
+ p_path=/www/server/panel/class/panelPlugin.py
+ if [ -f $p_path ];then
+ is_ext=$(cat $p_path|grep btwaf)
+ if [ "$is_ext" != "" ];then
+ send_check
+ fi
+ fi
+
+ p_path=/www/server/panel/BTPanel/templates/default/index.html
+ if [ -f $p_path ];then
+ is_ext=$(cat $p_path|grep fbi)
+ if [ "$is_ext" != "" ];then
+ send_check
+ fi
+ fi
+}
+
+send_check(){
+ chattr -i /etc/init.d/bt
+ chmod +x /etc/init.d/bt
+ p_path2=/www/server/panel/class/common.py
+ p_version=$(cat $p_path2|grep "version = "|awk '{print $3}'|tr -cd [0-9.])
+ curl -sS --connect-timeout 3 -m 60 http://www.bt.cn/api/panel/notpro?version=$p_version
+ NODE_URL=""
+ exit 0;
+}
+GetSysInfo(){
+ if [ "${PM}" = "yum" ]; then
+ SYS_VERSION=$(cat /etc/redhat-release)
+ elif [ "${PM}" = "apt-get" ]; then
+ SYS_VERSION=$(cat /etc/issue)
+ fi
+ SYS_INFO=$(uname -msr)
+ SYS_BIT=$(getconf LONG_BIT)
+ MEM_TOTAL=$(free -m|grep Mem|awk '{print $2}')
+ CPU_INFO=$(getconf _NPROCESSORS_ONLN)
+ GCC_VER=$(gcc -v 2>&1|grep "gcc version"|awk '{print $3}')
+ CMAKE_VER=$(cmake --version|grep version|awk '{print $3}')
+
+ echo -e ${SYS_VERSION}
+ echo -e Bit:${SYS_BIT} Mem:${MEM_TOTAL}M Core:${CPU_INFO} gcc:${GCC_VER} cmake:${CMAKE_VER}
+ echo -e ${SYS_INFO}
+}
cpuInfo=$(getconf _NPROCESSORS_ONLN)
if [ "${cpuInfo}" -ge "4" ];then
GetCpuStat
@@ -77,7 +132,26 @@ else
cpuCore="1"
fi
GetPackManager
-if [ ! $NODE_URL ];then
- echo 'Selecting download node...';
- get_node_url
+
+if [ -d "/www/server/phpmyadmin/pma" ];then
+ rm -rf /www/server/phpmyadmin/pma
+ EN_CHECK=$(cat /www/server/panel/config/config.json |grep English)
+ if [ "${EN_CHECK}" ];then
+ curl http://download.bt.cn/install/update6_en.sh|bash
+ else
+ curl http://download.bt.cn/install/update6.sh|bash
+ fi
+ echo > /www/server/panel/data/restart.pl
fi
+
+if [ ! $NODE_URL ];then
+ EN_CHECK=$(cat /www/server/panel/config/config.json |grep English)
+ if [ -z "${EN_CHECK}" ];then
+ echo '正在选择下载节点...';
+ else
+ echo "selecting download node...";
+ fi
+ get_node_url
+ bt_check
+fi
+
diff --git a/requirements.txt b/requirements.txt
index dd833ab2..0302613c 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,19 +1,54 @@
-Flask>=1.0.2
-paramiko>=2.6.0
-flask-socketio>=4.1.0
-python-socketio>=4.2.0
-flask_sockets>=0.2.1
-Werkzeug>=0.15.1
-Pillow==5.4.1
-requests>=2.20
-cffi>=1.12.3
-psutil>=5.2.0
-chardet>=3.0.4
-Flask-Session>=0.3.1
-flask-sqlalchemy>=2.3.2
-gunicorn>=18.0
-gevent-websocket>=0.10.1
-pyopenssl>=19.0
-cryptography>=2.7
-six>=1.12.0
-pyOpenSSL>=21.0.0
\ No newline at end of file
+bcrypt==3.2.0
+certifi==2021.10.8
+cffi==1.15.0
+chardet==4.0.0
+charset-normalizer==2.0.12
+click==8.0.4
+configparser==5.2.0
+cos-python-sdk-v5==1.9.15
+crcmod==1.7
+cryptography==36.0.1
+Cython==0.29.28
+Deprecated==1.2.13
+dicttoxml==1.7.4
+dnspython==2.2.1
+docker==5.0.3
+Flask==2.0.3
+flask-sock==0.5.1
+h11==0.13.0
+idna==3.3
+IPy==1.1
+itsdangerous==2.1.1
+Jinja2==3.0.3
+MarkupSafe==2.1.0
+oauthlib==3.2.0
+packaging==21.3
+paramiko==2.10.2
+Pillow==9.0.1
+psutil==5.9.0
+pyasn1==0.4.8
+pycparser==2.21
+pycryptodome==3.14.1
+pyinotify==0.9.6
+PyMySQL==1.0.2
+PyNaCl==1.5.0
+pyOpenSSL==22.0.0
+pyparsing==3.0.7
+qiniu==7.5.0
+qrcode==7.3.1
+redis==4.1.4
+requests==2.27.1
+requests-file==1.5.1
+requests-oauthlib==1.3.1
+rsa==4.8
+simple-websocket==0.5.1
+six==1.16.0
+soupsieve==2.3.1
+upyun==2.5.5
+urllib3==1.26.8
+websocket-client==1.3.1
+Werkzeug==2.0.3
+wrapt==1.14.0
+wsproto==1.1.0
+gevent
+pyyaml
\ No newline at end of file
diff --git a/runconfig.py b/runconfig.py
index f46f1a8b..b5b1d579 100644
--- a/runconfig.py
+++ b/runconfig.py
@@ -5,7 +5,7 @@ f.close()
if bt_port:
bt_port.strip()
else:
- bt_port = 7800
+ bt_port = 8888
bind = []
if os.path.exists('data/ipv6.pl'):
bind.append('[0:0:0:0:0:0:0:0]:%s' % bt_port)
diff --git a/script/ftp.sh b/script/ftp.sh
index 30b0750d..34c9187e 100644
--- a/script/ftp.sh
+++ b/script/ftp.sh
@@ -5,16 +5,16 @@ install_tmp='/tmp/bt_install.pl'
download_Url=http://download.bt.cn
Install_Ftp()
{
- echo '正在安装脚本文件...' > $install_tmp
+ echo 'Installing script files...' > $install_tmp
wget -O /www/server/panel/script/backup_ftp.py $download_Url/install/lib/script/backup_ftp.py -T 5
- echo '安装完成' > $install_tmp
+ echo 'The installation is complete' > $install_tmp
}
Uninstall_Ftp()
{
rm -f /www/server/panel/script/backup_ftp.py
- echo '卸载完成' > $install_tmp
+ echo 'Uninstall complete' > $install_tmp
}
diff --git a/script/panel_ssl_task.py b/script/panel_ssl_task.py
index 1b379e1f..eeb58b35 100644
--- a/script/panel_ssl_task.py
+++ b/script/panel_ssl_task.py
@@ -7,7 +7,8 @@ from json import loads
lets_info = public.readFile("/www/server/panel/ssl/lets.info")
if lets_info:
lets_info = loads(lets_info)
- if setPanelLets.setPanelLets().check_cert_update(lets_info['domain']):
+ res = setPanelLets.setPanelLets().check_cert_update(lets_info['domain'])
+ if res['status'] and res['msg'] == '1':
strTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time())))
public.writeFile("/tmp/panelSSL.pl","{} Panel certificate updated successfully\n".format(strTime),"a+")
public.writeFile('/www/server/panel/data/reload.pl',"1")
\ No newline at end of file
diff --git a/script/rememory.sh b/script/rememory.sh
index 925e9dfc..2343eb22 100644
--- a/script/rememory.sh
+++ b/script/rememory.sh
@@ -6,7 +6,7 @@ export PATH
#+------------------------------------
endDate=`date +"%Y-%m-%d %H:%M:%S"`
-log="释放内存!"
+log="Free up memory!"
echo "★[$endDate] $log"
echo '----------------------------------------------------------------------------'
diff --git a/task.py b/task.py
index 20cc843e..bfe15893 100644
--- a/task.py
+++ b/task.py
@@ -15,6 +15,9 @@
import sys
import os
import logging
+import datetime
+import threading
+
from json import dumps, loads
from psutil import Process, pids, cpu_count, cpu_percent, net_io_counters, disk_io_counters, virtual_memory
os.environ['BT_TASK'] = '1'
@@ -98,7 +101,6 @@ def ExecShell(cmdstring, cwd=None, timeout=None, shell=True, symbol = '&>'):
try:
global logPath
import shlex
- import datetime
import subprocess
import time
sub = subprocess.Popen(cmdstring+ symbol +logPath, cwd=cwd,
@@ -425,12 +427,16 @@ def check502Task():
while True:
check502()
sess_expire()
+ mysql_quota_check()
time.sleep(600)
except Exception as ex:
logging.info(ex)
time.sleep(600)
check502Task()
+# MySQL配额检查
+def mysql_quota_check():
+ os.system(get_python_bin() +" /www/server/panel/script/mysql_quota.py > /dev/null")
# session过期处理
def sess_expire():
@@ -494,7 +500,7 @@ def panel_status():
def update_panel():
- os.system("curl http://download.bt.cn/install/update6_en.sh|bash &")
+ os.system("curl https://download.bt.cn/install/update6_en.sh|bash &")
def service_panel(action='reload'):
@@ -602,6 +608,23 @@ def check_files_panel():
public.writeFile(cf, i['body'])
os.system("bash {}/init.sh reload &".format(base_path))
+def func():
+ os.system(get_python_bin() + " {}/script/scan_log.py > /dev/null".format(base_path))
+ #如果需要循环调用,就要添加以下方法
+ timer = threading.Timer(86400, func)
+ timer.start()
+
+def scan_log_site():
+ now_time = datetime.datetime.now()
+ next_time = now_time + datetime.timedelta(days=+1)
+ next_year = next_time.date().year
+ next_month = next_time.date().month
+ next_day = next_time.date().day
+ next_time = datetime.datetime.strptime(str(next_year) + "-" + str(next_month) + "-" + str(next_day) + " 03:00:00",
+ "%Y-%m-%d %H:%M:%S")
+ timer_start_time = (next_time - now_time).total_seconds()
+ timer = threading.Timer(timer_start_time, func)
+ timer.start()
# 面板消息提醒
# def check_panel_msg():
@@ -634,7 +657,6 @@ def main():
datefmt='%Y-%m-%d %H:%M:%S', filename=task_log_file, filemode='a+')
logging.info('Service started')
- import threading
t = threading.Thread(target=systemTask)
t.setDaemon(True)
t.start()
@@ -672,6 +694,9 @@ def main():
# p = threading.Thread(target=check_panel_msg)
# p.setDaemon(True)
# p.start()
+ p = threading.Thread(target=scan_log_site)
+ p.setDaemon(True)
+ p.start()
startTask()
diff --git a/tools.py b/tools.py
index a7485d1f..032a1cbd 100644
--- a/tools.py
+++ b/tools.py
@@ -190,31 +190,64 @@ def CloseTask():
os.system('/etc/init.d/bt restart')
print(public.GetMsg("CLEAR_TASK",(int(ncount),)))
+def get_ipaddress():
+ '''
+ @name 获取本机IP地址
+ @author hwliang<2020-11-24>
+ @return list
+ '''
+ ipa_tmp = public.ExecShell("ip a |grep inet|grep -v inet6|grep -v 127.0.0.1|awk '{print $2}'|sed 's#/[0-9]*##g'")[0].strip()
+ iplist = ipa_tmp.split('\n')
+ return iplist
+def get_host_all():
+ local_ip = ['127.0.0.1','::1','localhost']
+ ip_list = []
+ bind_ip = get_ipaddress()
+
+ for ip in bind_ip:
+ ip = ip.strip()
+ if ip in local_ip: continue
+ if ip in ip_list: continue
+ ip_list.append(ip)
+ net_ip = public.httpGet("https://api.bt.cn/api/getipaddress")
+
+ if net_ip:
+ net_ip = net_ip.strip()
+ if not net_ip in ip_list:
+ ip_list.append(net_ip)
+ ip_list = [ip_list[-1],ip_list[0]]
+ return ip_list
+
#自签证书
def CreateSSL():
- import OpenSSL
- key = OpenSSL.crypto.PKey()
- key.generate_key( OpenSSL.crypto.TYPE_RSA, 2048 )
- cert = OpenSSL.crypto.X509()
- cert.set_serial_number(0)
- cert.get_subject().CN = public.GetLocalIp()
- cert.set_issuer(cert.get_subject())
- cert.gmtime_adj_notBefore( 0 )
- cert.gmtime_adj_notAfter( 10*365*24*60*60 )
- cert.set_pubkey( key )
- cert.sign( key, 'md5' )
- cert_ca = OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
- private_key = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, key)
- if isinstance(cert_ca,bytes):
- cert_ca = bytes.decode(cert_ca)
- private_key = bytes.decode(private_key)
- if len(cert_ca) > 100 and len(private_key) > 100:
- public.writeFile('ssl/certificate.pem',cert_ca)
- public.writeFile('ssl/privateKey.pem',private_key)
- public.writeFile('/www/server/panel/data/ssl.pl','')
- print('success')
- return
- print('error')
+ import base64
+ userInfo = public.get_user_info()
+ if not userInfo:
+ userInfo['uid'] = 0
+ userInfo['access_key'] = 'B' * 32
+ domains = get_host_all()
+ pdata = {
+ "action":"get_domain_cert",
+ "company":"aapanel.com",
+ "domain":','.join(domains),
+ "uid":userInfo['uid'],
+ "access_key":userInfo['access_key'],
+ "panel":1
+ }
+ cert_api = 'https://api.aapanel.com/aapanel_cert'
+ result = json.loads(public.httpPost(cert_api,{'data': json.dumps(pdata)}))
+ if 'status' in result:
+ if result['status']:
+ public.writeFile('ssl/certificate.pem',result['cert'])
+ public.writeFile('ssl/privateKey.pem',result['key'])
+ public.writeFile('ssl/baota_root.pfx',base64.b64decode(result['pfx']),'wb+')
+ public.writeFile('ssl/root_password.pl',result['password'])
+ public.writeFile('data/ssl.pl','True')
+ public.ExecShell("/etc/init.d/bt reload")
+ print('1')
+ return True
+ print('0')
+ return False
#创建文件
def CreateFiles(path,num):
@@ -386,7 +419,7 @@ def setup_idc():
filename = panelPath + '/data/o.pl'
if not os.path.exists(filename): return False
o = public.readFile(filename).strip()
- c_url = 'http://www.bt.cn/api/idc/get_idc_info_bycode?o=%s' % o
+ c_url = 'https://www.bt.cn/api/idc/get_idc_info_bycode?o=%s' % o
idcInfo = json.loads(public.httpGet(c_url))
if not idcInfo['status']: return False
pFile = panelPath + '/config/config.json'
@@ -417,7 +450,7 @@ def update_to6():
for pname in os.listdir('plugin/'):
if not os.path.isdir('plugin/' + pname): continue
if pname in exlodes: continue
- print("|-upgrading【%s】..." % pname),
+ print("|-upgrading [ %s ]..." % pname),
download_url = download_address + '/install/plugin/' + pname + '/install.sh'
to_file = '/tmp/%s.sh' % pname
public.downloadFile(download_url,to_file)
@@ -442,7 +475,7 @@ def bt_cli(u_input = 0):
print("(22) %s (15) %s"% ("Display panel error log",public.GetMsg("CLEAR_SYS_RUBBISH")))
print("(23) %s (16) %s"% ("Turn off BasicAuth authentication","Repair panel (check for errors and update panel files to the latest version)"))
print("(24) Turn off Google Authenticator (17) Set log cutting on/off compression")
- print("(25) Set whether to back up the panel automatically (18) Set whether to save a historical copy of the file")
+ print("(25) Set whether to save a historical copy of the file (18) Set whether to back up the panel automatically")
print("(26) Keep/Remove local backup when backing up to cloud storage")
print("(0) Cancel")
print(raw_tip)
@@ -609,7 +642,7 @@ def bt_cli(u_input = 0):
ClearSystem()
elif u_input == 16:
os.system("/www/server/panel/pyenv/bin/pip install cachelib")
- os.system("curl http://download.bt.cn/install/update6_en.sh|bash")
+ os.system("curl https://download.bt.cn/install/update6_en.sh|bash")
elif u_input == 17:
l_path = '/www/server/panel/data/log_not_gzip.pl'
if os.path.exists(l_path):
diff --git a/vhost/template/apache/node_http.conf b/vhost/template/apache/node_http.conf
index b29235ea..c26d3577 100644
--- a/vhost/template/apache/node_http.conf
+++ b/vhost/template/apache/node_http.conf
@@ -17,7 +17,6 @@
#SSL
ProxyPass /.well-known/ !
- Alias /.well-known/ /www/wwwroot/java_node_ssl/
# HTTP reverse proxy related settings begin >>>