install.sh 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  1. #!/bin/bash
  2. red='\033[0;31m'
  3. green='\033[0;32m'
  4. blue='\033[0;34m'
  5. yellow='\033[0;33m'
  6. plain='\033[0m'
  7. cur_dir=$(pwd)
  8. xui_folder="${XUI_MAIN_FOLDER:=/usr/local/x-ui}"
  9. xui_service="${XUI_SERVICE:=/etc/systemd/system}"
  10. # check root
  11. [[ $EUID -ne 0 ]] && echo -e "${red}Fatal error: ${plain} Please run this script with root privilege \n " && exit 1
  12. # Check OS and set release variable
  13. if [[ -f /etc/os-release ]]; then
  14. source /etc/os-release
  15. release=$ID
  16. elif [[ -f /usr/lib/os-release ]]; then
  17. source /usr/lib/os-release
  18. release=$ID
  19. else
  20. echo "Failed to check the system OS, please contact the author!" >&2
  21. exit 1
  22. fi
  23. echo "The OS release is: $release"
  24. arch() {
  25. case "$(uname -m)" in
  26. x86_64 | x64 | amd64) echo 'amd64' ;;
  27. i*86 | x86) echo '386' ;;
  28. armv8* | armv8 | arm64 | aarch64) echo 'arm64' ;;
  29. armv7* | armv7 | arm) echo 'armv7' ;;
  30. armv6* | armv6) echo 'armv6' ;;
  31. armv5* | armv5) echo 'armv5' ;;
  32. s390x) echo 's390x' ;;
  33. *) echo -e "${green}Unsupported CPU architecture! ${plain}" && rm -f install.sh && exit 1 ;;
  34. esac
  35. }
  36. echo "Arch: $(arch)"
  37. # Simple helpers
  38. is_ipv4() {
  39. [[ "$1" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]] && return 0 || return 1
  40. }
  41. is_ipv6() {
  42. [[ "$1" =~ : ]] && return 0 || return 1
  43. }
  44. is_ip() {
  45. is_ipv4 "$1" || is_ipv6 "$1"
  46. }
  47. is_domain() {
  48. [[ "$1" =~ ^([A-Za-z0-9](-*[A-Za-z0-9])*\.)+[A-Za-z]{2,}$ ]] && return 0 || return 1
  49. }
  50. install_base() {
  51. case "${release}" in
  52. ubuntu | debian | armbian)
  53. apt-get update && apt-get install -y -q curl tar tzdata openssl socat
  54. ;;
  55. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  56. dnf -y update && dnf install -y -q curl tar tzdata openssl socat
  57. ;;
  58. centos)
  59. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  60. yum -y update && yum install -y curl tar tzdata openssl socat
  61. else
  62. dnf -y update && dnf install -y -q curl tar tzdata openssl socat
  63. fi
  64. ;;
  65. arch | manjaro | parch)
  66. pacman -Syu && pacman -Syu --noconfirm curl tar tzdata openssl socat
  67. ;;
  68. opensuse-tumbleweed | opensuse-leap)
  69. zypper refresh && zypper -q install -y curl tar timezone openssl socat
  70. ;;
  71. alpine)
  72. apk update && apk add curl tar tzdata openssl socat
  73. ;;
  74. *)
  75. apt-get update && apt-get install -y -q curl tar tzdata openssl socat
  76. ;;
  77. esac
  78. }
  79. gen_random_string() {
  80. local length="$1"
  81. local random_string=$(LC_ALL=C tr -dc 'a-zA-Z0-9' </dev/urandom | fold -w "$length" | head -n 1)
  82. echo "$random_string"
  83. }
  84. install_acme() {
  85. echo -e "${green}Installing acme.sh for SSL certificate management...${plain}"
  86. cd ~ || return 1
  87. curl -s https://get.acme.sh | sh >/dev/null 2>&1
  88. if [ $? -ne 0 ]; then
  89. echo -e "${red}Failed to install acme.sh${plain}"
  90. return 1
  91. else
  92. echo -e "${green}acme.sh installed successfully${plain}"
  93. fi
  94. return 0
  95. }
  96. setup_ssl_certificate() {
  97. local domain="$1"
  98. local server_ip="$2"
  99. local existing_port="$3"
  100. local existing_webBasePath="$4"
  101. echo -e "${green}Setting up SSL certificate...${plain}"
  102. # Check if acme.sh is installed
  103. if ! command -v ~/.acme.sh/acme.sh &>/dev/null; then
  104. install_acme
  105. if [ $? -ne 0 ]; then
  106. echo -e "${yellow}Failed to install acme.sh, skipping SSL setup${plain}"
  107. return 1
  108. fi
  109. fi
  110. # Create certificate directory
  111. local certPath="/root/cert/${domain}"
  112. mkdir -p "$certPath"
  113. # Issue certificate
  114. echo -e "${green}Issuing SSL certificate for ${domain}...${plain}"
  115. echo -e "${yellow}Note: Port 80 must be open and accessible from the internet${plain}"
  116. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt >/dev/null 2>&1
  117. ~/.acme.sh/acme.sh --issue -d ${domain} --listen-v6 --standalone --httpport 80 --force
  118. if [ $? -ne 0 ]; then
  119. echo -e "${yellow}Failed to issue certificate for ${domain}${plain}"
  120. echo -e "${yellow}Please ensure port 80 is open and try again later with: x-ui${plain}"
  121. rm -rf ~/.acme.sh/${domain} 2>/dev/null
  122. rm -rf "$certPath" 2>/dev/null
  123. return 1
  124. fi
  125. # Install certificate
  126. ~/.acme.sh/acme.sh --installcert -d ${domain} \
  127. --key-file /root/cert/${domain}/privkey.pem \
  128. --fullchain-file /root/cert/${domain}/fullchain.pem \
  129. --reloadcmd "systemctl restart x-ui" >/dev/null 2>&1
  130. if [ $? -ne 0 ]; then
  131. echo -e "${yellow}Failed to install certificate${plain}"
  132. return 1
  133. fi
  134. # Enable auto-renew
  135. ~/.acme.sh/acme.sh --upgrade --auto-upgrade >/dev/null 2>&1
  136. chmod 755 $certPath/* 2>/dev/null
  137. # Set certificate for panel
  138. local webCertFile="/root/cert/${domain}/fullchain.pem"
  139. local webKeyFile="/root/cert/${domain}/privkey.pem"
  140. if [[ -f "$webCertFile" && -f "$webKeyFile" ]]; then
  141. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile" >/dev/null 2>&1
  142. echo -e "${green}SSL certificate installed and configured successfully!${plain}"
  143. return 0
  144. else
  145. echo -e "${yellow}Certificate files not found${plain}"
  146. return 1
  147. fi
  148. }
  149. # Fallback: generate a self-signed certificate (not publicly trusted)
  150. setup_self_signed_certificate() {
  151. local name="$1" # domain or IP to place in SAN
  152. local certDir="/root/cert/selfsigned"
  153. echo -e "${yellow}Generating a self-signed certificate (not publicly trusted)...${plain}"
  154. mkdir -p "$certDir"
  155. local sanExt=""
  156. if is_ip "$name"; then
  157. sanExt="IP:${name}"
  158. else
  159. sanExt="DNS:${name}"
  160. fi
  161. # Use -addext if supported; fallback to config file if needed
  162. openssl req -x509 -nodes -newkey rsa:2048 -days 365 \
  163. -keyout "${certDir}/privkey.pem" \
  164. -out "${certDir}/fullchain.pem" \
  165. -subj "/CN=${name}" \
  166. -addext "subjectAltName=${sanExt}" >/dev/null 2>&1
  167. if [[ $? -ne 0 ]]; then
  168. # Fallback via temporary config file (for older OpenSSL versions)
  169. local tmpCfg="${certDir}/openssl.cnf"
  170. cat > "$tmpCfg" <<EOF
  171. [req]
  172. distinguished_name=req_distinguished_name
  173. req_extensions=v3_req
  174. [req_distinguished_name]
  175. [v3_req]
  176. subjectAltName=${sanExt}
  177. EOF
  178. openssl req -x509 -nodes -newkey rsa:2048 -days 365 \
  179. -keyout "${certDir}/privkey.pem" \
  180. -out "${certDir}/fullchain.pem" \
  181. -subj "/CN=${name}" \
  182. -config "$tmpCfg" -extensions v3_req >/dev/null 2>&1
  183. rm -f "$tmpCfg"
  184. fi
  185. if [[ ! -f "${certDir}/fullchain.pem" || ! -f "${certDir}/privkey.pem" ]]; then
  186. echo -e "${red}Failed to generate self-signed certificate${plain}"
  187. return 1
  188. fi
  189. chmod 755 ${certDir}/* 2>/dev/null
  190. ${xui_folder}/x-ui cert -webCert "${certDir}/fullchain.pem" -webCertKey "${certDir}/privkey.pem" >/dev/null 2>&1
  191. echo -e "${yellow}Self-signed certificate configured. Browsers will show a warning.${plain}"
  192. return 0
  193. }
  194. # Comprehensive manual SSL certificate issuance via acme.sh
  195. ssl_cert_issue() {
  196. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep 'webBasePath:' | awk -F': ' '{print $2}' | tr -d '[:space:]' | sed 's#^/##')
  197. local existing_port=$(${xui_folder}/x-ui setting -show true | grep 'port:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
  198. # check for acme.sh first
  199. if ! command -v ~/.acme.sh/acme.sh &>/dev/null; then
  200. echo "acme.sh could not be found. Installing now..."
  201. cd ~ || return 1
  202. curl -s https://get.acme.sh | sh
  203. if [ $? -ne 0 ]; then
  204. echo -e "${red}Failed to install acme.sh${plain}"
  205. return 1
  206. else
  207. echo -e "${green}acme.sh installed successfully${plain}"
  208. fi
  209. fi
  210. # get the domain here, and we need to verify it
  211. local domain=""
  212. while true; do
  213. read -rp "Please enter your domain name: " domain
  214. domain="${domain// /}" # Trim whitespace
  215. if [[ -z "$domain" ]]; then
  216. echo -e "${red}Domain name cannot be empty. Please try again.${plain}"
  217. continue
  218. fi
  219. if ! is_domain "$domain"; then
  220. echo -e "${red}Invalid domain format: ${domain}. Please enter a valid domain name.${plain}"
  221. continue
  222. fi
  223. break
  224. done
  225. echo -e "${green}Your domain is: ${domain}, checking it...${plain}"
  226. # check if there already exists a certificate
  227. local currentCert=$(~/.acme.sh/acme.sh --list | tail -1 | awk '{print $1}')
  228. if [ "${currentCert}" == "${domain}" ]; then
  229. local certInfo=$(~/.acme.sh/acme.sh --list)
  230. echo -e "${red}System already has certificates for this domain. Cannot issue again.${plain}"
  231. echo -e "${yellow}Current certificate details:${plain}"
  232. echo "$certInfo"
  233. return 1
  234. else
  235. echo -e "${green}Your domain is ready for issuing certificates now...${plain}"
  236. fi
  237. # create a directory for the certificate
  238. certPath="/root/cert/${domain}"
  239. if [ ! -d "$certPath" ]; then
  240. mkdir -p "$certPath"
  241. else
  242. rm -rf "$certPath"
  243. mkdir -p "$certPath"
  244. fi
  245. # get the port number for the standalone server
  246. local WebPort=80
  247. read -rp "Please choose which port to use (default is 80): " WebPort
  248. if [[ ${WebPort} -gt 65535 || ${WebPort} -lt 1 ]]; then
  249. echo -e "${yellow}Your input ${WebPort} is invalid, will use default port 80.${plain}"
  250. WebPort=80
  251. fi
  252. echo -e "${green}Will use port: ${WebPort} to issue certificates. Please make sure this port is open.${plain}"
  253. # Stop panel temporarily
  254. echo -e "${yellow}Stopping panel temporarily...${plain}"
  255. systemctl stop x-ui 2>/dev/null || rc-service x-ui stop 2>/dev/null
  256. # issue the certificate
  257. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt
  258. ~/.acme.sh/acme.sh --issue -d ${domain} --listen-v6 --standalone --httpport ${WebPort} --force
  259. if [ $? -ne 0 ]; then
  260. echo -e "${red}Issuing certificate failed, please check logs.${plain}"
  261. rm -rf ~/.acme.sh/${domain}
  262. systemctl start x-ui 2>/dev/null || rc-service x-ui start 2>/dev/null
  263. return 1
  264. else
  265. echo -e "${green}Issuing certificate succeeded, installing certificates...${plain}"
  266. fi
  267. # Setup reload command
  268. reloadCmd="systemctl restart x-ui || rc-service x-ui restart"
  269. echo -e "${green}Default --reloadcmd for ACME is: ${yellow}systemctl restart x-ui || rc-service x-ui restart${plain}"
  270. echo -e "${green}This command will run on every certificate issue and renew.${plain}"
  271. read -rp "Would you like to modify --reloadcmd for ACME? (y/n): " setReloadcmd
  272. if [[ "$setReloadcmd" == "y" || "$setReloadcmd" == "Y" ]]; then
  273. echo -e "\n${green}\t1.${plain} Preset: systemctl reload nginx ; systemctl restart x-ui"
  274. echo -e "${green}\t2.${plain} Input your own command"
  275. echo -e "${green}\t0.${plain} Keep default reloadcmd"
  276. read -rp "Choose an option: " choice
  277. case "$choice" in
  278. 1)
  279. echo -e "${green}Reloadcmd is: systemctl reload nginx ; systemctl restart x-ui${plain}"
  280. reloadCmd="systemctl reload nginx ; systemctl restart x-ui"
  281. ;;
  282. 2)
  283. echo -e "${yellow}It's recommended to put x-ui restart at the end${plain}"
  284. read -rp "Please enter your custom reloadcmd: " reloadCmd
  285. echo -e "${green}Reloadcmd is: ${reloadCmd}${plain}"
  286. ;;
  287. *)
  288. echo -e "${green}Keeping default reloadcmd${plain}"
  289. ;;
  290. esac
  291. fi
  292. # install the certificate
  293. ~/.acme.sh/acme.sh --installcert -d ${domain} \
  294. --key-file /root/cert/${domain}/privkey.pem \
  295. --fullchain-file /root/cert/${domain}/fullchain.pem --reloadcmd "${reloadCmd}"
  296. if [ $? -ne 0 ]; then
  297. echo -e "${red}Installing certificate failed, exiting.${plain}"
  298. rm -rf ~/.acme.sh/${domain}
  299. systemctl start x-ui 2>/dev/null || rc-service x-ui start 2>/dev/null
  300. return 1
  301. else
  302. echo -e "${green}Installing certificate succeeded, enabling auto renew...${plain}"
  303. fi
  304. # enable auto-renew
  305. ~/.acme.sh/acme.sh --upgrade --auto-upgrade
  306. if [ $? -ne 0 ]; then
  307. echo -e "${yellow}Auto renew setup had issues, certificate details:${plain}"
  308. ls -lah /root/cert/${domain}/
  309. chmod 755 $certPath/*
  310. else
  311. echo -e "${green}Auto renew succeeded, certificate details:${plain}"
  312. ls -lah /root/cert/${domain}/
  313. chmod 755 $certPath/*
  314. fi
  315. # Restart panel
  316. systemctl start x-ui 2>/dev/null || rc-service x-ui start 2>/dev/null
  317. # Prompt user to set panel paths after successful certificate installation
  318. read -rp "Would you like to set this certificate for the panel? (y/n): " setPanel
  319. if [[ "$setPanel" == "y" || "$setPanel" == "Y" ]]; then
  320. local webCertFile="/root/cert/${domain}/fullchain.pem"
  321. local webKeyFile="/root/cert/${domain}/privkey.pem"
  322. if [[ -f "$webCertFile" && -f "$webKeyFile" ]]; then
  323. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile"
  324. echo -e "${green}Certificate paths set for the panel${plain}"
  325. echo -e "${green}Certificate File: $webCertFile${plain}"
  326. echo -e "${green}Private Key File: $webKeyFile${plain}"
  327. echo ""
  328. echo -e "${green}Access URL: https://${domain}:${existing_port}/${existing_webBasePath}${plain}"
  329. echo -e "${yellow}Panel will restart to apply SSL certificate...${plain}"
  330. systemctl restart x-ui 2>/dev/null || rc-service x-ui restart 2>/dev/null
  331. else
  332. echo -e "${red}Error: Certificate or private key file not found for domain: $domain.${plain}"
  333. fi
  334. else
  335. echo -e "${yellow}Skipping panel path setting.${plain}"
  336. fi
  337. return 0
  338. }
  339. # Reusable interactive SSL setup (domain or self-signed)
  340. # Sets global `SSL_HOST` to the chosen domain/IP for Access URL usage
  341. prompt_and_setup_ssl() {
  342. local panel_port="$1"
  343. local web_base_path="$2" # expected without leading slash
  344. local server_ip="$3"
  345. local ssl_choice=""
  346. echo -e "${yellow}Choose SSL certificate setup method:${plain}"
  347. echo -e "${green}1.${plain} Let's Encrypt (domain required, recommended)"
  348. echo -e "${green}2.${plain} Self-signed certificate (not publicly trusted)"
  349. read -rp "Choose an option (default 2): " ssl_choice
  350. ssl_choice="${ssl_choice// /}" # Trim whitespace
  351. # Default to 2 (self-signed) if not 1
  352. if [[ "$ssl_choice" != "1" ]]; then
  353. ssl_choice="2"
  354. fi
  355. case "$ssl_choice" in
  356. 1)
  357. # User chose Let's Encrypt domain option
  358. echo -e "${green}Using ssl_cert_issue() for comprehensive domain setup...${plain}"
  359. ssl_cert_issue
  360. # Extract the domain that was used from the certificate
  361. local cert_domain=$(~/.acme.sh/acme.sh --list 2>/dev/null | tail -1 | awk '{print $1}')
  362. if [[ -n "${cert_domain}" ]]; then
  363. SSL_HOST="${cert_domain}"
  364. echo -e "${green}✓ SSL certificate configured successfully with domain: ${cert_domain}${plain}"
  365. else
  366. echo -e "${yellow}SSL setup may have completed, but domain extraction failed${plain}"
  367. SSL_HOST="${server_ip}"
  368. fi
  369. ;;
  370. 2)
  371. # User chose self-signed option
  372. # Stop panel if running
  373. if [[ $release == "alpine" ]]; then
  374. rc-service x-ui stop >/dev/null 2>&1
  375. else
  376. systemctl stop x-ui >/dev/null 2>&1
  377. fi
  378. echo -e "${yellow}Using server IP for self-signed certificate: ${server_ip}${plain}"
  379. setup_self_signed_certificate "${server_ip}"
  380. if [ $? -eq 0 ]; then
  381. SSL_HOST="${server_ip}"
  382. echo -e "${green}✓ Self-signed SSL configured successfully${plain}"
  383. else
  384. echo -e "${red}✗ Self-signed SSL setup failed${plain}"
  385. SSL_HOST="${server_ip}"
  386. fi
  387. # Start panel after SSL is configured
  388. if [[ $release == "alpine" ]]; then
  389. rc-service x-ui start >/dev/null 2>&1
  390. else
  391. systemctl start x-ui >/dev/null 2>&1
  392. fi
  393. ;;
  394. *)
  395. echo -e "${red}Invalid option. Skipping SSL setup.${plain}"
  396. SSL_HOST="${server_ip}"
  397. ;;
  398. esac
  399. }
  400. config_after_install() {
  401. local existing_hasDefaultCredential=$(${xui_folder}/x-ui setting -show true | grep -Eo 'hasDefaultCredential: .+' | awk '{print $2}')
  402. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep -Eo 'webBasePath: .+' | awk '{print $2}' | sed 's#^/##')
  403. local existing_port=$(${xui_folder}/x-ui setting -show true | grep -Eo 'port: .+' | awk '{print $2}')
  404. # Properly detect empty cert by checking if cert: line exists and has content after it
  405. local existing_cert=$(${xui_folder}/x-ui setting -getCert true | grep 'cert:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
  406. local URL_lists=(
  407. "https://api4.ipify.org"
  408. "https://ipv4.icanhazip.com"
  409. "https://v4.api.ipinfo.io/ip"
  410. "https://ipv4.myexternalip.com/raw"
  411. "https://4.ident.me"
  412. "https://check-host.net/ip"
  413. )
  414. local server_ip=""
  415. for ip_address in "${URL_lists[@]}"; do
  416. server_ip=$(curl -s --max-time 3 "${ip_address}" 2>/dev/null | tr -d '[:space:]')
  417. if [[ -n "${server_ip}" ]]; then
  418. break
  419. fi
  420. done
  421. if [[ ${#existing_webBasePath} -lt 4 ]]; then
  422. if [[ "$existing_hasDefaultCredential" == "true" ]]; then
  423. local config_webBasePath=$(gen_random_string 18)
  424. local config_username=$(gen_random_string 10)
  425. local config_password=$(gen_random_string 10)
  426. read -rp "Would you like to customize the Panel Port settings? (If not, a random port will be applied) [y/n]: " config_confirm
  427. if [[ "${config_confirm}" == "y" || "${config_confirm}" == "Y" ]]; then
  428. read -rp "Please set up the panel port: " config_port
  429. echo -e "${yellow}Your Panel Port is: ${config_port}${plain}"
  430. else
  431. local config_port=$(shuf -i 1024-62000 -n 1)
  432. echo -e "${yellow}Generated random port: ${config_port}${plain}"
  433. fi
  434. ${xui_folder}/x-ui setting -username "${config_username}" -password "${config_password}" -port "${config_port}" -webBasePath "${config_webBasePath}"
  435. echo ""
  436. echo -e "${green}═══════════════════════════════════════════${plain}"
  437. echo -e "${green} SSL Certificate Setup (MANDATORY) ${plain}"
  438. echo -e "${green}═══════════════════════════════════════════${plain}"
  439. echo -e "${yellow}For security, SSL certificate is required for all panels.${plain}"
  440. echo -e "${yellow}Let's Encrypt requires a domain name (IP certificates are not issued).${plain}"
  441. echo ""
  442. prompt_and_setup_ssl "${config_port}" "${config_webBasePath}" "${server_ip}"
  443. # Display final credentials and access information
  444. echo ""
  445. echo -e "${green}═══════════════════════════════════════════${plain}"
  446. echo -e "${green} Panel Installation Complete! ${plain}"
  447. echo -e "${green}═══════════════════════════════════════════${plain}"
  448. echo -e "${green}Username: ${config_username}${plain}"
  449. echo -e "${green}Password: ${config_password}${plain}"
  450. echo -e "${green}Port: ${config_port}${plain}"
  451. echo -e "${green}WebBasePath: ${config_webBasePath}${plain}"
  452. echo -e "${green}Access URL: https://${SSL_HOST}:${config_port}/${config_webBasePath}${plain}"
  453. echo -e "${green}═══════════════════════════════════════════${plain}"
  454. echo -e "${yellow}⚠ IMPORTANT: Save these credentials securely!${plain}"
  455. echo -e "${yellow}⚠ SSL Certificate: Enabled and configured${plain}"
  456. else
  457. local config_webBasePath=$(gen_random_string 18)
  458. echo -e "${yellow}WebBasePath is missing or too short. Generating a new one...${plain}"
  459. ${xui_folder}/x-ui setting -webBasePath "${config_webBasePath}"
  460. echo -e "${green}New WebBasePath: ${config_webBasePath}${plain}"
  461. # If the panel is already installed but no certificate is configured, prompt for SSL now
  462. if [[ -z "${existing_cert}" ]]; then
  463. echo ""
  464. echo -e "${green}═══════════════════════════════════════════${plain}"
  465. echo -e "${green} SSL Certificate Setup (RECOMMENDED) ${plain}"
  466. echo -e "${green}═══════════════════════════════════════════${plain}"
  467. echo -e "${yellow}Let's Encrypt requires a domain name (IP certificates are not issued).${plain}"
  468. echo ""
  469. prompt_and_setup_ssl "${existing_port}" "${config_webBasePath}" "${server_ip}"
  470. echo -e "${green}Access URL: https://${SSL_HOST}:${existing_port}/${config_webBasePath}${plain}"
  471. else
  472. # If a cert already exists, just show the access URL
  473. echo -e "${green}Access URL: https://${server_ip}:${existing_port}/${config_webBasePath}${plain}"
  474. fi
  475. fi
  476. else
  477. if [[ "$existing_hasDefaultCredential" == "true" ]]; then
  478. local config_username=$(gen_random_string 10)
  479. local config_password=$(gen_random_string 10)
  480. echo -e "${yellow}Default credentials detected. Security update required...${plain}"
  481. ${xui_folder}/x-ui setting -username "${config_username}" -password "${config_password}"
  482. echo -e "Generated new random login credentials:"
  483. echo -e "###############################################"
  484. echo -e "${green}Username: ${config_username}${plain}"
  485. echo -e "${green}Password: ${config_password}${plain}"
  486. echo -e "###############################################"
  487. else
  488. echo -e "${green}Username, Password, and WebBasePath are properly set.${plain}"
  489. fi
  490. # Existing install: if no cert configured, prompt user to set domain or self-signed
  491. # Properly detect empty cert by checking if cert: line exists and has content after it
  492. existing_cert=$(${xui_folder}/x-ui setting -getCert true | grep 'cert:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
  493. if [[ -z "$existing_cert" ]]; then
  494. echo ""
  495. echo -e "${green}═══════════════════════════════════════════${plain}"
  496. echo -e "${green} SSL Certificate Setup (RECOMMENDED) ${plain}"
  497. echo -e "${green}═══════════════════════════════════════════${plain}"
  498. echo -e "${yellow}Let's Encrypt requires a domain name (IP certificates are not issued).${plain}"
  499. echo ""
  500. prompt_and_setup_ssl "${existing_port}" "${existing_webBasePath}" "${server_ip}"
  501. echo -e "${green}Access URL: https://${SSL_HOST}:${existing_port}/${existing_webBasePath}${plain}"
  502. else
  503. echo -e "${green}SSL certificate already configured. No action needed.${plain}"
  504. fi
  505. fi
  506. ${xui_folder}/x-ui migrate
  507. }
  508. install_x-ui() {
  509. cd ${xui_folder%/x-ui}/
  510. # Download resources
  511. if [ $# == 0 ]; then
  512. tag_version=$(curl -Ls "https://api.github.com/repos/MHSanaei/3x-ui/releases/latest" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')
  513. if [[ ! -n "$tag_version" ]]; then
  514. echo -e "${yellow}Trying to fetch version with IPv4...${plain}"
  515. tag_version=$(curl -4 -Ls "https://api.github.com/repos/MHSanaei/3x-ui/releases/latest" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')
  516. if [[ ! -n "$tag_version" ]]; then
  517. echo -e "${red}Failed to fetch x-ui version, it may be due to GitHub API restrictions, please try it later${plain}"
  518. exit 1
  519. fi
  520. fi
  521. echo -e "Got x-ui latest version: ${tag_version}, beginning the installation..."
  522. curl -4fLRo ${xui_folder}-linux-$(arch).tar.gz -z ${xui_folder}-linux-$(arch).tar.gz https://github.com/MHSanaei/3x-ui/releases/download/${tag_version}/x-ui-linux-$(arch).tar.gz
  523. if [[ $? -ne 0 ]]; then
  524. echo -e "${red}Downloading x-ui failed, please be sure that your server can access GitHub ${plain}"
  525. exit 1
  526. fi
  527. else
  528. tag_version=$1
  529. tag_version_numeric=${tag_version#v}
  530. min_version="2.3.5"
  531. if [[ "$(printf '%s\n' "$min_version" "$tag_version_numeric" | sort -V | head -n1)" != "$min_version" ]]; then
  532. echo -e "${red}Please use a newer version (at least v2.3.5). Exiting installation.${plain}"
  533. exit 1
  534. fi
  535. url="https://github.com/MHSanaei/3x-ui/releases/download/${tag_version}/x-ui-linux-$(arch).tar.gz"
  536. echo -e "Beginning to install x-ui $1"
  537. curl -4fLRo ${xui_folder}-linux-$(arch).tar.gz -z ${xui_folder}-linux-$(arch).tar.gz ${url}
  538. if [[ $? -ne 0 ]]; then
  539. echo -e "${red}Download x-ui $1 failed, please check if the version exists ${plain}"
  540. exit 1
  541. fi
  542. fi
  543. curl -4fLRo /usr/bin/x-ui-temp https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.sh
  544. if [[ $? -ne 0 ]]; then
  545. echo -e "${red}Failed to download x-ui.sh${plain}"
  546. exit 1
  547. fi
  548. # Stop x-ui service and remove old resources
  549. if [[ -e ${xui_folder}/ ]]; then
  550. if [[ $release == "alpine" ]]; then
  551. rc-service x-ui stop
  552. else
  553. systemctl stop x-ui
  554. fi
  555. rm ${xui_folder}/ -rf
  556. fi
  557. # Extract resources and set permissions
  558. tar zxvf x-ui-linux-$(arch).tar.gz
  559. rm x-ui-linux-$(arch).tar.gz -f
  560. cd x-ui
  561. chmod +x x-ui
  562. chmod +x x-ui.sh
  563. # Check the system's architecture and rename the file accordingly
  564. if [[ $(arch) == "armv5" || $(arch) == "armv6" || $(arch) == "armv7" ]]; then
  565. mv bin/xray-linux-$(arch) bin/xray-linux-arm
  566. chmod +x bin/xray-linux-arm
  567. fi
  568. chmod +x x-ui bin/xray-linux-$(arch)
  569. # Update x-ui cli and se set permission
  570. mv -f /usr/bin/x-ui-temp /usr/bin/x-ui
  571. chmod +x /usr/bin/x-ui
  572. mkdir -p /var/log/x-ui
  573. config_after_install
  574. # Etckeeper compatibility
  575. if [ -d "/etc/.git" ]; then
  576. if [ -f "/etc/.gitignore" ]; then
  577. if ! grep -q "x-ui/x-ui.db" "/etc/.gitignore"; then
  578. echo "" >> "/etc/.gitignore"
  579. echo "x-ui/x-ui.db" >> "/etc/.gitignore"
  580. echo -e "${green}Added x-ui.db to /etc/.gitignore for etckeeper${plain}"
  581. fi
  582. else
  583. echo "x-ui/x-ui.db" > "/etc/.gitignore"
  584. echo -e "${green}Created /etc/.gitignore and added x-ui.db for etckeeper${plain}"
  585. fi
  586. fi
  587. if [[ $release == "alpine" ]]; then
  588. curl -4fLRo /etc/init.d/x-ui https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.rc
  589. if [[ $? -ne 0 ]]; then
  590. echo -e "${red}Failed to download x-ui.rc${plain}"
  591. exit 1
  592. fi
  593. chmod +x /etc/init.d/x-ui
  594. rc-update add x-ui
  595. rc-service x-ui start
  596. else
  597. # Install systemd service file
  598. service_installed=false
  599. if [ -f "x-ui.service" ]; then
  600. echo -e "${green}Found x-ui.service in extracted files, installing...${plain}"
  601. cp -f x-ui.service ${xui_service}/ >/dev/null 2>&1
  602. if [[ $? -eq 0 ]]; then
  603. service_installed=true
  604. fi
  605. fi
  606. if [ "$service_installed" = false ]; then
  607. case "${release}" in
  608. ubuntu | debian | armbian)
  609. if [ -f "x-ui.service.debian" ]; then
  610. echo -e "${green}Found x-ui.service.debian in extracted files, installing...${plain}"
  611. cp -f x-ui.service.debian ${xui_service}/x-ui.service >/dev/null 2>&1
  612. if [[ $? -eq 0 ]]; then
  613. service_installed=true
  614. fi
  615. fi
  616. ;;
  617. *)
  618. if [ -f "x-ui.service.rhel" ]; then
  619. echo -e "${green}Found x-ui.service.rhel in extracted files, installing...${plain}"
  620. cp -f x-ui.service.rhel ${xui_service}/x-ui.service >/dev/null 2>&1
  621. if [[ $? -eq 0 ]]; then
  622. service_installed=true
  623. fi
  624. fi
  625. ;;
  626. esac
  627. fi
  628. # If service file not found in tar.gz, download from GitHub
  629. if [ "$service_installed" = false ]; then
  630. echo -e "${yellow}Service files not found in tar.gz, downloading from GitHub...${plain}"
  631. case "${release}" in
  632. ubuntu | debian | armbian)
  633. curl -4fLRo ${xui_service}/x-ui.service https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.debian >/dev/null 2>&1
  634. ;;
  635. *)
  636. curl -4fLRo ${xui_service}/x-ui.service https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.rhel >/dev/null 2>&1
  637. ;;
  638. esac
  639. if [[ $? -ne 0 ]]; then
  640. echo -e "${red}Failed to install x-ui.service from GitHub${plain}"
  641. exit 1
  642. fi
  643. service_installed=true
  644. fi
  645. if [ "$service_installed" = true ]; then
  646. echo -e "${green}Setting up systemd unit...${plain}"
  647. chown root:root ${xui_service}/x-ui.service >/dev/null 2>&1
  648. chmod 644 ${xui_service}/x-ui.service >/dev/null 2>&1
  649. systemctl daemon-reload
  650. systemctl enable x-ui
  651. systemctl start x-ui
  652. else
  653. echo -e "${red}Failed to install x-ui.service file${plain}"
  654. exit 1
  655. fi
  656. fi
  657. echo -e "${green}x-ui ${tag_version}${plain} installation finished, it is running now..."
  658. echo -e ""
  659. echo -e "┌───────────────────────────────────────────────────────┐
  660. │ ${blue}x-ui control menu usages (subcommands):${plain} │
  661. │ │
  662. │ ${blue}x-ui${plain} - Admin Management Script │
  663. │ ${blue}x-ui start${plain} - Start │
  664. │ ${blue}x-ui stop${plain} - Stop │
  665. │ ${blue}x-ui restart${plain} - Restart │
  666. │ ${blue}x-ui status${plain} - Current Status │
  667. │ ${blue}x-ui settings${plain} - Current Settings │
  668. │ ${blue}x-ui enable${plain} - Enable Autostart on OS Startup │
  669. │ ${blue}x-ui disable${plain} - Disable Autostart on OS Startup │
  670. │ ${blue}x-ui log${plain} - Check logs │
  671. │ ${blue}x-ui banlog${plain} - Check Fail2ban ban logs │
  672. │ ${blue}x-ui update${plain} - Update │
  673. │ ${blue}x-ui legacy${plain} - Legacy version │
  674. │ ${blue}x-ui install${plain} - Install │
  675. │ ${blue}x-ui uninstall${plain} - Uninstall │
  676. └───────────────────────────────────────────────────────┘"
  677. }
  678. echo -e "${green}Running...${plain}"
  679. install_base
  680. install_x-ui $1