ithuang
ithuang
发布于 2025-07-26 / 3 阅读
0

Shell脚本一键部署LNMP博客

Shell脚本一键部署LNMP博客

作用:掌握LAMP/LNMP环境构建,方便后期构建Zabbix监控以及Jumpserver堡垒机 => PHP

LAMP:Linux + Apache(httpd) + MySQL + PHP(老版)

LNMP:Linux + Nginx + MySQL/MariaDB + PHP(新版)

脚本实现:

[root@hab1 /shell]# vim lnmp.sh
[root@hab1 /shell]# cat lnmp.sh
#!/bin/bash

# 数据库密码(统一管理)
DB_NAME="wordpress"
DB_USER="wpuser"
DB_PASS="LNMP@wd666"
DB_ROOT_PASS="Root@666"

echo "===== 安装 LNMP ====="
dnf -y install nginx mariadb-server php php-mysqlnd php-fpm wget

echo "===== 启动服务 ====="
systemctl start nginx mariadb php-fpm
systemctl enable nginx mariadb php-fpm

echo "===== 配置防火墙 ====="
systemctl enable firewalld --now
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload

echo "===== 初始化 MariaDB(自动安全配置)====="

# 设置 root 密码 + 安全初始化
mysql -u root <<MYSQL_SCRIPT
ALTER USER 'root'@'localhost' IDENTIFIED BY '${DB_ROOT_PASS}';
DELETE FROM mysql.user WHERE User='';
DROP DATABASE IF EXISTS test;
DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%';
FLUSH PRIVILEGES;
MYSQL_SCRIPT

echo "===== 创建 WordPress 数据库 ====="
mysql -u root -p${DB_ROOT_PASS} <<MYSQL_SCRIPT
CREATE DATABASE ${DB_NAME};
CREATE USER '${DB_USER}'@'localhost' IDENTIFIED BY '${DB_PASS}';
GRANT ALL PRIVILEGES ON ${DB_NAME}.* TO '${DB_USER}'@'localhost';
FLUSH PRIVILEGES;
MYSQL_SCRIPT

echo "===== 部署 WordPress ====="
cd /var/www/html
wget https://wordpress.org/latest.tar.gz
tar -xzf latest.tar.gz
rm -f latest.tar.gz

chown -R nginx:nginx wordpress

cp wordpress/wp-config-sample.php wordpress/wp-config.php

sed -i "s/database_name_here/${DB_NAME}/" wordpress/wp-config.php
sed -i "s/username_here/${DB_USER}/" wordpress/wp-config.php
sed -i "s/password_here/${DB_PASS}/" wordpress/wp-config.php

mv wordpress/* .
rm -rf wordpress

echo "===== 配置 Nginx ====="
cat > /etc/nginx/conf.d/wordpress.conf <<NGINX_CONF
server {
    listen 80;
    server_name _;

    root /var/www/html;
    index index.php index.html;

    location / {
        try_files \$uri \$uri/ /index.php?\$args;
    }

    location ~ \.php\$ {
        fastcgi_pass unix:/var/run/php-fpm/www.sock;
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.ht {
        deny all;
    }
}
NGINX_CONF

echo "===== 重启服务 ====="
systemctl restart nginx php-fpm

echo "===== 安装完成 ====="
echo "访问: http://<your-server-ip>"
echo "数据库信息:"
echo "DB: ${DB_NAME}"
echo "User: ${DB_USER}"
echo "Pass: ${DB_PASS}"
echo "Root Pass: ${DB_ROOT_PASS}"