用一个shell脚本完成5项任务。实现一键安装Nginx服务。Ubuntu 22.04、rocky 9.0、Debian 11、centos 7.9、almalinux 同时都能支持的脚本。希望对你有启发。
脚本目标任务:
1,运行脚本可以显示出本机的ip地址
2,如果ip地址中有3这个数字,那么就打印出当前的系统时间
3,如果ip地址中不含3这个数字,就批量建立用户dashu_00, dashu_01, ... dashu_100并且所有用户同属于dashu组;
4,打印出/etc/passwd这个文件中可以登陆的用户(非/usr/sbin/nologin)
5,yum安装nginx服务,并且启动该服务
6,以上所有任务在一个脚本完成
#!/bin/bash
if [[ "$EUID" -ne 0 ]]; then
echo "pls use superuser to run the bash."
exit
fi
if grep -qs "ubuntu" /etc/os-release; then
os="ubuntu"
elif [[ -e /etc/debian_version ]]; then
os="debian"
elif [[ -e /etc/almalinux-release || -e /etc/rocky-release || -e /etc/centos-release ]]; then
os="centos"
else
echo "this installer is only for ubuntu or debian or centos system. bye"
exit
fi
ip=$(ip -4 addr | grep inet | grep -vE '127(\.[0-9]{1,3}){3}' | cut -d'/' -f 1 | grep -oE '[0-9]{1,3}(\.[0-9]{1,3}){3}')
echo "what ip of the current system is: "
echo $ip
if [[ "$ip" =~ '3' ]]; then
echo "Time right now is: $(date +%F' '%T)"
else
echo "there is no 3 in $ip"
echo "we got another task as below"
if [[ ! -e /data/test/dashu.log ]]; then
mkdir -p /data/test
touch /data/test/dashu.log
fi
groupadd dashu 2>/dev/null
for i in {01..100}; do
useradd dashu_$i -g dashu 2>/dev/null
PASS=$(cat /dev/urandom | tr -dc '[:alnum:]' | head -c12)
echo $PASS | passwd --stdin dashu_$i &> /dev/null
echo dashu_$i:$PASS >> /data/test/dashu.log &> /dev/null
done
echo "User dashu_01~dashu_100 has been created."
fi
echo "Below is who can login( without /sbin/nologin )"
echo $(grep -v 'sbin/nologin' /etc/passwd | cut -d : -f 1)
echo "Here now we are going to install Nginx, without your permission of course."
if [[ "$os" = "debian" ]]; then
apt update
apt install -y nginx
elif [[ "$os" = "ubuntu" ]]; then
apt update
export DEBIAN_FRONTEND=noninteractive
apt-get install -y nginx
else
yum install -y yum-utils
if [[ ! -e /etc/yum.repos.d/nginx.repo ]]; then
touch /etc/yum.repos.d/nginx.repo
fi
echo '[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true' > /etc/yum.repos.d/nginx.repo
yum install -y nginx
fi
echo "Nginx has been installed!"
echo $(nginx -v)
echo "Nginx is now to be loaded."
echo $(systemctl start nginx)
ps -ef | grep nginx
echo "\nall is well. bye~"
测试执行情况:rocky9.0、Debian11、Ubuntu2204均能通过。
TODO:自己在准备环境的时候,发现经常忘记配VMware虚拟机的dns,导致脚本最开始的时候一直跑不通。所以考虑后续加一个网络连通性检测。如果是断网状态,直接宣告退出。
TODO:目前只针对各发行版的最新版,对低版本没有做兼容测试。后续可以纳入考虑范围。