当前位置: 首页 > news >正文

企业linux常用服务搭建

#!/bin/bash #判断是否是root用户if [ "$USER" != "root" ]; then echo "不是root用户,无法进行安装操作" exit 1 fi#关闭防火墙systemctl stop firewalld && systemctl disable firewalld && echo "防火墙已经关闭" sed -i 's/SELINUX=*/SELINUX=disabled/g' /etc/selinux/config && setenforce 0 && echo "关闭selinux"#安装bind服务yum install bind bind-utils -y#测试是否安装成功if [ $? -eq 0 ]; then echo "bind安装成功" else echo "bind安装失败,即将退出" exit 0 fi#!/bin/bash#提示用户输入信息read -p "请输入主服务器的 IP 地址: " MASTER_IP read -p "请输入从服务器的 IP 地址: " SLAVE_IP read -p "请输入域名: " DOMAIN#提取 IP 地址的网络段NETWORK=$(echo $MASTER_IP | cut -d '.' -f 1-3) REVERSE_NETWORK=$(echo $NETWORK | awk -F. '{print $3"."$2"."$1}')#配置主服务器的 named.confcat << EOF > /etc/named.conf options { listen-on port 53 { 127.0.0.1; $MASTER_IP; }; listen-on-v6 port 53 { ::1; }; directory "/var/named"; dump-file "/var/named/data/cache_dump.db"; statistics-file "/var/named/data/named_stats.txt"; memstatistics-file "/var/named/data/named_mem_stats.txt"; recursing-file "/var/named/data/named.recursing"; secroots-file "/var/named/data/named.secroots"; allow-query { any; }; recursion yes; dnssec-enable yes; dnssec-validation yes; bindkeys-file "/etc/named.iscdlv.key"; managed-keys-directory "/var/named/dynamic"; pid-file "/run/named/named.pid"; session-keyfile "/run/named/session.key"; }; logging { channel default_debug { file "data/named.run"; severity dynamic; }; }; zone "." IN { type hint; file "named.ca"; }; zone "$DOMAIN" IN { type master; file "$DOMAIN.zone"; allow-transfer { $SLAVE_IP; }; }; zone "$REVERSE_NETWORK.in-addr.arpa" IN { type master; file "$REVERSE_NETWORK.rev"; allow-transfer { $SLAVE_IP; }; }; include "/etc/named.rfc1912.zones"; include "/etc/named.root.key"; EOF#创建正向区域文件cat << EOF > /var/named/$DOMAIN.zone $TTL 86400 @ IN SOA ns1.$DOMAIN. admin.$DOMAIN. ( $(date +%Y%m%d01) ; Serial 3600 ; Refresh 1800 ; Retry 604800 ; Expire 86400 ) ; Minimum IN NS ns1.$DOMAIN. ns1 IN A $MASTER_IP www IN A $MASTER_IP EOF#创建反向区域文件MASTER_LAST_OCTET=$(echo $MASTER_IP | cut -d '.' -f 4) cat << EOF > /var/named/$REVERSE_NETWORK.rev $TTL 86400 @ IN SOA ns1.$DOMAIN. admin.$DOMAIN. ( $(date +%Y%m%d01) ; Serial 3600 ; Refresh 1800 ; Retry 604800 ; Expire 86400 ) ; Minimum IN NS ns1.$DOMAIN. $MASTER_LAST_OCTET IN PTR ns1.$DOMAIN. EOF#修改文件权限chown named:named /var/named/$DOMAIN.zone chown named:named /var/named/$REVERSE_NETWORK.rev#启动并设置开机自启systemctl start named systemctl enable namedecho "主服务器配置完成!"

下图为结果图DNS测试情况:

#!/bin/bashvsftpd虚拟用户安装配置脚本功能:1.配置虚拟用户FTP 2.设置定时备份 3.管理用户权限#全局变量定义VUSER_HOME="/data/ftp"
VUSER_CONF_DIR="/etc/vsftpd/vsftpd_user_conf"
VUSER_DB="/etc/vsftpd/vsftpd_login.db"
VUSER_LIST="/etc/vsftpd/vusers.list"
SYSTEM_USER="vuser"
BACKUP_DIR="/var/ftp/pub"        # 新增备份目录
DATA_DIR="/data/ftp"             # 业务数据目录
CRON_LOG="/var/log/ftp_backup.log" # 备份日志#函数定义log_info() { echo -e "\033[34m[INFO] $1\033[0m"; }
log_error() { echo -e "\033[31m[ERROR] $1\033[0m"; }
check_command() { command -v $1 >/dev/null || { log_error "$1未安装,安装失败!"; exit 1; } }#环境检查log_info "开始环境检查..."
check_command yum
check_command db_load
mkdir -p $BACKUP_DIR $DATA_DIR   # 创建业务目录和备份目录#安装依赖包(优化镜像源配置)log_info "配置阿里云镜像源..."
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
yum clean all >/dev/null
yum makecache fast >/dev/nulllog_info "开始安装vsftpd及依赖..."
yum install -y vsftpd libdb-utils lftp cronie >/dev/null
if [ $? -ne 0 ]; thenlog_error "yum安装失败,请检查网络连接或系统状态!"exit 1
fi#关闭防火墙和SELinux(优化配置)log_info "关闭防火墙..."
systemctl stop firewalld >/dev/null
systemctl disable firewalld >/dev/nulllog_info "配置SELinux..."
setenforce 0 >/dev/null
if ! grep -q "^SELINUX=disabled" /etc/selinux/config; thensed -i 's/^SELINUX=.*/SELINUX=disabled/g' /etc/selinux/config
fi#创建虚拟用户(新增业务用户)log_info "创建虚拟用户列表..."
cat > "$VUSER_LIST" <<EOF
employeeA
employeeA@123
outsourceB
outsourceB@456
backupuser
Backup@789
oppic
oppic_2025
EOF#生成虚拟用户数据库log_info "生成认证数据库..."
db_load -T -t hash -f "$VUSER_LIST" "$VUSER_DB" >/dev/null
if [ $? -ne 0 ]; thenlog_error "数据库生成失败,请检查$VUSER_LIST格式!"exit 1
fi
chmod 600 "$VUSER_DB"#配置PAM认证log_info "配置PAM认证..."
mv /etc/pam.d/vsftpd{,.bak} >/dev/null 2>&1
cat > /etc/pam.d/vsftpd <<EOF
#%PAM-1.0
auth required pam_userdb.so db=/etc/vsftpd/vsftpd_login
account required pam_userdb.so db=/etc/vsftpd/vsftpd_login
EOF#创建系统映射用户log_info "创建虚拟用户主目录..."
mkdir -p "$VUSER_HOME"/{employeeA,outsourceB,oppic} $DATA_DIR $BACKUP_DIR
chmod 755 "$VUSER_HOME"
chown -R "$SYSTEM_USER":"$SYSTEM_USER" "$VUSER_HOME"log_info "创建系统映射用户..."
if ! id "$SYSTEM_USER" &>/dev/null; thenuseradd -d "$VUSER_HOME" -s /sbin/nologin "$SYSTEM_USER" >/dev/null 2>&1 || {log_error "用户$SYSTEM_USER创建失败,请检查权限!"exit 1}
fi#配置vsftpd主文件log_info "配置vsftpd主文件..."
cat > /etc/vsftpd/vsftpd.conf <<EOF
anonymous_enable=NO
local_enable=YES
write_enable=YES
local_umask=022
dirmessage_enable=YES
xferlog_enable=YES
connect_from_port_20=YES
xferlog_file=/var/log/xferlog
xferlog_std_format=YES
listen=YES
listen_ipv6=NO
pam_service_name=vsftpd
userlist_enable=YES
tcp_wrappers=YES
guest_enable=YES
guest_username=$SYSTEM_USER
allow_writeable_chroot=YES
chroot_local_user=YES
user_config_dir=$VUSER_CONF_DIR
pasv_enable=YES
pasv_min_port=30000
pasv_max_port=30999
EOF#配置用户独立权限(新增权限管理)log_info "创建用户独立配置..."
mkdir -p "$VUSER_CONF_DIR"#员工A配置(可上传下载)cat > "$VUSER_CONF_DIR/employeeA" <<EOF
local_root=$DATA_DIR
write_enable=YES
anon_upload_enable=YES
anon_mkdir_write_enable=YES
download_enable=YES
file_open_mode=0666
EOF#外包B配置(仅上传)cat > "$VUSER_CONF_DIR/outsourceB" <<EOF
local_root=$DATA_DIR
write_enable=YES
anon_upload_enable=YES
anon_mkdir_write_enable=YES
download_enable=NO
cmds_deny=RETR
EOF#备份用户配置(只读)cat > "$VUSER_CONF_DIR/backupuser" <<EOF
local_root=$BACKUP_DIR
write_enable=NO
anon_upload_enable=NO
anon_mkdir_write_enable=NO
download_enable=NO
EOF#配置定时备份(新增备份功能)log_info "配置自动备份系统..."
cat > /usr/local/bin/ftp_backup.sh <<'EOF'
#!/bin/bash#备份配置BACKUP_SRC="/var/log"
FTP_SERVER="localhost"
BACKUP_USER="backupuser"
BACKUP_PASS="Backup@789"
BACKUP_DIR="/pub"#生成备份文件名BACKUP_FILE="logbackup_$(date +%Y%m%d_%H%M).tgz"#执行备份tar czf /tmp/${BACKUP_FILE} ${BACKUP_SRC}/*.log 2>/dev/null
if [ $? -ne 0 ]; thenecho "$(date) - 备份文件打包失败" >> /var/log/ftp_backup.logexit 1
fi#上传到FTPlftp -u ${BACKUP_USER},${BACKUP_PASS} ${FTP_SERVER} <<END
cd ${BACKUP_DIR}
put /tmp/${BACKUP_FILE}
bye
ENDif [ $? -eq 0 ]; thenecho "$(date) - 备份成功: ${BACKUP_FILE}" >> /var/log/ftp_backup.log
elseecho "$(date) - 备份上传失败" >> /var/log/ftp_backup.log
fi#清理临时文件rm -f /tmp/${BACKUP_FILE}#保留最近7天备份find ${BACKUP_DIR} -name "logbackup_*.tgz" -mtime +7 -delete
EOFchmod +x /usr/local/bin/ftp_backup.sh
echo "0 1 * * * root /usr/local/bin/ftp_backup.sh" > /etc/cron.d/ftp_backup#启动服务log_info "启动vsftpd服务..."
systemctl restart vsftpd >/dev/null 2>&1
if [ $? -ne 0 ]; thenlog_error "服务启动失败,请检查配置文件!"exit 1
fi
systemctl enable vsftpd >/dev/null#验证测试log_info "开始验证测试..."
FTP_SERVER_IP=$(hostname -I | awk '{print $1}')#测试员工A权限log_info "测试员工A权限..."
lftp -u employeeA,employeeA@123 ${FTP_SERVER_IP} <<END
cd /data/ftp
put /etc/hostname
get hostname /tmp/
ls
bye
END#测试外包B权限log_info "测试外包B权限..."
lftp -u outsourceB,outsourceB@456 ${FTP_SERVER_IP} <<END 2>&1 | grep "Access denied"
cd /data/ftp
get hostname
bye
END#测试备份功能log_info "执行首次备份测试..."
/usr/local/bin/ftp_backup.sh
if [ -f "${BACKUP_DIR}/logbackup_$(date +%Y%m%d)*.tgz" ]; thenlog_info "备份验证成功"
elselog_error "备份文件未生成,请检查配置!"
filog_info "
=== 部署完成报告 ===
FTP服务地址: ftp://${FTP_SERVER_IP}
数据存储目录: ${DATA_DIR}
备份存储目录: ${BACKUP_DIR}用户权限说明:1. 员工A (employeeA/employeeA@123)- 可上传下载文件- 访问路径: /data/ftp2. 外包B (outsourceB/outsourceB@456)- 仅可上传文件- 禁止下载操作3. 备份用户 (backupuser/Backup@789)- 仅限系统自动使用定时备份配置:执行时间: 每天凌晨1点备份日志: /var/log/ftp_backup.log保留策略: 保留最近7天备份
"

#!/bin/bash#Samba本地用户认证共享配置脚本#使用系统本地用户+组认证#保持DNS服务器配置#定义变量DOMAIN="daoyeniubi.com"              # 保持域名配置
DNS_SERVER="192.168.135.160"         # 替换为实际DNS服务器IP
SHARE_GROUPS=("manager" "market" "admin")  # 需要创建的组
SHARE_USERS=(                         # 用户配置数组"john:manager""mike:market""admin:admin"
)#安装必要软件包yum install -y samba samba-client policycoreutils-python-utils#配置DNS指向cat > /etc/resolv.conf << EOF
search $DOMAIN
nameserver $DNS_SERVER
EOF#配置Samba主文件cat > /etc/samba/smb.conf << EOF
[global]workgroup = WORKGROUPsecurity = userpassdb backend = tdbsamprinting = cupsprintcap name = cupsload printers = yescups options = raw[shared]path = /data/sharevalid users = @userswritable = yesbrowseable = yescreate mask = 0664directory mask = 0775[manager]path = /data/managervalid users = @manager, @adminwritable = yesbrowseable = yescreate mask = 0664directory mask = 0775force group = manager[market]path = /data/marketvalid users = @market, @adminwritable = yesbrowseable = yescreate mask = 0664directory mask = 0775force group = market
EOF#创建系统用户和组for group in "${SHARE_GROUPS[@]}"; dogroupadd -f $group
donefor user_info in "${SHARE_USERS[@]}"; doIFS=':' read -ra user_data <<< "$user_info"user=${user_data[0]}group=${user_data[1]}useradd -M -s /sbin/nologin -G $group $userecho "为 $user 设置SMB密码:"smbpasswd -a $userdone#创建共享目录并设置权限mkdir -p /data/{share,manager,market}
chmod 2775 /data/share /data/manager /data/market
chown :manager /data/manager
chown :market /data/market
chown :users /data/share#配置SELinuxsetsebool -P samba_export_all_rw=1
semanage fcontext -a -t samba_share_t "/data/share(/.*)?"
semanage fcontext -a -t samba_share_t "/data/manager(/.*)?"
semanage fcontext -a -t samba_share_t "/data/market(/.*)?"
restorecon -Rv /data#防火墙配置firewall-cmd --permanent --add-service=samba
firewall-cmd --reload#重启服务systemctl restart smb
systemctl enable smb#验证命令提示echo "配置完成!验证步骤:"
echo "1. 检查共享列表: smbclient -L localhost -U%"
echo "2. 访问共享示例:"
echo "   - 经理共享: smbclient //$(hostname)/manager -U john"
echo "   - 市场共享: smbclient //$(hostname)/market -U mike"
echo "   - 管理员测试: smbclient //$(hostname)/manager -U admin"

限制smb服务器磁盘规划,规划文件文件挂载及存放

#!/bin/bash
# Samba共享自动配置与验证脚本# 服务端配置部分
SERVER_IP=$(hostname -I | awk '{print $1}')
DOMAIN="samba.abc.com"
SHARE_USER_PASS="123456"  # 设置统一密码,生产环境建议使用更安全的方式# 创建共享目录结构
mkdir -p /data/{manager,market}
echo "samba test." > /data/manager/sa.txt
cp /var/log/secure /data/market/# 设置权限
chmod 2775 /data/{manager,market}
chown :manager /data/manager
chown :market /data/market
restorecon -Rv /data# 创建系统用户和组
declare -A USER_GROUPS=(["john"]="manager"["mike"]="market"["admin"]="admin"
)for user in "${!USER_GROUPS[@]}"; dogroup=${USER_GROUPS[$user]}groupadd -f $groupif ! id -u $user &>/dev/null; thenuseradd -M -s /sbin/nologin -G $group $userfi(echo "$SHARE_USER_PASS"; echo "$SHARE_USER_PASS") | smbpasswd -a -s $user
done# 配置SELinux
setsebool -P samba_export_all_rw=1
semanage fcontext -a -t samba_share_t "/data/manager(/.*)?" 
semanage fcontext -a -t samba_share_t "/data/market(/.*)?"
restorecon -Rv /data# 防火墙配置
firewall-cmd --permanent --add-service=samba
firewall-cmd --reload# 重启服务
systemctl restart smb
systemctl enable smb# 客户端验证指令生成
cat <<EOF==================== 客户端验证步骤 ====================1. Windows客户端访问:资源管理器地址栏输入:\\\\$DOMAIN\\manager使用凭证:- john 用户:用户名 john 密码 $SHARE_USER_PASS- admin 用户:用户名 admin 密码 $SHARE_USER_PASS应能看到 sa.txt 文件2. Linux客户端挂载:# 安装依赖sudo yum install -y cifs-utils# 创建挂载点sudo mkdir -p /opt/market# 临时挂载测试sudo mount -t cifs //$DOMAIN/market /opt/market \\-o username=mike,password=$SHARE_USER_PASS,uid=\$(id -u),gid=\$(id -g)# 查看文件ls -l /opt/market/secure# 持久化挂载(编辑/etc/fstab)://$DOMAIN/market  /opt/market  cifs  credentials=/etc/samba/cred,uid=\$(id -u),gid=\$(id -g) 0 0创建凭据文件:echo -e "username=mike\\npassword=$SHARE_USER_PASS" | sudo tee /etc/samba/credsudo chmod 600 /etc/samba/cred3. 服务端状态检查:smbstatustestparm -s
EOF

samba脚本运行结果

服务器安全控制 加强系统账号安全 清理无用的账号,锁定长期不用的账号,锁定账号配置文件 设置用户密码的过期时间为90天 配置保持历史命令10条 配置闲置超时时间为600秒 加强系统引导和登录安全 为GRUB菜单设置密码,限制更改GRUB引导参数 禁止root用户从tty5、tty6登录

检测弱口令账号 使用John the Ripper检查所有服务器的弱口令 根据弱口令检测检测结果分别重设口令,提高口令复杂度

#!/bin/bash
# 服务器安全加固脚本 - 谨慎执行前请备份系统!# 检查是否为root权限
if [ "$(id -u)" != "0" ]; thenecho "错误:必须使用root权限运行此脚本!" >&2echo "请尝试 'sudo $0'"exit 1
fi# 记录日志
LOG_FILE="/var/log/security_harden.log"
exec > >(tee -a "$LOG_FILE") 2>&1
echo "安全加固开始时间: $(date)"#----------------------- 第一部分:系统账号安全 -----------------------
echo ">>> 正在加强系统账号安全..."# 1. 清理无用账号(示例:删除testuser,请根据实际情况修改)
UNUSED_ACCOUNTS="testuser guest demo"  # 在此定义需删除的账户
for user in $UNUSED_ACCOUNTS; doif id "$user" &>/dev/null; thenecho "正在删除账户:$user"userdel -r "$user" 2>/dev/null || echo "删除失败:$user"fi
done# 2. 锁定长期未使用账号(示例:锁定olduser)
INACTIVE_ACCOUNTS="olduser"  # 在此定义需锁定的账户
for user in $INACTIVE_ACCOUNTS; doif id "$user" &>/dev/null; thenecho "正在锁定账户:$user"passwd -l "$user"fi
done# 3. 锁定账户配置文件
echo "锁定系统账户配置文件..."
chattr +i /etc/passwd /etc/shadow /etc/group 2>/dev/null# 4. 设置密码过期策略
echo "配置密码过期时间为90天..."
sed -i 's/^PASS_MAX_DAYS.*/PASS_MAX_DAYS 90/' /etc/login.defs
sed -i 's/^PASS_MIN_DAYS.*/PASS_MIN_DAYS 1/' /etc/login.defs
awk -F: '($2 != "!") {system("chage --maxdays 90 "$1)}' /etc/shadow# 5. 历史命令保留10条
echo "export HISTSIZE=10" >> /etc/profile
echo "export HISTFILESIZE=10" >> /etc/profile# 6. 闲置超时600秒
echo "export TMOUT=600" >> /etc/profile
source /etc/profile#----------------------- 第二部分:引导和登录安全 -----------------------
echo ">>> 正在配置引导和登录安全..."# 1. 设置GRUB密码
read -rp "是否为GRUB设置密码?(y/n, 默认n): " grub_choice
if [[ $grub_choice =~ [Yy] ]]; thenecho "请设置GRUB密码:"grub-mkpasswd-pbkdf2 | tee /tmp/grub_hash.txtgrub_hash=$(awk -F': ' '/hash/{print $2}' /tmp/grub_hash.txt)[ -n "$grub_hash" ] && {cat << EOF > /etc/grub.d/40_custom
set superusers="admin"
password_pbkdf2 admin $grub_hash
EOFupdate-grub 2>/dev/null || grub2-mkconfig -o /boot/grub2/grub.cfgecho "GRUB密码已设置!"}
fi# 2. 禁止root登录tty5/tty6
sed -i '/^[^#].*tty5$/s/^/#/' /etc/securetty
sed -i '/^[^#].*tty6$/s/^/#/' /etc/securetty#----------------------- 第三部分:弱口令检测与修复 -----------------------
echo ">>> 正在检测弱口令..."# 1. 安装John the Ripper
if command -v apt &>/dev/null; thenapt install -y john
elif command -v yum &>/dev/null; thenyum install -y epel-releaseyum install -y john
fi# 2. 检测弱口令
unshadow /etc/passwd /etc/shadow > /tmp/passwd.db
echo "正在运行弱口令检测(可能需要时间)..."
john --format=crypt /tmp/passwd.db | tee /tmp/weak_passwords.txt
echo "检测结果已保存至:/tmp/weak_passwords.txt"# 3. 密码复杂度配置
echo "配置密码复杂度策略..."
if [ -f /etc/security/pwquality.conf ]; thensed -i 's/^# minlen =.*/minlen = 12/' /etc/security/pwquality.confsed -i 's/^# minclass =.*/minclass = 3/' /etc/security/pwquality.conf
fi#----------------------- 第四部分:其他安全加固 -----------------------
echo ">>> 正在执行其他安全加固..."# 1. SSH加固
echo "配置SSH安全策略..."
sshd_config="/etc/ssh/sshd_config"
cp $sshd_config $sshd_config.bak
sed -i 's/^#PermitRootLogin.*/PermitRootLogin no/' $sshd_config
sed -i 's/^PasswordAuthentication.*/PasswordAuthentication no/' $sshd_config
systemctl restart sshd# 2. 防火墙配置
if command -v ufw &>/dev/null; thenufw enable
elif command -v firewall-cmd &>/dev/null; thensystemctl start firewalldfirewall-cmd --reload
fi# 3. 系统更新
echo "正在更新系统..."
if command -v apt &>/dev/null; thenapt update && apt upgrade -y
elif command -v yum &>/dev/null; thenyum update -y
fi#----------------------- 完成提示 -----------------------
echo "安全加固已完成!请执行以下操作验证:"
echo "1. 重启服务器检查GRUB密码是否生效"
echo "2. 检查/etc/securetty是否已禁用tty5/tty6"
echo "3. 检查弱口令检测结果并手动重置密码:/tmp/weak_passwords.txt"
echo "4. 测试SSH密钥登录是否正常"
echo "详细日志请查看:$LOG_FILE"


http://www.mrgr.cn/news/96726.html

相关文章:

  • SSH服务
  • 增加等IO状态的唤醒堆栈打印及缺页异常导致iowait分析
  • 设计模式 三、结构型设计模式
  • CMD(命令提示符)、PowerShell 和 Windows Terminal
  • C++练习3
  • ZGC 参数优化与 GC 触发机制解析分享
  • cpu下安装MinerU进行数据清洗
  • Linux centos 7 常用服务器搭建
  • 解决 CMS Old GC 频繁触发线上问题技术方案
  • Spring Boot向Vue发送消息通过WebSocket实现通信
  • 初学STM32系统时钟设置
  • 【SpringBoot + MyBatis + MySQL + Thymeleaf 的使用】
  • Linux基础入门指南:用户管理、基本指令(一)
  • QT 非空指针 软件奔溃
  • RAG优化:python从零实现Proposition Chunking[命题分块]让 RAG不再“断章取义”,从此“言之有物”!
  • SpringIoC和DI
  • Sink Token
  • Day3 蓝桥杯省赛冲刺精炼刷题 —— 排序算法与贪心思维
  • Redis 6.2.6 生产环境单机配置详解redis.conf
  • 深入解析拓扑排序:算法与实现细节