1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
|
import json,os,sys,time,re,socket,importlib,binascii,base64,io _LAN_PUBLIC = None _LAN_LOG = None _LAN_TEMPLATE = None
if sys.version_info[0] == 2: reload(sys) sys.setdefaultencoding('utf8') else: from importlib import reload
def M(table): """ @name 访问面板数据库 @author hwliang<hwl@bt.cn> @table 被访问的表名(必需) @return db.Sql object
ps: 默认访问data/default.db """ import db with db.Sql() as sql: return sql.table(table)
def HttpGet(url,timeout = 6,headers = {}): """ @name 发送GET请求 @author hwliang<hwl@bt.cn> @url 被请求的URL地址(必需) @timeout 超时时间默认60秒 @return string """ if is_local(): return False home = 'www.bt.cn' host_home = 'data/home_host.pl' old_url = url if url.find(home) != -1: if os.path.exists(host_home): headers['host'] = home url = url.replace(home,readFile(host_home))
import http_requests res = http_requests.get(url,timeout=timeout,headers = headers) if res.status_code == 0: if old_url.find(home) != -1: return http_get_home(old_url,timeout,res.text) if headers: return False s_body = res.text return s_body s_body = res.text del res return s_body
def http_get_home(url,timeout,ex): """ @name Get方式使用优选节点访问官网 @author hwliang<hwl@bt.cn> @param url 当前官网URL地址 @param timeout 用于测试超时时间 @param ex 上一次错误的响应内容 @return string 响应内容
如果已经是优选节点,将直接返回ex """ try: home = 'www.bt.cn' if url.find(home) == -1: return ex hosts_file = "config/hosts.json" if not os.path.exists(hosts_file): return ex hosts = json.loads(readFile(hosts_file)) headers = {"host":home} for host in hosts: new_url = url.replace(home,host) res = HttpGet(new_url,timeout,headers) if res: writeFile("data/home_host.pl",host) set_home_host(host) return res return ex except: return ex
def set_home_host(host): """ @name 设置官网hosts @author hwliang<hwl@bt.cn> @param host IP地址 @return void """ ExecShell('sed -i "/www.bt.cn/d" /etc/hosts') ExecShell("echo '' >> /etc/hosts") ExecShell("echo '%s www.bt.cn' >> /etc/hosts" % host) ExecShell('sed -i "/^\s*$/d" /etc/hosts')
def httpGet(url,timeout=6): return HttpGet(url,timeout)
def HttpPost(url,data,timeout = 6,headers = {}): """ 发送POST请求 @url 被请求的URL地址(必需) @data POST参数,可以是字符串或字典(必需) @timeout 超时时间默认60秒 return string """ if is_local(): return False home = 'www.bt.cn' host_home = 'data/home_host.pl' old_url = url if url.find(home) != -1: if os.path.exists(host_home): headers['host'] = home url = url.replace(home,readFile(host_home))
import http_requests res = http_requests.post(url,data=data,timeout=timeout,headers = headers) if res.status_code == 0: if old_url.find(home) != -1: return http_post_home(old_url,data,timeout,res.text) if headers: return False s_body = res.text return s_body s_body = res.text del res return s_body
def http_post_home(url,data,timeout,ex): """ @name POST方式使用优选节点访问官网 @author hwliang<hwl@bt.cn> @param url(string) 当前官网URL地址 @param data(dict) POST数据 @param timeout(int) 用于测试超时时间 @param ex(string) 上一次错误的响应内容 @return string 响应内容
如果已经是优选节点,将直接返回ex """ try: home = 'www.bt.cn' if url.find(home) == -1: return ex hosts_file = "config/hosts.json" if not os.path.exists(hosts_file): return ex hosts = json.loads(readFile(hosts_file)) headers = {"host":home} for host in hosts: new_url = url.replace(home,host) res = HttpPost(new_url,data,timeout,headers) if res: writeFile("data/home_host.pl",host) set_home_host(host) return res return ex except: return ex
def httpPost(url,data,timeout=6): """ @name 发送POST请求 @author hwliang<hwl@bt.cn> @param url 被请求的URL地址(必需) @param data POST参数,可以是字符串或字典(必需) @param timeout 超时时间默认60秒 @return string """ return HttpPost(url,data,timeout)
def check_home(): return True
def Md5(strings): """ @name 生成MD5 @author hwliang<hwl@bt.cn> @param strings 要被处理的字符串 @return string(32) """ if type(strings) != bytes: strings = strings.encode() import hashlib m = hashlib.md5() m.update(strings) return m.hexdigest()
def md5(strings): return Md5(strings)
def FileMd5(filename): """ @name 生成文件的MD5 @author hwliang<hwl@bt.cn> @param filename 文件名 @return string(32) or False """ if not os.path.isfile(filename): return False import hashlib my_hash = hashlib.md5() f = open(filename,'rb') while True: b = f.read(8096) if not b : break my_hash.update(b) f.close() return my_hash.hexdigest()
def GetRandomString(length): """ @name 取随机字符串 @author hwliang<hwl@bt.cn> @param length 要获取的长度 @return string(length) """ from random import Random strings = '' chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789' chrlen = len(chars) - 1 random = Random() for i in range(length): strings += chars[random.randint(0, chrlen)] return strings
def ReturnJson(status,msg,args=()): """ @name 取通用Json返回 @author hwliang<hwl@bt.cn> @param status 返回状态 @param msg 返回消息 @return string(json) """ return GetJson(ReturnMsg(status,msg,args))
def returnJson(status,msg,args=()): """ @name 取通用Json返回 @author hwliang<hwl@bt.cn> @param status 返回状态 @param msg 返回消息 @return string(json) """ return ReturnJson(status,msg,args)
def ReturnMsg(status,msg,args = ()): """ @name 取通用dict返回 @author hwliang<hwl@bt.cn> @param status 返回状态 @param msg 返回消息 @return dict {"status":bool,"msg":string} """ log_message = json.loads(ReadFile('BTPanel/static/language/' + GetLanguage() + '/public.json')) keys = log_message.keys() if type(msg) == str: if msg in keys: msg = log_message[msg] for i in range(len(args)): rep = '{'+str(i+1)+'}' msg = msg.replace(rep,args[i]) return {'status':status,'msg':msg}
def returnMsg(status,msg,args = ()): """ @name 取通用dict返回 @author hwliang<hwl@bt.cn> @param status 返回状态 @param msg 返回消息 @return dict {"status":bool,"msg":string} """ return ReturnMsg(status,msg,args)
def GetFileMode(filename): """ @name 取文件权限字符串 @author hwliang<hwl@bt.cn> @param filename 文件全路径 @return string 如:644/777/755 """ stat = os.stat(filename) accept = str(oct(stat.st_mode)[-3:]) return accept
def get_mode_and_user(path): '''取文件或目录权限信息''' import pwd data = {} if not os.path.exists(path): return None stat = os.stat(path) data['mode'] = str(oct(stat.st_mode)[-3:]) try: data['user'] = pwd.getpwuid(stat.st_uid).pw_name except: data['user'] = str(stat.st_uid) return data
def GetJson(data): """ 将对象转换为JSON @data 被转换的对象(dict/list/str/int...) """ from json import dumps if data == bytes: data = data.decode('utf-8') try: return dumps(data,ensure_ascii=False) except: return dumps(returnMsg(False,"错误的响应: %s" % str(data)))
def getJson(data): return GetJson(data)
def ReadFile(filename,mode = 'r'): """ 读取文件内容 @filename 文件名 return string(bin) 若文件不存在,则返回None """ import os if not os.path.exists(filename): return False try: fp = open(filename, mode) f_body = fp.read() fp.close() except Exception as ex: if sys.version_info[0] != 2: try: fp = open(filename, mode,encoding="utf-8") f_body = fp.read() fp.close() except Exception as ex2: WriteLog('打开文件',str(ex2)) return False else: WriteLog('打开文件',str(ex)) return False return f_body
def readFile(filename,mode='r'): return ReadFile(filename,mode)
def WriteFile(filename,s_body,mode='w+'): """ 写入文件内容 @filename 文件名 @s_body 欲写入的内容 return bool 若文件不存在则尝试自动创建 """ try: fp = open(filename, mode) fp.write(s_body) fp.close() return True except: try: fp = open(filename, mode,encoding="utf-8") fp.write(s_body) fp.close() return True except: return False
def writeFile(filename,s_body,mode='w+'): return WriteFile(filename,s_body,mode)
def WriteLog(type,logMsg,args=(),not_web = False): import time,db,json username = 'system' uid = 1 tmp_msg = '' if not not_web: try: from BTPanel import session if 'username' in session: username = session['username'] uid = session['uid'] except: pass global _LAN_LOG if not _LAN_LOG: _LAN_LOG = json.loads(ReadFile('BTPanel/static/language/' + GetLanguage() + '/log.json')) keys = _LAN_LOG.keys() if logMsg in keys: logMsg = _LAN_LOG[logMsg] for i in range(len(args)): rep = '{'+str(i+1)+'}' logMsg = logMsg.replace(rep,args[i]) if type in keys: type = _LAN_LOG[type] sql = db.Sql() mDate = time.strftime('%Y-%m-%d %X',time.localtime()) data = (uid,username,type,logMsg + tmp_msg,mDate) result = sql.table('logs').add('uid,username,type,log,addtime',data)
def GetLanguage(): ''' 取语言 ''' return GetConfigValue("language")
def get_language(): return GetLanguage()
def GetConfigValue(key): ''' 取配置值 ''' config = GetConfig() if not key in config.keys(): return None return config[key]
def SetConfigValue(key,value): config = GetConfig() config[key] = value WriteConfig(config)
def GetConfig(): ''' 取所有配置项 ''' path = "config/config.json" if not os.path.exists(path): return {} f_body = ReadFile(path) if not f_body: return {} return json.loads(f_body)
def WriteConfig(config): path = "config/config.json" WriteFile(path,json.dumps(config))
def GetLan(key): """ 取提示消息 """ global _LAN_TEMPLATE if not _LAN_TEMPLATE: _LAN_TEMPLATE = json.loads(ReadFile('BTPanel/static/language/' + GetLanguage() + '/template.json')) keys = _LAN_TEMPLATE.keys() msg = None if key in keys: msg = _LAN_TEMPLATE[key] return msg def getLan(key): return GetLan(key)
def GetMsg(key,args = ()): try: global _LAN_PUBLIC if not _LAN_PUBLIC: _LAN_PUBLIC = json.loads(ReadFile('BTPanel/static/language/' + GetLanguage() + '/public.json')) keys = _LAN_PUBLIC.keys() msg = None if key in keys: msg = _LAN_PUBLIC[key] for i in range(len(args)): rep = '{'+str(i+1)+'}' msg = msg.replace(rep,args[i]) return msg except: return key def getMsg(key,args = ()): return GetMsg(key,args)
def GetWebServer(): if os.path.exists('/www/server/apache/bin/apachectl'): webserver = 'apache' elif os.path.exists('/usr/local/lsws/bin/lswsctrl'): webserver = 'openlitespeed' else: webserver = 'nginx' return webserver
def get_webserver(): return GetWebServer()
def ServiceReload(): if os.path.exists('/www/server/nginx/sbin/nginx'): result = ExecShell('/etc/init.d/nginx reload') if result[1].find('nginx.pid') != -1: ExecShell('pkill -9 nginx && sleep 1') ExecShell('/etc/init.d/nginx start') elif os.path.exists('/www/server/apache/bin/apachectl'): result = ExecShell('/etc/init.d/httpd reload') else: result = ExecShell('rm -f /tmp/lshttpd/*.sock* && /usr/local/lsws/bin/lswsctrl restart') return result def serviceReload(): return ServiceReload()
def ExecShell(cmdstring, cwd=None, timeout=None, shell=True): a = '' e = '' import subprocess,tempfile
try: rx = md5(cmdstring) succ_f = tempfile.SpooledTemporaryFile(max_size=4096,mode='wb+',suffix='_succ',prefix='btex_' + rx ,dir='/dev/shm') err_f = tempfile.SpooledTemporaryFile(max_size=4096,mode='wb+',suffix='_err',prefix='btex_' + rx ,dir='/dev/shm') sub = subprocess.Popen(cmdstring, close_fds=True, shell=shell,bufsize=128,stdout=succ_f,stderr=err_f) sub.wait() err_f.seek(0) succ_f.seek(0) a = succ_f.read() e = err_f.read() if not err_f.closed: err_f.close() if not succ_f.closed: succ_f.close() except: print(get_error_info()) try: if type(a) == bytes: a = a.decode('utf-8') if type(e) == bytes: e = e.decode('utf-8') except:pass
return a,e
def GetLocalIp(): try: filename = 'data/iplist.txt' ipaddress = readFile(filename) if not ipaddress: url = 'http://pv.sohu.com/cityjson?ie=utf-8' m_str = HttpGet(url) ipaddress = re.search(r'\d+.\d+.\d+.\d+',m_str).group(0) WriteFile(filename,ipaddress) c_ip = check_ip(ipaddress) if not c_ip: return GetHost() return ipaddress except: try: url = GetConfigValue('home') + '/Api/getIpAddress' return HttpGet(url) except: return GetHost()
def is_ipv4(ip): try: socket.inet_pton(socket.AF_INET, ip) except AttributeError: try: socket.inet_aton(ip) except socket.error: return False return ip.count('.') == 3 except socket.error: return False return True
def is_ipv6(ip): try: socket.inet_pton(socket.AF_INET6, ip) except socket.error: return False return True
def check_ip(ip): return is_ipv4(ip) or is_ipv6(ip)
def GetHost(port = False): from flask import request host_tmp = request.headers.get('host') if not host_tmp: if request.url_root: tmp = re.findall(r"(https|http)://([\w:\.-]+)",request.url_root) if tmp: host_tmp = tmp[0][1] if not host_tmp: host_tmp = GetLocalIp() + ':' + readFile('data/port.pl').strip() try: if host_tmp.find(':') == -1: host_tmp += ':80' except: host_tmp = "127.0.0.1:8888" h = host_tmp.split(':') if port: return h[-1] return ':'.join(h[0:-1])
def GetClientIp(): from flask import request return request.remote_addr.replace('::ffff:','')
def phpReload(version): import os if os.path.exists('/www/server/php/' + version + '/libphp5.so'): ExecShell('/etc/init.d/httpd reload') else: ExecShell('/etc/init.d/php-fpm-'+version+' reload')
def get_timeout(url,timeout=3): try: start = time.time() result = int(httpGet(url,timeout)) return result,int((time.time() - start) * 1000 - 500) except: return 0,False
def get_url(timeout = 0.5): import json try: nodeFile = 'data/node.json' node_list = json.loads(readFile(nodeFile)) mnode1 = [] mnode2 = [] mnode3 = [] new_node_list = {} for node in node_list: node['net'],node['ping'] = get_timeout(node['protocol'] + node['address'] + ':' + node['port'] + '/net_test',1) new_node_list[node['address']] = node['ping'] if not node['ping']: continue if node['ping'] < 100: if node['net'] > 1500: mnode1.append(node) elif node['net'] > 1000: mnode3.append(node) else: if node['net'] > 1000: mnode2.append(node) if node['ping'] < 100: if node['net'] > 3000: break if mnode1: mnode = sorted(mnode1,key= lambda x:x['net'],reverse=True) elif mnode3: mnode = sorted(mnode3,key= lambda x:x['net'],reverse=True) else: mnode = sorted(mnode2,key= lambda x:x['ping'],reverse=False)
if not mnode: return 'http://download.bt.cn'
new_node_keys = new_node_list.keys() for i in range(len(node_list)): if node_list[i]['address'] in new_node_keys: node_list[i]['ping'] = new_node_list[node_list[i]['address']] else: node_list[i]['ping'] = 500
new_node_list = sorted(node_list,key=lambda x: x['ping'],reverse=False) writeFile(nodeFile,json.dumps(new_node_list)) return mnode[0]['protocol'] + mnode[0]['address'] + ':' + mnode[0]['port'] except: return 'http://download.bt.cn'
def checkInput(data): if not data: return data if type(data) != str: return data checkList = [ {'d':'<','r':'<'}, {'d':'>','r':'>'}, {'d':'\'','r':'‘'}, {'d':'"','r':'“'}, {'d':'&','r':'&'}, {'d':'#','r':'#'}, {'d':'<','r':'<'} ] for v in checkList: data = data.replace(v['d'],v['r']) return data
def GetNumLines(path,num,p=1): pyVersion = sys.version_info[0] max_len = 1024*128 try: import cgi if not os.path.exists(path): return "" start_line = (p - 1) * num count = start_line + num fp = open(path,'r') buf = "" fp.seek(-1, 2) if fp.read(1) == "\n": fp.seek(-1, 2) data = [] total_len = 0 b = True n = 0 for i in range(count): while True: newline_pos = str.rfind(str(buf), "\n") pos = fp.tell() if newline_pos != -1: if n >= start_line: line = buf[newline_pos + 1:] line_len = len(line) total_len += line_len sp_len = total_len - max_len if sp_len > 0: line = line[sp_len:] try: data.insert(0,cgi.escape(line)) except: pass buf = buf[:newline_pos] n += 1 break else: if pos == 0: b = False break to_read = min(4096, pos) fp.seek(-to_read, 1) t_buf = fp.read(to_read) if pyVersion == 3: try: if type(t_buf) == bytes: t_buf = t_buf.decode('utf-8') except:t_buf = str(t_buf) buf = t_buf + buf fp.seek(-to_read, 1) if pos - to_read == 0: buf = "\n" + buf if total_len >= max_len: break if not b: break fp.close() result = "\n".join(data) if not result: raise Exception('null') except: result = ExecShell("tail -n {} {}".format(num,path))[0] if len(result) > max_len: result = result[-max_len:]
try: try: result = json.dumps(result) return json.loads(result).strip() except: if pyVersion == 2: result = result.decode('utf8',errors='ignore') else: result = result.encode('utf-8',errors='ignore').decode("utf-8",errors="ignore") return result.strip() except: return ""
def CheckCert(certPath = 'ssl/certificate.pem'): openssl = '/usr/local/openssl/bin/openssl' if not os.path.exists(openssl): openssl = 'openssl' certPem = readFile(certPath) s = "\n-----BEGIN CERTIFICATE-----" tmp = certPem.strip().split(s) for tmp1 in tmp: if tmp1.find('-----BEGIN CERTIFICATE-----') == -1: tmp1 = s + tmp1 writeFile(certPath,tmp1) result = ExecShell(openssl + " x509 -in "+certPath+" -noout -subject") if result[1].find('-bash:') != -1: return True if len(result[1]) > 2: return False if result[0].find('error:') != -1: return False return True
def getPanelAddr(): from flask import request protocol = 'https://' if os.path.exists("data/ssl.pl") else 'http://' return protocol + request.headers.get('host')
def to_size(size): if not size: return '0.00 b' size = float(size) d = ('b','KB','MB','GB','TB') s = d[0] for b in d: if size < 1024: return ("%.2f" % size) + ' ' + b size = size / 1024 s = b return ("%.2f" % size) + ' ' + b
def checkCode(code,outime = 120): from BTPanel import session,cache try: codeStr = cache.get('codeStr') cache.delete('codeStr') if not codeStr: session['login_error'] = GetMsg('CODE_TIMEOUT') return False
if md5(code.lower()) != codeStr: session['login_error'] = GetMsg('CODE_ERR') return False return True except: session['login_error'] = GetMsg('CODE_NOT_EXISTS') return False
def writeSpeed(title,used,total,speed = 0): import json if not title: data = {'title':None,'progress':0,'total':0,'used':0,'speed':0} else: progress = int((100.0 * used / total)) data = {'title':title,'progress':progress,'total':total,'used':used,'speed':speed} writeFile('/tmp/panelSpeed.pl',json.dumps(data)) return True
def getSpeed(): import json; data = readFile('/tmp/panelSpeed.pl') if not data: data = json.dumps({'title':None,'progress':0,'total':0,'used':0,'speed':0}) writeFile('/tmp/panelSpeed.pl',data) return json.loads(data)
def downloadFile(url,filename): try: if sys.version_info[0] == 2: import urllib urllib.urlretrieve(url,filename=filename ,reporthook= downloadHook) else: import urllib.request urllib.request.urlretrieve(url,filename=filename ,reporthook= downloadHook) except: return False
def downloadHook(count, blockSize, totalSize): speed = {'total':totalSize,'block':blockSize,'count':count}
def get_error_info(): import traceback errorMsg = traceback.format_exc() return errorMsg
def submit_error(err_msg = None): try: if os.path.exists('/www/server/panel/not_submit_errinfo.pl'): return False from BTPanel import request import system if not err_msg: err_msg = get_error_info() pdata = {} pdata['err_info'] = err_msg pdata['path_full'] = request.full_path pdata['version'] = 'Linux-Panel-%s' % version() pdata['os'] = system.system().GetSystemVersion() pdata['py_version'] = sys.version pdata['install_date'] = int(os.stat('/www/server/panel/class/common.py').st_mtime) httpPost("http://www.bt.cn/api/panel/s_error",pdata,timeout=3) except: pass
def inArray(arrays,searchStr): for key in arrays: if key == searchStr: return True
return False
def format_date(format="%Y-%m-%d %H:%M:%S",times = None): if not times: times = int(time.time()) time_local = time.localtime(times) return time.strftime(format, time_local)
def checkWebConfig(): f1 = '/www/server/panel/vhost/' f2 = '/www/server/panel/plugin/' if not os.path.exists(f2 + 'btwaf'): f3 = f1 + 'nginx/btwaf.conf' if os.path.exists(f3): os.remove(f3)
if not os.path.exists(f2 + 'total'): f3 = f1 + 'apache/total.conf' if os.path.exists(f3): os.remove(f3) f3 = f1 + 'nginx/total.conf' if os.path.exists(f3): os.remove(f3) else: if os.path.exists('/www/server/apache/modules/mod_lua.so'): writeFile(f1 + 'apache/btwaf.conf','LoadModule lua_module modules/mod_lua.so') writeFile(f1 + 'apache/total.conf','LuaHookLog /www/server/total/httpd_log.lua run_logs') else: f3 = f1 + 'apache/total.conf' if os.path.exists(f3): os.remove(f3)
if get_webserver() == 'nginx': result = ExecShell("ulimit -n 8192 ; /www/server/nginx/sbin/nginx -t -c /www/server/nginx/conf/nginx.conf") searchStr = 'successful' elif get_webserver() == 'apache': result = ExecShell("ulimit -n 8192 ; /www/server/apache/bin/apachectl -t") searchStr = 'Syntax OK' else: result = ["1","1"] searchStr = "1" if result[1].find(searchStr) == -1: WriteLog("TYPE_SOFT", 'CONF_CHECK_ERR',(result[1],)) return result[1] return True
def checkIp(ip): p = re.compile(r'^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$') if p.match(ip): return True else: return False
def checkPort(port): if not re.match("^\d+$",port): return False ports = ['21','25','443','8080','888','8888','8443'] if port in ports: return False intport = int(port) if intport < 1 or intport > 65535: return False return True
def getStrBetween(startStr,endStr,srcStr): start = srcStr.find(startStr) if start == -1: return None end = srcStr.find(endStr) if end == -1: return None return srcStr[start+1:end]
def getCpuType(): cpuinfo = open('/proc/cpuinfo','r').read() rep = "model\s+name\s+:\s+(.+)" tmp = re.search(rep,cpuinfo,re.I) cpuType = '' if tmp: cpuType = tmp.groups()[0] else: cpuinfo = ExecShell('LANG="en_US.UTF-8" && lscpu')[0] rep = "Model\s+name:\s+(.+)" tmp = re.search(rep,cpuinfo,re.I) if tmp: cpuType = tmp.groups()[0] return cpuType
def IsRestart(): num = M('tasks').where('status!=?',('1',)).count() if num > 0: return False return True
def hasPwd(password): import crypt; return crypt.crypt(password,password)
def getDate(format='%Y-%m-%d %X'): return time.strftime(format,time.localtime())
def CheckMyCnf(): import os; confFile = '/etc/my.cnf' if os.path.exists(confFile): conf = readFile(confFile) if conf.find('[mysqld]') != -1: return True versionFile = '/www/server/mysql/version.pl' if not os.path.exists(versionFile): return False
versions = ['5.1','5.5','5.6','5.7','8.0','AliSQL'] version = readFile(versionFile) for key in versions: if key in version: version = key break
shellStr = ''' #!/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=$HK fi
Download_Url=http://$nodeAddr:5880
MySQL_Opt() { MemTotal=`free -m | grep Mem | awk '{print $2}'` if [[ ${MemTotal} -gt 1024 && ${MemTotal} -lt 2048 ]]; then sed -i "s#^key_buffer_size.*#key_buffer_size = 32M#" /etc/my.cnf sed -i "s#^table_open_cache.*#table_open_cache = 128#" /etc/my.cnf sed -i "s#^sort_buffer_size.*#sort_buffer_size = 768K#" /etc/my.cnf sed -i "s#^read_buffer_size.*#read_buffer_size = 768K#" /etc/my.cnf sed -i "s#^myisam_sort_buffer_size.*#myisam_sort_buffer_size = 8M#" /etc/my.cnf sed -i "s#^thread_cache_size.*#thread_cache_size = 16#" /etc/my.cnf sed -i "s#^query_cache_size.*#query_cache_size = 16M#" /etc/my.cnf sed -i "s#^tmp_table_size.*#tmp_table_size = 32M#" /etc/my.cnf sed -i "s#^innodb_buffer_pool_size.*#innodb_buffer_pool_size = 128M#" /etc/my.cnf sed -i "s#^innodb_log_file_size.*#innodb_log_file_size = 32M#" /etc/my.cnf elif [[ ${MemTotal} -ge 2048 && ${MemTotal} -lt 4096 ]]; then sed -i "s#^key_buffer_size.*#key_buffer_size = 64M#" /etc/my.cnf sed -i "s#^table_open_cache.*#table_open_cache = 256#" /etc/my.cnf sed -i "s#^sort_buffer_size.*#sort_buffer_size = 1M#" /etc/my.cnf sed -i "s#^read_buffer_size.*#read_buffer_size = 1M#" /etc/my.cnf sed -i "s#^myisam_sort_buffer_size.*#myisam_sort_buffer_size = 16M#" /etc/my.cnf sed -i "s#^thread_cache_size.*#thread_cache_size = 32#" /etc/my.cnf sed -i "s#^query_cache_size.*#query_cache_size = 32M#" /etc/my.cnf sed -i "s#^tmp_table_size.*#tmp_table_size = 64M#" /etc/my.cnf sed -i "s#^innodb_buffer_pool_size.*#innodb_buffer_pool_size = 256M#" /etc/my.cnf sed -i "s#^innodb_log_file_size.*#innodb_log_file_size = 64M#" /etc/my.cnf elif [[ ${MemTotal} -ge 4096 && ${MemTotal} -lt 8192 ]]; then sed -i "s#^key_buffer_size.*#key_buffer_size = 128M#" /etc/my.cnf sed -i "s#^table_open_cache.*#table_open_cache = 512#" /etc/my.cnf sed -i "s#^sort_buffer_size.*#sort_buffer_size = 2M#" /etc/my.cnf sed -i "s#^read_buffer_size.*#read_buffer_size = 2M#" /etc/my.cnf sed -i "s#^myisam_sort_buffer_size.*#myisam_sort_buffer_size = 32M#" /etc/my.cnf sed -i "s#^thread_cache_size.*#thread_cache_size = 64#" /etc/my.cnf sed -i "s#^query_cache_size.*#query_cache_size = 64M#" /etc/my.cnf sed -i "s#^tmp_table_size.*#tmp_table_size = 64M#" /etc/my.cnf sed -i "s#^innodb_buffer_pool_size.*#innodb_buffer_pool_size = 512M#" /etc/my.cnf sed -i "s#^innodb_log_file_size.*#innodb_log_file_size = 128M#" /etc/my.cnf elif [[ ${MemTotal} -ge 8192 && ${MemTotal} -lt 16384 ]]; then sed -i "s#^key_buffer_size.*#key_buffer_size = 256M#" /etc/my.cnf sed -i "s#^table_open_cache.*#table_open_cache = 1024#" /etc/my.cnf sed -i "s#^sort_buffer_size.*#sort_buffer_size = 4M#" /etc/my.cnf sed -i "s#^read_buffer_size.*#read_buffer_size = 4M#" /etc/my.cnf sed -i "s#^myisam_sort_buffer_size.*#myisam_sort_buffer_size = 64M#" /etc/my.cnf sed -i "s#^thread_cache_size.*#thread_cache_size = 128#" /etc/my.cnf sed -i "s#^query_cache_size.*#query_cache_size = 128M#" /etc/my.cnf sed -i "s#^tmp_table_size.*#tmp_table_size = 128M#" /etc/my.cnf sed -i "s#^innodb_buffer_pool_size.*#innodb_buffer_pool_size = 1024M#" /etc/my.cnf sed -i "s#^innodb_log_file_size.*#innodb_log_file_size = 256M#" /etc/my.cnf elif [[ ${MemTotal} -ge 16384 && ${MemTotal} -lt 32768 ]]; then sed -i "s#^key_buffer_size.*#key_buffer_size = 512M#" /etc/my.cnf sed -i "s#^table_open_cache.*#table_open_cache = 2048#" /etc/my.cnf sed -i "s#^sort_buffer_size.*#sort_buffer_size = 8M#" /etc/my.cnf sed -i "s#^read_buffer_size.*#read_buffer_size = 8M#" /etc/my.cnf sed -i "s#^myisam_sort_buffer_size.*#myisam_sort_buffer_size = 128M#" /etc/my.cnf sed -i "s#^thread_cache_size.*#thread_cache_size = 256#" /etc/my.cnf sed -i "s#^query_cache_size.*#query_cache_size = 256M#" /etc/my.cnf sed -i "s#^tmp_table_size.*#tmp_table_size = 256M#" /etc/my.cnf sed -i "s#^innodb_buffer_pool_size.*#innodb_buffer_pool_size = 2048M#" /etc/my.cnf sed -i "s#^innodb_log_file_size.*#innodb_log_file_size = 512M#" /etc/my.cnf elif [[ ${MemTotal} -ge 32768 ]]; then sed -i "s#^key_buffer_size.*#key_buffer_size = 1024M#" /etc/my.cnf sed -i "s#^table_open_cache.*#table_open_cache = 4096#" /etc/my.cnf sed -i "s#^sort_buffer_size.*#sort_buffer_size = 16M#" /etc/my.cnf sed -i "s#^read_buffer_size.*#read_buffer_size = 16M#" /etc/my.cnf sed -i "s#^myisam_sort_buffer_size.*#myisam_sort_buffer_size = 256M#" /etc/my.cnf sed -i "s#^thread_cache_size.*#thread_cache_size = 512#" /etc/my.cnf sed -i "s#^query_cache_size.*#query_cache_size = 512M#" /etc/my.cnf sed -i "s#^tmp_table_size.*#tmp_table_size = 512M#" /etc/my.cnf sed -i "s#^innodb_buffer_pool_size.*#innodb_buffer_pool_size = 4096M#" /etc/my.cnf sed -i "s#^innodb_log_file_size.*#innodb_log_file_size = 1024M#" /etc/my.cnf fi }
wget -O /etc/my.cnf $Download_Url/install/conf/mysql-%s.conf -T 5 chmod 644 /etc/my.cnf MySQL_Opt ''' % (version,) ExecShell(shellStr) if os.path.exists('data/datadir.pl'): newPath = readFile('data/datadir.pl') if os.path.exists(newPath): mycnf = readFile('/etc/my.cnf') mycnf = mycnf.replace('/www/server/data',newPath) writeFile('/etc/my.cnf',mycnf) WriteLog('TYPE_SOFE', 'MYSQL_CHECK_ERR') return True
def GetSSHPort(): try: file = '/etc/ssh/sshd_config' conf = ReadFile(file) rep = "#*Port\s+([0-9]+)\s*\n" port = re.search(rep,conf).groups(0)[0] return int(port) except: return 22
def GetSSHStatus(): if os.path.exists('/usr/bin/apt-get'): status = ExecShell("service ssh status | grep -P '(dead|stop)'") else: import system panelsys = system.system() version = panelsys.GetSystemVersion() if version.find(' 7.') != -1: status = ExecShell("systemctl status sshd.service | grep 'dead'") else: status = ExecShell("/etc/init.d/sshd status | grep -e 'stopped' -e '已停'") if len(status[0]) > 3: status = False else: status = True return status
def CheckPort(port,other=None): if type(port) == str: port = int(port) if port < 1 or port > 65535: return False if other: checks = [22,20,21,8888,3306,11211,888,25] if port in checks: return False return True
def GetToken(): try: from json import loads tokenFile = 'data/token.json' if not os.path.exists(tokenFile): return False token = loads(readFile(tokenFile)) return token except: return False
def to_btint(string): m_list = [] for s in string: m_list.append(ord(s)) return m_list
def load_module(pluginCode): from imp import new_module from BTPanel import cache p_tk = 'data/%s' % md5(pluginCode + get_uuid()) pluginInfo = None if cache: pluginInfo = cache.get(pluginCode+'code') if not pluginInfo: import panelAuth pdata = panelAuth.panelAuth().create_serverid(None) pdata['pid'] = pluginCode url = GetConfigValue('home') + '/api/panel/get_py_module' pluginTmp = httpPost(url,pdata) try: pluginInfo = json.loads(pluginTmp) except: if not os.path.exists(p_tk): return False pluginInfo = json.loads(ReadFile(p_tk)) if pluginInfo['status'] == False: return False WriteFile(p_tk,json.dumps(pluginInfo)) os.chmod(p_tk,384) if cache: cache.set(pluginCode+'code',pluginInfo,1800)
mod = sys.modules.setdefault(pluginCode, new_module(pluginCode)) code = compile(pluginInfo['msg'].encode('utf-8'),pluginCode, 'exec') mod.__file__ = pluginCode mod.__package__ = '' exec(code, mod.__dict__) return mod
def auth_decode(data): token = GetToken() if not token: return returnMsg(False,'REQUEST_ERR')
if token['access_key'] != data['btauth_key']: return returnMsg(False,'REQUEST_ERR')
import binascii,hashlib,urllib,hmac,json tdata = binascii.unhexlify(data['data'])
signature = binascii.hexlify(hmac.new(token['secret_key'], tdata, digestmod=hashlib.sha256).digest()) if signature != data['signature']: return returnMsg(False,'REQUEST_ERR')
return json.loads(urllib.unquote(tdata))
def auth_encode(data): token = GetToken() pdata = {}
if not token: return returnMsg(False,'REQUEST_ERR')
import binascii,hashlib,urllib,hmac,json tdata = urllib.quote(json.dumps(data)) pdata['signature'] = binascii.hexlify(hmac.new(token['secret_key'], tdata, digestmod=hashlib.sha256).digest())
pdata['btauth_key'] = token['access_key'] pdata['data'] = binascii.hexlify(tdata) pdata['timestamp'] = time.time()
return pdata
def checkToken(get): tempFile = 'data/tempToken.json' if not os.path.exists(tempFile): return False import json,time tempToken = json.loads(readFile(tempFile)) if time.time() > tempToken['timeout']: return False if get.token != tempToken['token']: return False return True
def get_uuid(): import uuid return uuid.UUID(int=uuid.getnode()).hex[-12:]
def process_exists(pname,exe = None,cmdline = None): try: import psutil pids = psutil.pids() for pid in pids: try: p = psutil.Process(pid) if p.name() == pname: if not exe and not cmdline: return True else: if exe: if p.exe() == exe: return True if cmdline: if cmdline in p.cmdline(): return True except:pass return False except: return True
def restart_panel(): import system return system.system().ReWeb(None)
def get_mac_address(): import uuid mac=uuid.UUID(int = uuid.getnode()).hex[-12:] return ":".join([mac[e:e+2] for e in range(0,11,2)])
def to_string(lites): if type(lites) != list: lites = [lites] m_str = '' for mu in lites: if sys.version_info[0] == 2: m_str += unichr(mu).encode('utf-8') else: m_str += chr(mu) return m_str
def to_ord(string): o = [] for s in string: o.append(ord(s)) return o
def xssencode(text): import cgi list=['`','~','&','#','/','*','$','@','<','>','\"','\'',';','%',',','.','\\u'] ret=[] for i in text: if i in list: i='' ret.append(i) str_convert = ''.join(ret) text2=cgi.escape(str_convert, quote=True) return text2
def cache_get(key): from BTPanel import cache return cache.get(key)
def cache_set(key,value,timeout = None): from BTPanel import cache return cache.set(key,value,timeout)
def cache_remove(key): from BTPanel import cache return cache.delete(key)
def sess_get(key): from BTPanel import session if key in session: return session[key] return None
def sess_set(key,value): from BTPanel import session session[key] = value return True
def sess_remove(key): from BTPanel import session if key in session: del(session[key]) return True
def get_page(count,p=1,rows=12,callback='',result='1,2,3,4,5,8'): import page from BTPanel import request page = page.Page() info = { 'count':count, 'row':rows, 'p':p, 'return_js':callback ,'uri':request.full_path} data = { 'page': page.GetPage(info,result), 'shift': str(page.SHIFT), 'row': str(page.ROW) } return data
def version(): try: from BTPanel import g return g.version except: comm = ReadFile('/www/server/panel/class/common.py') return re.search("g\.version\s*=\s*'(\d+\.\d+\.\d+)'",comm).groups()[0]
def get_path_size(path): if not os.path.exists(path): return 0 if not os.path.isdir(path): return os.path.getsize(path) size_total = 0 for nf in os.walk(path): for f in nf[2]: filename = nf[0] + '/' + f if not os.path.exists(filename): continue if os.path.islink(filename): continue size_total += os.path.getsize(filename) return size_total
def write_request_log(reques = None): try: from BTPanel import request,g if request.path in ['/service_status','/favicon.ico','/task','/system','/ajax','/control','/data','/ssl']: return False
log_path = '/www/server/panel/logs/request' log_file = getDate(format='%Y-%m-%d') + '.json' if not os.path.exists(log_path): os.makedirs(log_path)
log_data = [] log_data.append(getDate()) log_data.append(GetClientIp() + ':' + str(request.environ.get('REMOTE_PORT'))) log_data.append(request.method) log_data.append(request.full_path) log_data.append(request.headers.get('User-Agent')) if request.method == 'POST': args = str(request.form.to_dict()) if len(args) < 2048 and args.find('pass') == -1 and args.find('user') == -1: log_data.append(args) else: log_data.append('{}') else: log_data.append('{}') log_data.append(int((time.time() - g.request_time) * 1000)) WriteFile(log_path + '/' + log_file,json.dumps(log_data) + "\n",'a+') rep_sys_path() except: pass
def mod_reload(mode): if not mode: return False try: if sys.version_info[0] == 2: reload(mode) else: import imp imp.reload(mode) return True except: return False
def set_mode(filename,mode): if not os.path.exists(filename): return False mode = int(str(mode),8) os.chmod(filename,mode) return True
def set_own(filename,user,group=None): if not os.path.exists(filename): return False from pwd import getpwnam try: user_info = getpwnam(user) user = user_info.pw_uid if group: user_info = getpwnam(group) group = user_info.pw_gid except: user_info = getpwnam('www') user = user_info.pw_uid group = user_info.pw_gid os.chown(filename,user,group) return True
def path_safe_check(path,force=True): if len(path) > 256: return False checks = ['..','./','\\','%','$','^','&','*','~','"',"'",';','|','{','}','`'] for c in checks: if path.find(c) != -1: return False if force: rep = r"^[\w\s\.\/-]+$" if not re.match(rep,path): return False return True
def get_database_character(db_name): try: import panelMysql tmp = panelMysql.panelMysql().query("show create database `%s`" % db_name.strip()) c_type = str(re.findall(r"SET\s+([\w\d-]+)\s",tmp[0][1])[0]) c_types = ['utf8','utf-8','gbk','big5','utf8mb4'] if not c_type.lower() in c_types: return 'utf8' return c_type except: return 'utf8'
def en_punycode(domain): if sys.version_info[0] == 2: domain = domain.encode('utf8') tmp = domain.split('.') newdomain = '' for dkey in tmp: if dkey == '*': continue match = re.search(u"[\x80-\xff]+",dkey) if not match: match = re.search(u"[\u4e00-\u9fa5]+",dkey) if not match: newdomain += dkey + '.' else: if sys.version_info[0] == 2: newdomain += 'xn--' + dkey.decode('utf-8').encode('punycode') + '.' else: newdomain += 'xn--' + dkey.encode('punycode').decode('utf-8') + '.' if tmp[0] == '*': newdomain = "*." + newdomain return newdomain[0:-1]
def de_punycode(domain): tmp = domain.split('.') newdomain = '' for dkey in tmp: if dkey.find('xn--') >=0: newdomain += dkey.replace('xn--','').encode('utf-8').decode('punycode') + '.' else: newdomain += dkey + '.' return newdomain[0:-1]
def get_cron_path(): u_file = '/var/spool/cron/crontabs/root' if not os.path.exists(u_file): file='/var/spool/cron/root' else: file=u_file return file
def en_crypt(key,strings): try: if type(strings) != bytes: strings = strings.encode('utf-8') from cryptography.fernet import Fernet f = Fernet(key) result = f.encrypt(strings) return result.decode('utf-8') except: return strings
def de_crypt(key,strings): try: if type(strings) != bytes: strings = strings.decode('utf-8') from cryptography.fernet import Fernet f = Fernet(key) result = f.decrypt(strings).decode('utf-8') return result except: return strings
def check_ip_panel(): ip_file = 'data/limitip.conf' if os.path.exists(ip_file): iplist = ReadFile(ip_file) if iplist: iplist = iplist.strip() if not GetClientIp() in iplist.split(','): errorStr = ReadFile('./BTPanel/templates/' + GetConfigValue('template') + '/error2.html') try: errorStr = errorStr.format(getMsg('PAGE_ERR_TITLE'),getMsg('PAGE_ERR_IP_H1'),getMsg('PAGE_ERR_IP_P1',(GetClientIp(),)),getMsg('PAGE_ERR_IP_P2'),getMsg('PAGE_ERR_IP_P3'),getMsg('NAME'),getMsg('PAGE_ERR_HELP')) except IndexError:pass return errorStr return False
def check_domain_panel(): tmp = GetHost() domain = ReadFile('data/domain.conf') if domain: if tmp.strip().lower() != domain.strip().lower(): errorStr = ReadFile('./BTPanel/templates/' + GetConfigValue('template') + '/error2.html') try: errorStr = errorStr.format(getMsg('PAGE_ERR_TITLE'),getMsg('PAGE_ERR_DOMAIN_H1'),getMsg('PAGE_ERR_DOMAIN_P1'),getMsg('PAGE_ERR_DOMAIN_P2'),getMsg('PAGE_ERR_DOMAIN_P3'),getMsg('NAME'),getMsg('PAGE_ERR_HELP')) except:pass return errorStr return False
def is_local(): s_file = '/www/server/panel/data/not_network.pl' return os.path.exists(s_file)
def auto_backup_panel(): try: panel_paeh = '/www/server/panel' paths = panel_paeh + '/data/not_auto_backup.pl' if os.path.exists(paths): return False b_path = '/www/backup/panel' backup_path = b_path + '/' + format_date('%Y-%m-%d') if os.path.exists(backup_path): return True if os.path.getsize(panel_paeh + '/data/default.db') > 104857600 * 2: return False os.makedirs(backup_path,384) import shutil shutil.copytree(panel_paeh + '/data',backup_path + '/data') shutil.copytree(panel_paeh + '/config',backup_path + '/config') shutil.copytree(panel_paeh + '/vhost',backup_path + '/vhost') ExecShell("chmod -R 600 {path};chown -R root.root {path}".format(paht=b_path)) time_now = time.time() - (86400 * 15) for f in os.listdir(b_path): try: if time.mktime(time.strptime(f, "%Y-%m-%d")) < time_now: path = b_path + '/' + f if os.path.exists(path): shutil.rmtree(path) except: continue except:pass
def check_port_stat(port,localIP = '127.0.0.1'): import socket temp = {} temp['port'] = port temp['local'] = True try: s = socket.socket() s.settimeout(0.15) s.connect((localIP,port)) s.close() except: temp['local'] = False
result = 0 if temp['local']: result +=2 return result
def sync_date(): tip_file = "/dev/shm/last_sync_time.pl" s_time = int(time.time()) try: if os.path.exists(tip_file): if s_time - int(readFile(tip_file)) < 60: return False os.remove(tip_file) time_str = HttpGet('http://www.bt.cn/api/index/get_time') new_time = int(time_str) time_arr = time.localtime(new_time) date_str = time.strftime("%Y-%m-%d %H:%M:%S", time_arr) ExecShell('date -s "%s"' % date_str) writeFile(tip_file,str(s_time)) return True except: if os.path.exists(tip_file): os.remove(tip_file) return False
def reload_mod(mod_name = None): modules = [] if mod_name: if type(mod_name) == str: mod_names = mod_name.split(',')
for mod_name in mod_names: if mod_name in sys.modules: print(mod_name) try: if sys.version_info[0] == 2: reload(sys.modules[mod_name]) else: importlib.reload(sys.modules[mod_name]) modules.append([mod_name,True]) except: modules.append([mod_name,False]) else: modules.append([mod_name,False]) return modules
for mod_name in sys.modules.keys(): if mod_name in ['BTPanel']: continue f = getattr(sys.modules[mod_name],'__file__',None) if f: try: if f.find('panel/') == -1: continue if sys.version_info[0] == 2: reload(sys.modules[mod_name]) else: importlib.reload(sys.modules[mod_name]) modules.append([mod_name,True]) except: modules.append([mod_name,False]) return modules
def de_hexb(data): if sys.version_info[0] != 2: if type(data) == str: data = data.encode('utf-8') pdata = base64.b64encode(data) if sys.version_info[0] != 2: if type(pdata) == str: pdata = pdata.encode('utf-8') return binascii.hexlify(pdata)
def en_hexb(data): if sys.version_info[0] != 2: if type(data) == str: data = data.encode('utf-8') result = base64.b64decode(binascii.unhexlify(data)) if type(result) != str: result = result.decode('utf-8') return result
def upload_file_url(filename): try: if os.path.exists(filename): data = ExecShell('/usr/bin/curl https://scanner.baidu.com/enqueue -F archive=@%s' % filename) data = json.loads(data[0]) time.sleep(1) import requests default_headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36' } data_list = requests.get(url=data['url'], headers=default_headers, verify=False) return (data_list.json()) else: return False except: return False
def request_php(version,uri,document_root,method='GET',pdata=b''): import panelPHP if type(pdata) == dict: pdata = url_encode(pdata) p = panelPHP.FPM('/tmp/php-cgi-'+version+'.sock',document_root) result = p.load_url_public(uri,pdata,method) return result
def url_encode(data): if type(data) == str: return data import urllib if sys.version_info[0] != 2: pdata = urllib.parse.urlencode(data).encode('utf-8') else: pdata = urllib.urlencode(data) return pdata
def url_decode(data): if type(data) == str: return data import urllib if sys.version_info[0] != 2: pdata = urllib.parse.urldecode(data).encode('utf-8') else: pdata = urllib.urldecode(data) return pdata
def unicode_encode(data): try: if sys.version_info[0] == 2: result = unicode(data,errors='ignore') else: result = data.encode('utf8',errors='ignore') return result except: return data
def unicode_decode(data,charset = 'utf8'): try: if sys.version_info[0] == 2: result = unicode(data,errors='ignore') else: result = data.decode('utf8',errors='ignore') return result except: return data
def import_cdn_plugin(): plugin_path = 'plugin/static_cdn' if not os.path.exists(plugin_path): return True try: import static_cdn_main except: package_path_append(plugin_path) import static_cdn_main
def get_cdn_hosts(): try: if import_cdn_plugin(): return [] import static_cdn_main return static_cdn_main.static_cdn_main().get_hosts(None) except: return []
def get_cdn_url(): try: if os.path.exists('plugin/static_cdn/not_open.pl'): return False from BTPanel import cache cdn_url = cache.get('cdn_url') if cdn_url: return cdn_url if import_cdn_plugin(): return False import static_cdn_main cdn_url = static_cdn_main.static_cdn_main().get_url(None) cache.set('cdn_url',cdn_url,3) return cdn_url except: return False
def set_cdn_url(cdn_url): if not cdn_url: return False import_cdn_plugin() get = dict_obj() get.cdn_url = cdn_url import static_cdn_main static_cdn_main.static_cdn_main().set_url(get) return True
def get_python_bin(): bin_file = '/www/server/panel/pyenv/bin/python' if os.path.exists(bin_file): return bin_file return '/usr/bin/python'
def aes_encrypt(data,key): import panelAes if sys.version_info[0] == 2: aes_obj = panelAes.aescrypt_py2(key) return aes_obj.aesencrypt(data) else: aes_obj = panelAes.aescrypt_py3(key) return aes_obj.aesencrypt(data)
def aes_decrypt(data,key): import panelAes if sys.version_info[0] == 2: aes_obj = panelAes.aescrypt_py2(key) return aes_obj.aesdecrypt(data) else: aes_obj = panelAes.aescrypt_py3(key) return aes_obj.aesdecrypt(data)
def clean_max_log(log_file,max_size = 100,old_line = 100): if not os.path.exists(log_file): return False max_size = 1024 * 1024 * max_size if os.path.getsize(log_file) > max_size: try: old_body = GetNumLines(log_file,old_line) writeFile(log_file,old_body) except: print(get_error_info())
def get_cert_data(path): import panelSSL get = dict_obj() get.certPath = path data = panelSSL.panelSSL().GetCertName(get) return data
def get_linux_distribution(): distribution = 'ubuntu' redhat_file = '/etc/redhat-release' if os.path.exists(redhat_file): try: tmp = readFile(redhat_file).split()[3][0] if int(tmp) > 7: distribution = 'centos8' except: distribution = 'centos7' return distribution
def long2ip(ips): ''' @name 将整数转换为IP地址 @author hwliang<2020-06-11> @param ips string(ip地址整数) @return ipv4 ''' i1 = int(ips / (2 ** 24)) i2 = int((ips - i1 * ( 2 ** 24 )) / ( 2 ** 16 )) i3 = int(((ips - i1 * ( 2 ** 24 )) - i2 * ( 2 ** 16 )) / ( 2 ** 8)) i4 = int(((ips - i1 * ( 2 ** 24 )) - i2 * ( 2 ** 16 )) - i3 * ( 2 ** 8)) return "{}.{}.{}.{}".format(i1,i2,i3,i4)
def ip2long(ip): ''' @name 将IP地址转换为整数 @author hwliang<2020-06-11> @param ip string(ipv4) @return long ''' ips = ip.split('.') if len(ips) != 4: return 0 iplong = 2 ** 24 * int(ips[0]) + 2 ** 16 * int(ips[1]) + 2 ** 8 * int(ips[2]) + int(ips[3]) return iplong
def submit_keyword(keyword): pdata = {"keyword":keyword} httpPost(GetConfigValue('home') + '/api/panel/total_keyword',pdata)
def total_keyword(keyword): import threading p = threading.Thread(target=submit_keyword,args=(keyword,)) p.setDaemon(True) p.start()
def get_debug_log(): from BTPanel import request return GetClientIp() +':'+ str(request.environ.get('REMOTE_PORT')) + '|' + str(int(time.time())) + '|' + get_error_info()
def get_session_id(): from BTPanel import request session_id = request.cookies.get('SESSIONID','') return session_id
def rep_default_db(): db_path = '/www/server/panel/data/' db_file = db_path + 'default.db' db_tmp_backup = db_path + 'default_' + format_date("%Y%m%d_%H%M%S") + ".db"
panel_backup = '/www/backup/panel' bak_list = os.listdir(panel_backup) if not bak_list: return False bak_list = sorted(bak_list,reverse=True) db_bak_file = '' for d_name in bak_list: db_bak_file = panel_backup + '/' + d_name + '/data/default.db' if not os.path.exists(db_bak_file): continue if os.path.getsize(db_bak_file) < 17408: continue break
if not db_bak_file: return False ExecShell("\cp -arf {} {}".format(db_file,db_tmp_backup)) ExecShell("\cp -arf {} {}".format(db_bak_file,db_file)) return True
def chdck_salt(): ''' @name 检查所有用户密码是否加盐,若没有则自动加上 @author hwliang<2020-07-08> @return void '''
if not M('sqlite_master').where('type=? AND name=? AND sql LIKE ?', ('table', 'users','%salt%')).count(): M('users').execute("ALTER TABLE 'users' ADD 'salt' TEXT",()) u_list = M('users').where('salt is NULL',()).field('id,username,password,salt').select() if isinstance(u_list,str): if u_list.find('no such table: users') != -1: rep_default_db() if not M('sqlite_master').where('type=? AND name=? AND sql LIKE ?', ('table', 'users','%salt%')).count(): M('users').execute("ALTER TABLE 'users' ADD 'salt' TEXT",()) u_list = M('users').where('salt is NULL',()).field('id,username,password,salt').select()
for u_info in u_list: salt = GetRandomString(12) pdata = {} pdata['password'] = md5(md5(u_info['password']+'_bt.cn') + salt) pdata['salt'] = salt M('users').where('id=?',(u_info['id'],)).update(pdata)
def get_login_token(): token_s = readFile('/www/server/panel/data/login_token.pl') if not token_s: return GetRandomString(32) return token_s
def get_sess_key(): from BTPanel import session return md5(get_login_token() + session.get('request_token_head',''))
def password_salt(password,username=None,uid=None): ''' @name 为指定密码加盐 @author hwliang<2020-07-08> @param password string(被md5加密一次的密码) @param username string(用户名) 可选 @param uid int(uid) 可选 @return string ''' chdck_salt() if not uid: if not username: raise Exception('username或uid必需传一项') uid = M('users').where('username=?',(username,)).getField('id') salt = M('users').where('id=?',(uid,)).getField('salt') return md5(md5(password+'_bt.cn')+salt)
def package_path_append(path): if not path in sys.path: sys.path.insert(0,path)
def rep_sys_path(): sys_path = [] for p in sys.path: if p in sys_path: continue sys_path.append(p) sys.path = sys_path
def get_ssh_port(): ''' @name 获取本机SSH端口 @author hwliang<2020-08-07> @return int ''' s_file = '/etc/ssh/sshd_config' conf = readFile(s_file) if not conf: conf = '' rep = r"#*Port\s+([0-9]+)\s*\n" tmp1 = re.search(rep,conf) ssh_port = 22 if tmp1: ssh_port = int(tmp1.groups(0)[0]) return ssh_port
def set_error_num(key,empty = False,expire=3600): ''' @name 设置失败次数(每调用一次+1) @author hwliang<2020-08-21> @param key<string> 索引 @param empty<bool> 是否清空计数 @param expire<int> 计数器生命周期(秒) @return bool ''' from BTPanel import cache key = md5(key) num = cache.get(key) if not num: num = 0 else: if empty: cache.delete(key) return True cache.set(key,num + 1,expire) return True
def get_error_num(key,limit=False): ''' @name 获取失败次数 @author hwliang<2020-08-21> @param key<string> 索引 @param limit<False or int> 如果为False,则直接返回失败次数,否则与失败次数比较,若大于失败次数返回True,否则返回False @return int or bool ''' from BTPanel import cache key = md5(key) num = cache.get(key) if not num: num = 0 if not limit: return num if limit > num: return True return False
def get_menus(): ''' @name 获取菜单列表 @author hwliang<2020-08-31> @return list ''' data = json.loads(ReadFile('config/menu.json')) hide_menu = ReadFile('config/hide_menu.json') if hide_menu: hide_menu = json.loads(hide_menu) show_menu = [] for i in range(len(data)): if data[i]['id'] in hide_menu: continue show_menu.append(data[i]) data = show_menu del(hide_menu) del(show_menu) menus = sorted(data, key=lambda x: x['sort']) return menus
def get_curl_bin(): ''' @name 取CURL执行路径 @author hwliang<2020-09-01> @return string ''' c_bin = ['/usr/local/curl2/bin/curl','/usr/local/curl/bin/curl','/usr/bin/curl'] for cb in c_bin: if os.path.exists(cb): return cb return 'curl'
class dict_obj: def __contains__(self, key): return getattr(self,key,None) def __setitem__(self, key, value): setattr(self,key,value) def __getitem__(self, key): return getattr(self,key,None) def __delitem__(self,key): delattr(self,key) def __delattr__(self, key): delattr(self,key) def get_items(self): return self
class get_modules:
def __contains__(self, key): return self.get_attr(key)
def __setitem__(self, key, value): setattr(self,key,value)
def get_attr(self,key): ''' 尝试获取模块,若为字符串,则尝试实例化模块,否则直接返回模块对像 ''' res = getattr(self,key) if isinstance(res,str): try: tmp_obj = __import__(key) reload(tmp_obj) setattr(self,key,tmp_obj) return tmp_obj except: raise Exception(get_error_info()) return res
def __getitem__(self, key): return self.get_attr(key)
def __delitem__(self,key): delattr(self,key)
def __delattr__(self, key): delattr(self,key)
def get_items(self): return self
def __init__(self,path = "class",limit = None): ''' @name 加载指定目录下的模块 @author hwliang<2020-08-03> @param path<string> 指定目录,可指定绝对目录,也可指定相对于/www/server/panel的相对目录 默认加载class目录 @param limit<string/list/tuple> 指定限定加载的模块名称,默认加载path目录下的所有模块 @param object
@example p = get_modules('class') if 'public' in p: md5_str = p.public.md5('test') md5_str = p['public'].md5('test') md5_str = getattr(p['public'],'md5')('test') else: print(p.__dict__) ''' os.chdir('/www/server/panel') exp_files = ['__init__.py','__pycache__'] if not path in sys.path: sys.path.insert(0,path) for fname in os.listdir(path): if fname in exp_files: continue filename = '/'.join([path,fname]) if os.path.isfile(filename): if not fname[-3:] in ['.py','.so']: continue mod_name = fname[:-3] else: c_file = '/'.join((filename,'__init__.py')) if not os.path.exists(c_file): continue mod_name = fname
if limit: if not isinstance(limit,list) and not isinstance(limit,tuple): limit = (limit,) if not mod_name in limit: continue
setattr(self,mod_name,mod_name)
|