首页 > 系统相关 >shell实例

shell实例

时间:2024-10-06 16:00:42浏览次数:1  
标签:shell name text data 实例 nodes type id

1.显示系统一些基本信息 可以将该脚本加入到开机自启动里面,这样开机就会输出基本信息 #!/bin/bash info(){ system=$(hostnamectl | grep System | awk '{print $3}') kernel_release=$(hostnamectl | grep Kernel | awk -F : '{print $2}') Virtualization=$(hostnamectl | grep Virtualization | awk '{print $2}') server_name=$(hostname) ipaddr=$(hostname -I) echo "当前系统版本是:${system}" echo "当前系统内核是:${kernel_release}" echo "当前虚拟平台是:${Virtualization}" echo "当前主机名是:${server_name}" echo "当前ip地址:${ipaddr}" } checkerrror(){ error_info=$(dmesg | grep error) if [ ! -e ${error_info} ] then echo "无错误日志!" else echo ${error_info} fi } info checkerrror 2.关闭系统防火墙和SELinux 检查防火墙状态,是否安装防火墙,如果安装则关闭、关闭SELinux、清空iptables规则 #!/bin/bash close_firewalld(){ code=$(systemctl status firewalld) if [ ${code} -eq 0 ] then systemctl stop firewalld fi } close_selinux(){ sed -i '/^SELINUX/s/=./=disabled/' /etc/selinux/config setenforce 0 } close_iptables(){ iptables -F service iptables save service iptables restart } close_firewalld close_selinux close_iptables 3.定时任务计划:归档备份 打包压缩/var/log/nginx目录下所有内容,存放在/tmp/nginx目录里 压缩文件命名规范:yymmdd_logs.tar.gz,只保存七天内的文件,超过七天的文件会进行清理 #!bin/bash date="$(date +%Y%m%d)" dir='/tmp/nginx' backupfile='_logs.tar.gz' #查看/tmp/nginx是否存在,不存在则创建 checkbak(){ if [ ! -e ${dir} ] then mkdir ${dir} fi } #压缩文件 backup(){ tar -zcvf ${dir}/${date}${backupfile} /var/log/nginx/ > /dev/null 2>&1 echo "${backupfile} Compressed and packaged successfully !" } #清除七天过期文件 cleanup(){ find ${dir} -type f -mtime +7 | xagrs rm -rf if [ $? -eq 0 ] then echo "Cleaned up successfully!" else echo "data cleaning failed error, please pay attention in time" fi } checkbak backup cleanup 4.自动批量创建用户 批量创建user1、user2、user3..... #!/bin/bash #检查用户是否存在,不存在则创建 checkuser(){ for i in $(seq 1 20) do id user${i} > /dev/null 2>&1 if [ $? -eq 0 ] then echo "user${i} 已存在!" else useradd user${i} && echo "user${i}" | passwd --stdin user${i} > /dev/null 2>&1 fi done } checkuser 5.通过位置参数创建用户 $1 是执行脚本的第一个参数 $2 是执行脚本的第二个参数 #!/bin/bash checkuser(){ id ${1} > /dev/null 2>&1 if [ $? -eq 0 ] then echo "${1} 已存在!" else useradd "$1" echo "$2" | passwd ‐‐stdin "$1" fi } 6.批量删除用户 批量删除user1...user20 #!/bin/bash #检查用户是否存在,存在则删除 checkuser(){ for i in $(seq 1 20) do id user${i} > /dev/null 2>&1 if [ $? -eq 0 ] then userdel -r user${i} else echo "user${i} 不存在!" fi done } checkuser 7.更新系统时间,并写入硬件时间里 查看是否安装ntpdate工具 创建上海时区文件的软链接 更新时间并写入到硬件时间里 #!/bin/bash package="ntpdate" info=$(rpm -q ${package}) check_pkgs(){ if [ -e ${info} ] then echo "ntpdate already exists!" else echo "start installation!" yum clean all > /dev/null 2>&1 fi yum update -y && yum install -y ${package} > /dev/null 2>&1 fi } modify_time(){ echo "开始修改时间" rm -rf /etc/localtime && ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime /usr/sbin/ntpdate cn.pool.ntp.org > /dev/null 2>&1 && hwclock -w } check_pkgs modify_time 8.检查服务运行状态 检查某一服务是否正常运行,执行脚本的时候第一个参数为服务名 #!/bin/bash result=$(pidof $1 | wc -l) #echo ${result} if [ ${result} -eq 0 ] then echo "service does not exist !" else echo "Service is running normally !" fi 9.对目标主机进行心跳检测 ping目标主机看是否ping得通,三次ping通表示主机正常运行 将目标主机的ip地址作为第一个参数传进去 #!/bin/bash ipaddr=$1 echo ${ipaddr} ping_status(){ if ping -c 1 ${ipaddr} > /dev/null 2>&1 then echo "ping ${ipaddr} is successful!" continue fi } for i in $(seq 1 3) do ping_status echo "ping ${ipaddr} is failure!" done 进阶版:对ip地址池里的主机分别进行心跳检测 ipaddr=(192.168.149.131 192.168.149.130 192.168.149.132 192.168.149.133) for i in ${ipaddr[]} do echo ".... begin to ping ${i} ....." if ping -c 3 ${i} > /dev/null 2>&1 then echo "ping ${i} is successful!" else echo "ping ${i} is failure!" fi done 10.系统磁盘内存容量告警 根分区剩余空间小于20%(即使用空间大于80%) 输出告警信息 内存使用空间大于80% 输出告警信息 配合crond每5分钟检查一次 #!/bin/bash disk_letfspace=$(df -Th | grep -w / | awk '{print$6}' | cut -d % -f 1) mem_used=$(free -m | grep Mem | awk '{print$3}') mem_total=$(free -m | grep Mem | awk '{print$2}') mem_letfspace=$[${mem_used}*100/${mem_total}] if [ ${disk_letfspace} -gt 80 ] #-gt大于 then echo "Disk free space is less than 20%!" else echo "${disk_letfspace}% of disk space left" fi if [ ${mem_letfspace} -gt 80 ] then echo "memory space is less than 20%!" else echo "${mem_letfspace}% of memory space left" fi # 添加定时任务 crontab -l */5 * * * * /root/check_space.sh 11.操作系统信息提取 #!/bin/bash #清除屏幕信息 clear if [[ $# -eq 0 ]] then #系统类型 os=$(uname -o) echo "Operating System Type:" $os #系统版本和名字 os_name=$(cat /etc/issue | grep -e "Server") echo "Check OS Release Version and Name:" $os_name #cpu架构信息 architecture=$(uname -m) echo "Check Architecture:" $architecture #操作系统内核版本 kernerrelease=$(uname -r) echo "Check Knerner release:" $kernerrelease #主机名 hostname=$(uname -n) echo "Check Hostname:" $hostname #内网ip internelip=$(hostname -I) echo "Check Internel ip" $internalip #公网ip externalip=$(curl -s http://ipecho.net/plain) echo "Check External ip:" $externalip #dns信息 nameservers=$(cat /etc/resolv.conf | grep -E "<nameserver[ ]+" |awk '{print $NF}') echo "Check DNS:" $nameservers #是否已连接到Internet ping -c 2 baidu.com &>/dev/null && echo "Internet:Connectd" || echo "Internet:Disconnected" #检查用户登录数 who>/tmp/who echo "Logged In Users" && cat /tmp/who rm -f /tmp/who ############################# #操作系统运行状态 #系统使用内存=Total-Free #应用使用内存=Total-(Free+Cached+Buffers) system_mem_usages=$(awk '/MemTotal/{total=$2}/MemFree/{free=$2}END{print (total-free)/1024}' /proc/meminfo) echo "system memuserages " $system_mem_usages app_mem_usages=$(awk '/MemTotal/{total=$2}/MemFree/{free=$2}/^Cache/{caches=$2}/Buffers/{buffers=$2}END{print (total-free-cached-buffers)/1024}' /proc/meminfo) echo "apps memuserages " $app_mem_usages #cpu负载 loadaverage=$(top -n 1 -b | grep "load average:" | awk '{print $11 $12 $13}') echo "load averages" $loadaverage #磁盘使用量 diskaverage=$(df -h | grep -vE 'Filesystem|tmpfs' | awk '{print $1 " " $5}') echo "disk averages " $diskaverage fi 12.第三方服务监控 #!/bin/bash Nginxserver="http://192.168.47.128/nginx_status" Check_Nginx_Server() { Status_code=$(curl -m 5 -s -w %{http_code} ${Nginxserver} -o /dev/null) if [ $Status_code -eq 000 -o $Status_code -ge 500 ];then echo -e "Check http server erro,Response status code is" $Status_code else Http_content=$(curl -s ${Nginxserver}) echo -e "Check http server ok!\n" $Http_content fi } Check_Nginx_Server 13.收集内核信息 #! /bin/bash main() { if [ ! "ls -A /usr/src/" == "" ];then mkdir kernel_header cp -rf /usr/src/ kernel_header > /dev/null 2>&1 && echo "collect kernel headers done" cp /etc/release kernel_header > /dev/null 2>&1 && echo "collect release version done" uname -a >>"kernel_header/uname" 2>&1 uname -r >>"kernel_header/uname" 2>&1 uname -m >>"kernel_header/uname" 2>&1 echo "collect uname version done" which dpkg >> "kernel_header/package" 2>&1 which apt >> "kernel_header/package" 2>&1 which rpm >> "kernel_header/package" 2>&1 which yum >> "kernel_header/package" 2>&1 echo "collect package manager done" tar zcf kernel_header.tar.gz kernel_header --remove-files echo "collect kernel header success, please copy $(pwd)/kernel_header.tar.gz" else echo "/usr/src is empty, collect kernel header failed!" fi } main 14. 复制命令及其依赖到指定目录 #!/bin/bash ################### 变量声明 ################### #如果用户没有输入目标路径,将使用如下路径 DIR=/mnt/tmp #提示信息 prompt_1="Pls run as root user" prompt_2="路径名不能是/根目录,已将文件拷贝到默认路径" prompt_3="输入的命令名不正确,或者输入了多个命令名,请重新输入一个命令名" prompt_4="只能使用一个路径且不能是/根目录或包含空格,已将文件拷贝到默认路径" prompt_5="只能输入一个命令名,不能包含空格" ################### 函数 ################### #. /etc/init.d/functions #复制命令 cpcmd(){ local cmdpath=$2$(dirname which --skip-alias $1) [ -d $cmdpath ] || mkdir -p $cmdpath cp -a which --skip-alias $1 $cmdpath [ $? -eq 0 ] && action "$1 finish copy" true || action "$1 finish copy" false } #复制库 cplib(){ local libs=$(ldd which --skip-alias $1| egrep -o "/[^ ]+") for i in $libs;do local libpath=dirname $i [ -d $2$libpath ] || mkdir -p $2$libpath cp $i ${2}${libpath} done [ $? -eq 0 ] && action "$1's dependent libs finish copy" true || action "$1's dependent libs finish copy" false } ############### 主体部分 ############### #判断是否是管理员 [ $UID -ne 0 ] && { echo "$prompt_1"; exit; } #如果命令行没有传参,提示用户重新输入 flag=0 while [ $flag -ne 1 ]; do if [ $# -eq 2 ];then which --skip-alias $1 &>/dev/null [ $? -ne 0 ] && { echo -e "\033[1;33mUsage: $0 [CMD] [PATH]\033[0m";exit 1; } cmd=$1 #判断输入的路径是否是根目录 path=$2 [ "$path" == "/" ] && { path=$DIR;echo -e "\033[1;33m${prompt_2}$DIR \033[0m"; } flag=1 else #1.提示用户输入命令名 while : ; do read -p "请输入需要拷贝的命令(quit退出) " cmd [[ "$cmd" == " " ]] && { echo -e "\033[1;33m$prompt_5\033[0m"; continue; } #判断用户输入的是否是quit,是则退出 tmp=${cmd^^} [ "$tmp" == "QUIT" ] && exit which --skip-alias $cmd &>/dev/null [ $? -eq 0 ] && break echo -e "\a\033[1;31m${prompt_3}\033[0m" done #2.提示用户输入目标路径(默认路径$DIR): read -p "请输入需要拷贝的目标路径(默认路径$DIR): " path [ "$path" == "/" ] || [[ "$path" == " " ]] && { path=$DIR;echo -e "\033[1;33m${prompt_4}$DIR \033[0m"; } path=${path:=$DIR} [ -d $path ] || mkdir -p $path fi #3.拷贝命令到指定目录 cpcmd $cmd $path #4.拷贝函数到指定目录 cplib $cmd $path done 15.重启脚本(指定重启次数和间隔时间) #!/bin/bash rootPWD="testpass" logFile=$PWD/reboot.log inputSTR[0]="#!/bin/bash" inputSTR[1]="source /opt/times.left" inputSTR[2]="rm -rf /opt/times.left" inputSTR[3]="if [ ${timesLeft} -gt '0' ];then" inputSTR[4]=" echo "还剩余${timesLeft}次重启。" >> ${logFile}" inputSTR[5]=" date >> ${logFile}" inputSTR[6]=" echo >> ${logFile}" inputSTR[7]=" echo "timesLeft=$((timesLeft-1))" > /opt/times.left" inputSTR[8]=" reboot" inputSTR[9]="else" inputSTR[10]=" sed -i '/./rbt.sh/d' /etc/crontab" inputSTR[11]=" rm -rf /opt/rbt.sh" inputSTR[12]=" chown ${USER}:${USER} ${logFile}" inputSTR[13]="fi" echo -n -e "请输入自动重启的次数:\t" read timesLeft echo "timesLeft=${timesLeft}" > $PWD/times.left echo ${rootPWD} | sudo -S mv $PWD/times.left /opt/times.left &> /dev/null echo -n -e "请输入重启间隔的时间(分钟):\t" read interval echo -e "Checking necessary files for auto rebooting ..." if [ ! -f /opt/rbt.sh ];then for ((i=0; i<${#inputSTR[@]}; i++)) do echo ${inputSTR[$i]} >> $PWD/rbt.sh done echo ${rootPWD} | sudo -S mv $PWD/rbt.sh /opt/rbt.sh echo ${rootPWD} | sudo -S chown root:root /opt/rbt.sh echo ${rootPWD} | sudo -S chmod a+x /opt/rbt.sh fi echo -e "\e[1;32m[ REBOOT SCRIPT OK]\e[0m" oldIFS=$IFS IFS=$'\n' cfgOK=$(cat /etc/crontab | grep "./rbt.sh") if [ ! ${cfgOK} ];then echo ${rootPWD} | sudo -S sed -i "$a*/${interval:=2} * * * * root cd /opt && ./rbt.sh" /etc/crontab fi IFS=$oldIFS echo -e "\e[1;32m[CRONTAB CONFIG OK]\e[0m" echo -n "请稍候,系统即将重启中……" read   16.关机、重启、待机、休眠测试 #!/bin/bash uid=echo "$UID"; if [ $uid -ne 0 ];then zenity --info --text="该程序每次以ROOT身份执行"; exit; fi; SHUTDOWN="关机测试"; REBOOT="重启测试"; SUSPEND="待机测试"; SLEEP="休眠测试"; echo logname >/tmp/lognames; usrname=cat /tmp/lognames; echo "chmod 666 /sys/class/rtc/rtc0/wakealarm " >> /etc/rc.local; SELECTION=zenity --list --radiolist --title="测试工具" --text="选择您想操作的一项功能" --column "" --column "请您选择" True "$SHUTDOWN" Fasle "$REBOOT" Fasle "$SUSPEND" Fasle "$SLEEP" if [ -e $SELECTION ] ; then exit; fi if [ "$SELECTION" = "$SHUTDOWN" ] ;then echo -e -n "[daemon]\n TimedLoginEnable=true\n TimedLogin=$usrname\n TimedLoginDelay=0">>/etc/gdm/custom.conf; chmod 666 /etc/gdm/custom.conf; TestNo=zenity --entry --text="请您输入需要关机测试的次数"; if [ -e $TestNo ] ;then exit fi echo $TestNo > /tmp/LogBootNo; chmod 666 /tmp/LogBootNo; echo "BootReplace.sh" >>/etc/rc.local; BootTest.sh; fi if [ "$SELECTION" = "$REBOOT" ]; then echo -e -n "[daemon]\n TimedLoginEnable=true\n TimedLogin=$usrname\n TimedLoginDelay=0">>/etc/gdm/custom.conf; chmod 666 /etc/gdm/custom.conf; TestNo=zenity --entry --text="请您输入需要重启测试的次数"; if [ -e $TestNo ] ;then exit fi echo $TestNo > /tmp/LogRebootNo; chmod 666 /tmp/LogRebootNo; echo "RebootReplace.sh" >>/etc/rc.local; RebootTest.sh; fi if [ "$SELECTION" = "$SUSPEND" ] ;then TestNo=zenity --entry --text="请您输入需要待机测试的次数"; if [ -e $TestNo ] ;then exit fi echo $TestNo > /tmp/LogSuspendNo; chmod 666 /tmp/LogSuspendNo; SuspendTest.sh; fi #if [ "$SELECTION" = "$SLEEP" ] ;then TestNo=zenity --entry --text="请您输入需要休眠测试的次数"; #if [ -e $TestNo ] ;then exit fi echo $TestNo > /tmp/LogSleepNo; chmod 666 /tmp/LogSleepNo; SleepTest.sh; #fi 17.读取1.txt文本并输出其内容 #!/bin/bash # while语句应用 while read line do echo $line done < 1.txt 18.示例2 #!/bin/sh #xrdp X session start script (c) 2015, 2017 mirabilos #published under The MirOS Licence if test -r /etc/profile; then . /etc/profile fi if test -r /etc/default/locale; then . /etc/default/locale test -z "${LANG+x}" || export LANG test -z "${LANGUAGE+x}" || export LANGUAGE test -z "${LC_ADDRESS+x}" || export LC_ADDRESS test -z "${LC_ALL+x}" || export LC_ALL test -z "${LC_COLLATE+x}" || export LC_COLLATE test -z "${LC_CTYPE+x}" || export LC_CTYPE test -z "${LC_IDENTIFICATION+x}" || export LC_IDENTIFICATION test -z "${LC_MEASUREMENT+x}" || export LC_MEASUREMENT test -z "${LC_MESSAGES+x}" || export LC_MESSAGES test -z "${LC_MONETARY+x}" || export LC_MONETARY test -z "${LC_NAME+x}" || export LC_NAME test -z "${LC_NUMERIC+x}" || export LC_NUMERIC test -z "${LC_PAPER+x}" || export LC_PAPER test -z "${LC_TELEPHONE+x}" || export LC_TELEPHONE test -z "${LC_TIME+x}" || export LC_TIME test -z "${LOCPATH+x}" || export LOCPATH fi if test -r /etc/profile; then . /etc/profile fi test -x /etc/X11/Xsession && exec /etc/X11/Xsession exec /bin/sh /etc/X11/Xsession     19、记录远程登录信息 #!/bin/bash PS1="whoami@hostname:"'[$PWD]' history USER_IP=who -u am i 2>/dev/null| awk '{print $NF}'|sed -e 's/[()]//g' echo $USER_IP if [ "$USER_IP" = "" ] then USER_IP=hostname fi if [ ! -d /tmp/ruige ] then mkdir /tmp/ruige chmod 777 /tmp/ruige fi if [ ! -d /tmp/ruige/${LOGNAME} ] then mkdir /tmp/ruige/${LOGNAME} chmod 300 /tmp/ruige/${LOGNAME} fi export HISTSIZE=4096 DT=date '+%Y:%m:%d %r' export HISTFILE="/tmp/ruige/${LOGNAME}/${USER_IP} ruige.$DT" echo $HISTFILE chmod 600 /tmp/ruige/${LOGNAME}/ruige 2>/dev/null   20、查找/tmp下大于1K的文件,并复制到/tmp1下 #!/bin/bash dir1="/tmp/" for file in `ls $dir1` do if [ -f $dir1$file ];then size1=ls -l $dir1$file|awk -F ' ' '{print $5}' if [ $size1 -gt 102420 ];then cp $dir1$file /tmp1/ fi fi done 或者 find /tmp -siez +1K -exec cp {} /tmp1 \; 补充:如何将目录及子目录下的大于1K文件复制到/tmp1下   21、添加一个新组为 class01,然后,添加属于这个组的 30 个用户,用户名的形式为 stdXX,其中,XX 从 01 到 30 #!/bin/bash usergroup class01 num=$(seq -w 1 1 30) for i in $num do echo $i #useradd std$i -G class01 done 或者 seq -f "std%02g" 1 1 30|useradd -G class01   22、从 a.log 文件中提取包含“WARNING”或”FATAL”,同时不包含“IGNOR”的行,然后提取以“:”分割的第五个字段 grep -E 'WARNING|FATAL' a.log|grep -v 'IGNOR'|awk -F ':' '{print $5}'   23、在每个月的第一天备份并压缩/etc 目录下的所有内容,存放在/root/backup 目录里,且文件名为如下形式 yymmdd_etc,yy 为年,mm 为月,dd 为日。shell 程序 fileback存放在/usr/bin 目录下? cd /usr/bin vim fileback #!/bin/bash cd /root/backup tar -zcf date +%y%m%d"_etc.tgz" /etc   * * 1 * * /usr/bin/fileback >> /var/spool/cron/crontabs/root #写入root用户下的定时任务 24、编写个 shell 脚本将当前目录下大于 10K 的文件转移到/tmp 目录下 #/bin/bash for FileName in ls -l |awk '$5>10240 {print $9}' do mv $FileName /tmp done   定时任务题 某系统管理员需每天做一定的重复工作,请按照下列要求,编制一个解决 方案 : (1)在下午 4 :50 删除/abc 目录下的全部子目录和全部文件; (2)从早 8:00~下午 6:00 每小时读取/xyz 目录下 x1 文件中每行第一个域的全部数据 加入到/backup 目录下的 bak01.txt 文件内; (3)每逢星期一下午 5:50 将/data 目录下的所有目录和文件归档并压缩为文件: backup.tar.gz; (4)在下午 5:55 将 IDE 接口的 CD-ROM 卸载(假设:CD-ROM 的设备名为 hdc); (5)在早晨 8:00 前开机后启动。 参考答案: (1)用 vi 创建编辑一个名为 prgx 的 crontab 文件; prgx 文件的内容: 50 16 * * * rm -r /abc/* (2)、0 8-18/1 * * * cut -f1 /xyz/x1 >> /backup/bak01.txt (3)、50 17 * * * tar zcvf backup.tar.gz /data (4)、55 17 * * * umount /dev/hdc (5)、由超级用户登录,用 crontab 执行 prgx 文件中的内容: root@xxx:#crontab prgx;在每日早晨 8:00 之前开机后即可自动启动 crontab。 =====25、判断输入的文件是否是字符文件 #!/bin/bash read -p "shuru" filename echo $filename if [ -c $filename ];then echo "ok" else echo "no" fi ======26、case流程控制实现apache服务管理 #!/bin/bash # 脚本 加一个参数,通过参数判断 case "$1" in 'start') /usr/sbin/apachectl start ;; 'stop') /usr/sbin/apachectl stop ;; 'restart') /usr/sbin/apachectl restart ;; ) echo "usage $0 start|stop|restart" ;; esac ======27、验证passwdxx⽂件有效性 kylin@kylin-W515:~/桌面$ cat cc root:x:0:0:root:/root:/bin/bash :x:1:1:daemon:/usr/sbin:/usr/sbin/nologin bin::2:2:bin:/bin:/usr/sbin/nologin x:3:3:sys:/dev:/usr/sbin/nologin sync:x:4:65534:sync:/bin:/bin/sync   kylin@kylin-W515:~/桌面$ cat cc | awk -F: '\ #使用:作为分隔符 NF != 7{\ #当域的数量不等于7时,执行下面 #printf打印字符串"line ?? does not have 7 fields",并显⽰该条记录。 printf("line %d,does not have 7 fields:%s\n",NR,$0)} #如果第⼀个域没有包含任何字⺟和数字,printf打印“no alpha and numeric user id" ,并显⽰记录数和记录 $1 !~ /[A-Za-z0-9]/{printf("line %d,non alpha and numeric user id:%s\n",NR,$0)}\ #如果第⼆个域是⼀个星号,就打印字符串“no passwd”,紧跟着显⽰记录数和记录本⾝ $2 == "" {printf("line %d,no password: %s\n",NR,$0)}'   line 2,non alpha and numeric user id::x:1:1:daemon:/usr/sbin:/usr/sbin/nologin line 3,no password: bin::2:2:bin:/bin:/usr/sbin/nologin line 4,does not have 7 fields:x:3:3:sys:/dev:/usr/sbin/nologin   =====判断输入的压缩文件类型,并解压 #!/bin/bash ftype=`file $1` case $ftype in "$1: Zip archive"*) unzip $1;; "$1: gzip compressed"*) gunzip $1;; "$1: bzip2 compressed"*) bunzip2 $1;; *) echo "file $1 can not be uncompressed with smartzip";; esac   =====下载一个包 待完善! 根据用户输入的包名,迷糊匹配apt数据库,将查询结果展示并排序,根据用户输入的数字,选择的包下载 #!/bin/bash #问题:当将apt查询结果保存到变量中后,变量存储的内容行号和回车符改变乐 #根据用户输入的包名,apt查询相关包 read -p "输入包名,可输入关键词进行模糊匹配" pakname list=apt list|grep $pakname list0=head $list -n10|tr ' ' '\n'|grep -E '/'|cut -d/ -f1 echo $list0 read -p "请输入完整包名" pk #获取到包下载地址的前半部分 #text=cat apt policy $pk|grep "500"|grep https|cut -d' ' -f10|sed -n '1p' #获取到包下载地址的后半部分 #text2= cat apt-cache show $pk|grep "Filename:"|sed -n '1p' #下载包 #wget -cP "/tmp" $text$text2 ===== #!/bin/bash #function:一键部署nginx #请以root用户身份执行 systemctl stop firewalld.service systemctl disable firewalld.service sed -i 's/SELINUX=.*/SELINUX=disabled/' /etc/sysconfig/selinux systemctl stop nginx if [ -d /usr/local/nginx ]; then rm -rf /usr/local/nginx fi read -p "部署开始(nginx=1/tengine=2):" App if [ $App -eq 1 ];then echo "开始部署nginx服务...." echo "正在安装依赖包,请稍等...." yum -y install gcc-c++ && yum install -y pcre pcre-devel && yum install -y zlib zlib-devel && yum install -y openssl openssl-devel mkdir /usr/local/nginx && cd /usr/local/nginx useradd -s /sbin/nologin -M nginx echo "正在解压安装包,请稍等...." cd /root tar xvfz nginx-1.18.0.tar.gz echo "正在配置,请稍等...." cd nginx-1.18.0 && ./configure --prefix=/usr/local/nginx/ --user=nginx --group=nginx --with-http_stub_status_module --with-http_ssl_module --with-file-aio --with-http_realip_module --with-stream echo "正在安装服务请稍等..." make && make install /usr/local/nginx/sbin/./nginx -t fi if [ $App -eq 2 ];then echo "开始部署nginx服务...." if [ ! -f /usr/local/BabaSSL/libssl.pc ]; then if [ ! -d /usr/local/src ]; then mkdir /usr/local/src fi cp /root/BabaSSL-master.tar.gz /usr/local/src cd /usr/local/src tar -xzf BabaSSL-master.tar.gz -C /usr/local cd /usr/local/BabaSSL ./config enable-ntls make && make install mkdir /usr/local/nginx && cd /usr/local/nginx echo "正在解压安装包,请稍等...." cd /root tar xvfz tengine-master.tar.gz cd tengine-master && ./configure --prefix=/usr/local/nginx/--user=nginx --group=nginx --add-module=modules/ngx_openssl_ntls --with-openssl=/usr/local/BabaSSL --with-openssl-opt="--strict-warnings enable-ntls" --with-http_ssl_module --with-stream --with-stream_ssl_module --with-stream_sni echo "正在安装服务请稍等..." make && make install /usr/local/nginx/sbin/./nginx -t fi read -p "是否部署服务开机自启(yes=1/no=2):" fw if [ $fw -eq 1 ];then echo "开始部署服务开机自启...." echo " [Unit] Description=nginx After=network.target [Service] Type=forking ExecStart=/usr/local/nginx/sbin/nginx ExecReload=/usr/local/nginx/sbin/nginx -s reload ExecStop=/usr/local/nginx/sbin/nginx -s quit PrivateTmp=true [Install] WantedBy=multi-user.target" > /lib/systemd/system/nginx.service systemctl start nginx.service && systemctl enable nginx.service && systemctl enable nginx.service systemctl status nginx.service echo "服务及开机自启部署成功,请输入ifconfig | grep inet | cut -d " " -f 10 | head -1测试" fi if [ $fw -eq 2 ];then echo "即将开启服务并退出脚本..." echo " [Unit] Description=nginx After=network.target [Service] Type=forking ExecStart=/usr/local/nginx/sbin/nginx ExecReload=/usr/local/nginx/sbin/nginx -s reload ExecStop=/usr/local/nginx/sbin/nginx -s quit PrivateTmp=true [Install] WantedBy=multi-user.target" > /lib/systemd/system/nginx.service systemctl start nginx.service && systemctl disable nginx.service && systemctl disable nginx.service systemctl status nginx.service echo "服务部署成功,请输入ifconfig | grep inet | cut -d " " -f 10 | head -1测试" fi   ===获取当前登录用户及创建新终端下解压 #!/bin/bash #创建容器根 if [ ! -d ~/.cxoffice ];then mkdir ~/.cxoffice fi if [ -d ~/.cxoffice/wecom ];then echo "已存在企业微信容器" exit 0 fi #获取当前登录用户名 U=$(id -u) if [[ $U != 0 ]];then folder=$USER else for folder in ls /home/ do if test -d /home/$folder/.config/ then user_name=who |grep $folder if [[ $user_name != "" ]];then folder=${user_name%%$" "*} #echo $folder break fi fi done fi #解压企业微信容器 if [ ! -f wecom_files.7z ];then echo "脚本需要与wecom_files.7z文件在一个目录下" exit 0 fi #新建一个终端,查看解压进度 mate-terminal -x bash -c "7z x wecom_files.7z -o/home/$folder/.cxoffice;exec bash;"     ===查找baidunetdisk进程,并杀死它 shell脚本 NAME="baidunetdisk" echo $NAME ID=`ps -ef | grep "$NAME" | grep -v "$0" | grep -v "grep" | awk '{print $2}'` echo $ID echo "start kill baidunetdisk" for id in $ID do if [ "$$" = "$id" ];then continue else kill -3 $id fi done echo "baidunetdisk kill finished"

标签:shell,name,text,data,实例,nodes,type,id
From: https://www.cnblogs.com/gpysir/p/18449138

相关文章

  • shell调用expect实现用户创建免密登录
    这是一个用于(批量或者免交互)创建用户免密的shell脚本通过shell的for循环和变量,实现批处理和免交互#!/bin/bashpassword="liwanliang"expect-c"spawnsshliwl@node084expect{\"*yes/no*\"{send\"yes\r\",exp_continue}......
  • xshell配置使用快捷键翻译选种内容
    1.win10安装python我安装的是python3.122.编辑翻译脚本申请百度翻译api的key和appid注意安装相关依赖包:requestswin10toastimportrequestsimportrandomimportjsonfromhashlibimportmd5importsysimportpyperclipfromwin10toastimportToastNotifier#S......
  • GraphQL、sequelize-typescript 、Apollo Server 4 实例
    新建项目文件夹$mkdirdemo$cddemo初始化TypeScript配置$npxtsc--init安装SequelizeSequelize-cli$npminstall--save-dev@types/node@types/validator$npminstallsequelizereflect-metadatasequelize-typescript$npminstall--save-devts-node......
  • Windows Powershell and WSL terminal 路径
    在windowspowershell中访问C,D盘cdC:,cdD:,...:PSC:\Users\phil>cdC:PSC:\Users\phil>pwdPath----C:\Users\philPSC:\Users\phil>在windowspowershell中访问WSL:PSC:\Users\phil>cd\\wsl.localhost\Ubuntu\home\phil\在W......
  • CS3214 Customizable Shell
    CS3214FProject1-“CustomizableShell”DueDate: Seewebsiteforduedate(Latedaysmaybeused.)Thisprojectmustbedoneingroupsof2students.Self-selectedgroupsmusthaveregis-teredusingthegrouperapp(URL).Otherwise,apartnerwillbea......
  • 教你如何免费获取股票数据用python、JavaScript (Node.js)、JAVA等多种语言的实例代码
    ​近一两年来,股票量化分析逐渐受到广泛关注。而作为这一领域的初学者,首先需要面对的挑战就是如何获取全面且准确的股票数据。因为无论是实时交易数据、历史交易记录、财务数据还是基本面信息,这些数据都是我们进行量化分析时不可或缺的宝贵资源。我们的核心任务是从这些数据......
  • 828华为云征文 | 华为云Flexus X实例在混合云环境中的应用与实践
    目录前言1.混合云环境的优势与挑战1.1混合云的优势1.2混合云的挑战2.FlexusX实例的配置与集成2.1FlexusX实例简介2.2FlexusX实例的混合云部署2.3配置步骤与措施3.数据迁移与同步策略3.1数据迁移方案3.2数据同步措施4.安全性与合规性管理4.1混合云......
  • C++入门基础知识91(实例)——实例16【求两数最小公倍数】
    成长路上不孤单......
  • shell脚本常用命令
    常用命令2.1查看脚本执行过程2.2查看脚本是否有语法错误2.3date命令2.3.1显示年、月、日date+%Y-%m-%d   #年(以四位数字格式打印年份)月日date+%y-%m-%d   #年(以两位数字格式打印年份)月日date+%T         #年(以四位数字格式打印年份)月日2.3.2......
  • Shell脚本基础知识-初步版
    本文是笔者研究生期间在阅读《Linux命令行与shell脚本编程大全》之后总结出来的一些重点知识的记录,在此重新整理输出。以便在给上个帖子涉及到的相关知识点进行一下讲解,帮助自己复习shell脚本的首行规范化应该是#!/bin/bash#functiondescription其中第一行必须如此,#后......