Files
wiki/tasks/ha/proxy-vm/install.sh
2026-04-12 21:55:33 +03:00

229 lines
8.4 KiB
Bash
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env bash
# install.sh — Установка и настройка Xray на Ubuntu VM
# Запускать от root: sudo bash install.sh
set -euo pipefail
### ── Цвета ────────────────────────────────────────────────────────────────
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m'
info() { echo -e "${GREEN}[INFO]${NC} $*"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
error() { echo -e "${RED}[ERR]${NC} $*"; exit 1; }
### ── Проверка root ─────────────────────────────────────────────────────────
[[ $EUID -ne 0 ]] && error "Запускай от root (sudo bash install.sh)"
### ── Загрузка параметров ──────────────────────────────────────────────────
PARAMS_FILE="/etc/xray/params.env"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if [[ -f "$PARAMS_FILE" ]]; then
info "Загружаю параметры из $PARAMS_FILE"
# shellcheck disable=SC1090
source "$PARAMS_FILE"
elif [[ -f "$SCRIPT_DIR/params.env" ]]; then
info "Загружаю параметры из $SCRIPT_DIR/params.env"
source "$SCRIPT_DIR/params.env"
else
error "Файл параметров не найден!\nСкопируй params.env.example → params.env и заполни значения."
fi
# Обязательные переменные
: "${VLESS_SERVER_IP:?Укажи VLESS_SERVER_IP в params.env}"
: "${VLESS_UUID:?Укажи VLESS_UUID в params.env}"
: "${VLESS_PUBLIC_KEY:?Укажи VLESS_PUBLIC_KEY в params.env}"
: "${VLESS_SHORT_ID:?Укажи VLESS_SHORT_ID в params.env}"
: "${VLESS_SNI:?Укажи VLESS_SNI в params.env}"
### ── Обновление системы ────────────────────────────────────────────────────
info "Обновляю пакеты..."
apt-get update -qq
apt-get install -y -qq curl wget unzip iptables iptables-persistent netfilter-persistent
### ── Установка Xray ────────────────────────────────────────────────────────
info "Устанавливаю Xray (последняя версия)..."
XRAY_VERSION=$(curl -fsSL "https://api.github.com/repos/XTLS/Xray-core/releases/latest" \
| grep '"tag_name"' | sed 's/.*"tag_name": *"\(.*\)".*/\1/')
info "Версия: $XRAY_VERSION"
ARCH=$(uname -m)
case "$ARCH" in
x86_64) XRAY_ARCH="64" ;;
aarch64) XRAY_ARCH="arm64-v8a" ;;
*) error "Неизвестная архитектура: $ARCH" ;;
esac
XRAY_URL="https://github.com/XTLS/Xray-core/releases/download/${XRAY_VERSION}/Xray-linux-${XRAY_ARCH}.zip"
TMP_DIR=$(mktemp -d)
wget -q "$XRAY_URL" -O "$TMP_DIR/xray.zip"
unzip -q "$TMP_DIR/xray.zip" -d "$TMP_DIR/xray"
install -m 755 "$TMP_DIR/xray/xray" /usr/local/bin/xray
rm -rf "$TMP_DIR"
info "Xray установлен: $(xray --version | head -1)"
### ── Создание директорий и params.env ────────────────────────────────────
mkdir -p /etc/xray /var/log/xray
if [[ ! -f "$PARAMS_FILE" ]]; then
info "Создаю $PARAMS_FILE..."
cp "$SCRIPT_DIR/params.env" "$PARAMS_FILE" 2>/dev/null || \
cp "$SCRIPT_DIR/params.env.example" "$PARAMS_FILE"
fi
chmod 600 "$PARAMS_FILE"
### ── Генерация config.json ────────────────────────────────────────────────
info "Генерирую /etc/xray/config.json..."
cat > /etc/xray/config.json <<EOF
{
"log": {
"access": "/var/log/xray/access.log",
"error": "/var/log/xray/error.log",
"loglevel": "warning"
},
"inbounds": [
{
"tag": "http-in",
"listen": "0.0.0.0",
"port": 8888,
"protocol": "http",
"settings": {
"allowTransparent": false
}
},
{
"tag": "socks-in",
"listen": "0.0.0.0",
"port": 1080,
"protocol": "socks",
"settings": {
"auth": "noauth",
"udp": true
}
},
{
"tag": "tproxy-in",
"listen": "0.0.0.0",
"port": 12345,
"protocol": "dokodemo-door",
"settings": {
"network": "tcp,udp",
"followRedirect": true
},
"streamSettings": {
"sockopt": {
"tproxy": "tproxy"
}
}
}
],
"outbounds": [
{
"tag": "vless-out",
"protocol": "vless",
"settings": {
"vnext": [
{
"address": "${VLESS_SERVER_IP}",
"port": 443,
"users": [
{
"id": "${VLESS_UUID}",
"encryption": "none",
"flow": "xtls-rprx-vision"
}
]
}
]
},
"streamSettings": {
"network": "tcp",
"security": "reality",
"realitySettings": {
"serverName": "${VLESS_SNI}",
"publicKey": "${VLESS_PUBLIC_KEY}",
"shortId": "${VLESS_SHORT_ID}",
"fingerprint": "chrome"
}
}
},
{
"tag": "direct",
"protocol": "freedom"
},
{
"tag": "block",
"protocol": "blackhole"
}
],
"routing": {
"domainStrategy": "IPIfNonMatch",
"rules": [
{
"type": "field",
"ip": ["geoip:private"],
"outboundTag": "direct"
},
{
"type": "field",
"inboundTag": ["http-in", "socks-in", "tproxy-in"],
"outboundTag": "vless-out"
}
]
}
}
EOF
### ── IP Forwarding ─────────────────────────────────────────────────────────
info "Включаю IP forwarding..."
sysctl -w net.ipv4.ip_forward=1 > /dev/null
sysctl -w net.ipv6.conf.all.forwarding=1 > /dev/null
grep -qxF 'net.ipv4.ip_forward=1' /etc/sysctl.conf \
|| echo 'net.ipv4.ip_forward=1' >> /etc/sysctl.conf
grep -qxF 'net.ipv6.conf.all.forwarding=1' /etc/sysctl.conf \
|| echo 'net.ipv6.conf.all.forwarding=1' >> /etc/sysctl.conf
### ── systemd сервис ────────────────────────────────────────────────────────
info "Создаю systemd сервис xray..."
cat > /etc/systemd/system/xray.service <<'UNIT'
[Unit]
Description=Xray Service
Documentation=https://github.com/xtls/xray-core
After=network.target nss-lookup.target
[Service]
User=root
CapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_BIND_SERVICE CAP_NET_RAW
AmbientCapabilities=CAP_NET_ADMIN CAP_NET_BIND_SERVICE CAP_NET_RAW
NoNewPrivileges=false
ExecStart=/usr/local/bin/xray run -config /etc/xray/config.json
Restart=on-failure
RestartPreventExitStatus=23
LimitNPROC=10000
LimitNOFILE=1000000
[Install]
WantedBy=multi-user.target
UNIT
systemctl daemon-reload
systemctl enable xray
systemctl restart xray
sleep 2
if systemctl is-active --quiet xray; then
info "✓ Xray запущен и работает"
else
error "Xray не запустился! Смотри: journalctl -u xray -n 50"
fi
### ── Итог ─────────────────────────────────────────────────────────────────
echo ""
info "══════════════════════════════════════════════════════"
info " Установка завершена!"
info " HTTP прокси: http://$(hostname -I | awk '{print $1}'):8888"
info " SOCKS5: socks5://$(hostname -I | awk '{print $1}'):1080"
info " Tproxy порт: 12345"
info ""
info " Следующий шаг: настроить прозрачный прокси для TV:"
info " sudo bash transparent-proxy.sh"
info "══════════════════════════════════════════════════════"