[shell] 脚本使用 【记录】-环境初始化脚本整理11-修改网卡名字脚本

1.nginx日志切割

vi /var/log/nginx/cut_nginx_log.sh
#!/bin/bash
date=$(date +%F -d -1day)
cd /var/log/nginx/
if [ ! -d cut ] ; then
        mkdir cut
fi
mv access.log cut/access_$(date +%F -d -1day).log
mv error.log cut/error_$(date +%F -d -1day).log
/usr/sbin/nginx -s reload
tar -jcvf cut/$date.tar.bz2 cut/*
rm -rf cut/access* && rm -rf cut/error*
find -type f -mtime +10 | xargs rm -rf
计划任务加入开机计划任务
cat >>/var/spool/cron/root<<eof
00 00 * * * /bin/sh /var/log/nginx/cut_nginx_log.sh >/dev/null 2>&1
Eof

chmod a+x /var/log/nginx/cut_nginx_log.sh

不记录不需要的访问日志

location ~ .*\.(js|jpg|JPG|jpeg|JPEG|css|bmp|gif|GIF)$ {
    access_log  off;
}

3. 设置访问日志的权限

chown -R root.root /var/log/nginx
chmod -R 700 /var/log/nginx

2.数据库备份脚本记录

vim /etc/my.cnf
最后写入一下内容
[mysqldump]
user=root
password=123456
 
vi databackup.sh
cat databackup.sh
#!/bin/bash
export LANG=en_US.UTF-8
savedir=/var/backup/
cd "$savedir"
time="$(date +"%Y-%m-%d")" 
mysqldump -A > all-"$time".sql
scp all-"$time".sql root@192.168.42.251:/opt/backup/ && rm -rf all-*

数据库上创建导出数据库的文件夹

chmod 700 databackup.sh

mkdir  /var/backup

监控主机上创建备份文件夹

mkdir /opt/backup



3.网站程序备份

cat webbak.sh
#!/bin/bash
time="$(date +"%Y-%m-%d")"
tar -zcf /root/web-"$time".tar.gz /wwwdir
scp /root/web-* root@192.168.42.251:/opt/backup && rm -rf web-*
[root@nfs65 ~]# chmod 700 webbak.sh
[root@nfs65 ~]# sh webbak.sh
tar: Removing leading `/' from member names
web-2018-10-30.tar.gz 

启动任务开启

 crontab -e

30 * * * * /usr/sbin/ntpdate time.nuri.net

0 3 * * * /root/webbak.sh



 4.批量管理主机

[root@xuegod63 ~]# cat ip_pass.txt    #这里写上要执行的IP地址和root用户密码
192.168.1.63  123456
192.168.1.63  123456
192.168.1.63  123456
[root@xuegod63 ~]# cat ssh2.exp   #编写要执行的操作
#!/usr/bin/expect
set ipaddr [lindex $argv 0]
set passwd [lindex $argv 1]
set timeout 30
spawn ssh root@$ipaddr
expect {
"yes/no" { send "yes\r";exp_continue }
"password" { send "$passwd\r" }
}
expect "#"
send "touch /root/xuegod1011.txt\r"
send "ls /etc > /root/xuegod1011.txt\r"
send "mkdir /tmp/xuegod1011\r"
send "exit\r"
expect eof

[root@xuegod63
~]# cat login.sh #开始执行 #!/bin/bash echo for ip in `awk '{print $1}' /root/ip_pass.txt` do pass=`grep $ip /root/ip_pass.txt|awk '{print $2}'` expect /root/ssh.exp $ip $pass done

 

5.cpu监控脚本

#!/bin/bash  
#监控系统cpu的情况脚本程序  
#提取本服务器的IP地址信息  
IP=`ifconfig enp2s0f1 | grep "inet" | grep "broadcast" | awk '{print $2}'`  
#取当前空闲cpu百份比值(只取整数部分)  
cpu_idle=`top -b -n 1 | grep Cpu | awk '{print $8}' | cut -f1 -d "."`
#设置空闲cpu的告警值为20%,如果当前cpu使用超过80%(即剩余小于20%),立即发邮件告警  
if (($cpu_idle < 20)); then  
      echo "$IP服务器cpu剩余$cpu_idle%,使用率已经超过80%,请及时处理。" | mail -s "$IP 服务器CPU告警"  xuegod@xxx.com  
fi
top -b -n 1 | grep Cpu | awk '{print $8}' | cut -f1 -d "."
ifconfig enp2s0f1 | grep "inet" | grep "broadcast" | awk '{print $2}'

本地测试
#!/bin/bash
#监控系统cpu的情况脚本程序
#提取本服务器的IP地址信息
IP=`ifconfig enp2s0f1 | grep "inet" | grep "broadcast" | awk '{print $2}'`
#取当前空闲cpu百份比值(只取整数部分)
cpu_idle=`top -b -n 1 | grep Cpu | awk '{print $8}' | cut -f1 -d "."`
#设置空闲cpu的告警值为20%,如果当前cpu使用超过80%(即剩余小于20%),立即发邮件告警
if (($cpu_idle < 99)); then
      echo "$IP服务器cpu剩余$cpu_idle%,使用率已经超过80%,请及时处理。" > b.txt
fi


vi cpu.sh
chmod a+x cpu.sh
sh cpu.sh

top 参数n b
n 设置退出前屏幕刷新的次数
b 将top输出编排成适合输出到文件的格式,可以使用这个选项创建进程日志

 6.服务器资源查看

#!/bin/bash
date;
echo "uptime:"
uptime
echo "Currently connected:"
w
echo "--------------------"
echo "Last logins:"
last -a |head -3
echo "--------------------"
echo "Disk and memory usage:"
df -h | xargs | awk '{print "Free/total disk: " $11 " / " $9}'
free -m | xargs | awk '{print "Free/total memory: " $10 " / " $8 " MB"}'
echo "--------------------"
echo "Utilization and most expensive processes:"
top -b |head -3
echo
top -b |head -10 |tail -4
#echo "--------------------"
#echo "Open TCP ports:"
#nmap -p- -T4 127.0.0.1

echo "--------------------"
echo "Current connections:"
ss -s
echo "--------------------"
echo "processes:"
ps auxf --width=20
echo "--------------------"
echo "vmstat:"
vmstat 1 5

 7.日志备份脚本

[root@xuegod63 ~]# vim log-back.sh
#!/bin/sh
SRC_DIR=/var/log/
DES_DIR=/opt/backup/`date +%Y%m%d`
if
[ ! -d  $DES_DIR ] ; then
        mkdir -p $DES_DIR
fi
for i in  `find  $SRC_DIR  -name "*.log"`
do
        tar  czf  $i.tgz  $i
done
mv /var/log/*.tgz $DES_DIR
ls -lh $DES_DIR
echo "The scripts exec end, Files tar successfully !"

 

8.免密批量执行

1.安装免互交程序
yum install expect -y


2. vi mian.sh
#!/bin/bash #------------------------------------------# # FileName: 自动批量免密登陆 # Revision: 5.1.0 # Date: 2018-10-14 04:50:33 # Author: vinsent # Email: 37705109@qq.com # Description: This script can achieve ssh password-free login, # and can be deployed in batches, configuration #------------------------------------------# # Copyright: 2018 vinsent # License: GPL 3+ #------------------------------------------# [ ! -f /root/.ssh/id_rsa.pub ] && ssh-keygen -t rsa -p '' &>/dev/null # 密钥对不存在则创建密钥 while read line;do ip=`echo $line | cut -d " " -f1` # 提取文件中的ip user_name=`echo $line | cut -d " " -f2` # 提取文件中的用户名 pass_word=`echo $line | cut -d " " -f3` # 提取文件中的密码 expect <<EOF spawn ssh-copy-id -i /root/.ssh/id_rsa.pub $user_name@$ip expect { "yes/no" { send "yes\n";exp_continue} "password" { send "$pass_word\n"} } expect eof EOF done < /opt/ip.txt

3. vi /opt/ip.txt

192.168.1.64 root 123456

 9.批量ping服务器脚本

[root@yysslopenvpn01 ~]# cat hostip.txt
192.168.130.1
192.168.130.2
192.168.130.3
192.168.130.4
192.168.130.5
192.168.130.6
192.168.130.7

vi shell_ping.sh
 
#!/bin/sh
 for i in `cat hostip.txt`
 do
 ping -c 4 $i|grep -q 'ttl=' && echo "$i ok" || echo "$i failed"
 done

chmod +x shell_ping.sh
sh shell_ping.sh

 

第二种批量ping代码

vi ping.sh

#!/bin/bash
i=1
for (( i=1;i<10;i++ ))
do
ping -c 3 192.168.1.$i &> /dev/null
if [ $? -ne 0 ];then
echo 192.168.1.$i is shutdown
fi
done

 

10.脚本思路

mysql自动化备份脚本:
思路:
1、检查一下运行环境: 目录是否存在,时间,权限,用户
2、运行要执行的命令:备份,导出数据。。。
3、把命令执行过程中的没有用的文件删除一下
4、弹出命令运行成功的消息

/usr/bin/mysqldump -u$MYSQLUSR -p$MYSQLPW $MYSQLDB > $BAKDIR/${MYSQLDB}_db.sql
cd $BAKDIR ; tar -czf ${MYSQLDB}_db.tar.gz *.sql


[ $? -eq 0 ] && echo “This `date +%Y-%m-%d` MySQL BACKUP is SUCCESS”
cd /data/backup/mysql/ && find . -type d -mtime +30 |xargs rm -rf
echo "The mysql backup successfully "

 

日志备份思路

1.定义目录变量一个日志目录 一个备份目录
2.tar czf $i.tgz /var/log
3.查找日志目录4天前的文件

 

[root@xuegod63 ~]# vim /etc/init.d/nginx    
#!/bin/bash
#chkconfig: 2345 80 90
#description:nginx run

# nginx启动脚本
# @author    Devil
# @version    0.0.1
# @date        2018-05-29

PATH=/data/soft/nginx
DESC="nginx daemon"
NAME=nginx
DAEMON=$PATH/sbin/$NAME   #/data/soft/nginx/sbin/nginx
CONFIGFILE=$PATH/$NAME.conf
PIDFILE=$PATH/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME
[ -x "$DAEMON" ] || exit 0
do_start()
{
    $DAEMON -c $CONFIGFILE || echo -n "nginx already running"
}
do_stop()
{
    $DAEMON -s stop || echo -n "nginx not running"
}
do_reload()
{
    $DAEMON -s reload || echo -n "nginx can't reload"
}
case "$1" in
    start)
        echo -n "Starting $DESC: $NAME"
        do_start
        echo "."
    ;;
    stop)
        echo -n "Stopping $DESC: $NAME"
        do_stop
        echo "."
    ;;
    reload|graceful)
        echo -n "Reloading $DESC configuration..."
        do_reload
        echo "."
    ;;
    restart)
        echo -n "Restarting $DESC: $NAME"
        do_stop
        do_start
        echo "."
    ;;
    *)
        echo "Usage: $SCRIPTNAME {start|stop|reload|restart}" >&2
        exit 3
    ;;
esac
exit 0


chkconfig --add /etc/init.d/nginx

chkconfig --list

service nginx start

[root@client tmp]# cat road1.sh

#!/bin/env bash

read -p "路径:" l

if [ -L $l ];then

        echo "链接文件"

        if [ -e $l ];then

                echo "有效链接文件"

        else

                echo "无效的链接文件"

        fi

else

        if [ -d $l ];then

                echo "目录"

        elif [ -f $l ];then

                echo "文件"

        elif [ -e $l ];then

                echo "文件存在"

        else

                echo "文件不存在"

        fi

fi

 

11.环境初始化脚本-

#!/bin/bash
# Optimize the system after installation
PASSWD=123456
NETIP=192.168.1.63
NETGATWAY=192.168.1.1
PROTOBOOT=none
HOSTNAME=zsl.cn
DNS1=8.8.8.8
NTPSERVER=ntp1.aliyun.com
YUMREPO=http://mirrors.aliyun.com/repo/Centos-7.repo
EPELREPO=http://mirrors.aliyun.com/repo/epel-7.repo
SSH_PORT=10024
eth0=ens33

# in case of some bad behaviours
CHATTR=chenhao
# Open the port for iptabeles input or maybe stop iptables
PORTS=80,22,21,8088
# record the system user,ip addresse,shell command and detail
HISTDIR=/usr/etc/.history
 
# the welcome info
cat << EOF
+------------------------------------------------------------------+
|     **********  Welcome to CentOS 7.x System init  **********    |
+------------------------------------------------------------------+
EOF
[ `whoami` != "root" ] && echo "please use root" && exit 1
function format() {
    echo -e "\033[32m Success!!!\033[0m\n"
    echo "#########################################################"
}
 
###change the root passwd
echo "set root passwd"
echo $PASSWD | passwd root --stdin &> /dev/null
format
 
###change network setting
# sed -i "s/\$releasever/${RHEL_Ver}/g" --替换写法
cat > /etc/sysconfig/network-scripts/ifcfg-$eth0 << EOF
TYPE=Ethernet
BOOTPROTO=none
NAME=$eth0
DEVICE=$eth0
ONBOOT=yes
IPADDR=$NETIP
PREFIX=24
GATEWAY=$NETGATWAY
DNS1=8.8.8.8
EOF
systemctl restart network
format


 
###change the hostname
echo "set hostname"
hostname $HOSTNAME && echo "$HOSTNAME" > /etc/hostname
format
 
###change the dns
echo "set DNS"
echo "" > /etc/resolv.conf    
echo "nameserver $DNS1" > /etc/resolv.conf
#echo "nameserver $DNS2" >> /etc/resolv.conf
ping -c 3 www.baidu.com &> /dev/null || echo "Network is unreachable" || exit 3
format
 
###diable selinux
echo "disable selinux"
[ `getenforce` != "Disabled" ] && setenforce 0 &> /dev/null && sed -i s/"^SELINUX=.*$"/"SELINUX=disabled"/g /etc/sysconfig/selinux
format
# echo "/dev/cdrom /mnt iso9660 defaults 0 0" >> /etc/fstab
mount -a
###update yum repo
echo "set yum mirrors"
rm -rf /etc/yum.repos.d/*
curl -o /etc/yum.repos.d/CentOS-Base.repo $YUMREPO &> /dev/null
curl -o /etc/yum.repos.d/epel.repo $EPELREPO &> /dev/null
yum clean all &> /dev/null && yum makecache &> /dev/null
format
 
###install the basic command
yum install vim wget openssl-devel ntpdate make gcc-c++  ncurses-devel net-snmp sysstat lrzsz zip unzip tree net-tools lftp -y
#yum -y groupinstall "Development Tools" "Server Platform Development" &> /dev/null
format
 

###character set
echo "set LANG"
#sed -i s/"^LANG=.*$"/"LANG=zh_CN.UTF-8"/ /etc/locale.conf
#source /etc/locale.conf
 
###update timezone
echo "set ntptime"
rm /etc/localtime
ln -vs /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
yum install ntpdate -y
ntpdate $NTPSERVER &> /dev/null
echo "*/5 * * * * /usr/sbin/ntpdate $NTPSERVER  &>/dev/null" >> /etc/crontab
hwclock -w
format
  
###show the system info
echo "Set login message."
echo "This is Product Server" > /etc/issue
format
 
###iptables setting
echo "set iptables"
systemctl stop firewalld &&  systemctl disable firewalld

format
iptables -F
#iptables -A INPUT -p tcp -m multiport --dports $SSH_PORT,$PORTS -j ACCEPT
#iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
#iptables -A INPUT -i lo -j ACCEPT
#iptables -A OUTPUT -m state --state NEW,ESTABLISHED -j ACCEPT
#iptables -P INPUT DROP
#iptables -P FORWARD DROP
#iptables -P OUTPUT ACCEPT
#service iptables save &> /dev/null
echo " 内核优化"
cat > /etc/sysctl.conf << EOF

# 前三个,一般只要是服务器都会配,唯独数据库除外设定
net.ipv4.tcp_synack_retries = 0
net.ipv4.tcp_syn_retries = 1
net.ipv4.tcp_max_syn_backlog = 20480
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_fin_timeout = 10
fs.file-max = 819200
net.core.somaxconn = 65536
net.core.rmem_max = 1024123000
net.core.wmem_max = 16777126
net.core.netdev_max_backlog = 165536
net.ipv4.ip_local_port_range = 10000 65535
EOF

sysctl -p
format

echo " 打开数优化 用户打开数优化"
ulimit -n 65536
echo "* soft nofile 65536" >> /etc/security/limits.conf
echo "* hard nofile 65536" >> /etc/security/limits.conf
cat > /etc/security/limits.d/20-nproc.conf << EOF

* soft nproc 66666
* hard nproc 66666
root       soft    nproc     unlimited
EOF
format
 
# reboot the system after setting
reboot

 12.网卡名字修改脚本

#!/bin/bash
NETIP=192.168.100.211
NETGATWAY=192.168.100.1
# 用不到HOSTNAME=dockercang.cn
DNS1=8.8.8.8
ethold=ens33

cat << EOF
+------------------------------------------------------------------+
|     **********  Welcome to CentOS 7.x Rename Network  **********    |
+------------------------------------------------------------------+
EOF
[ `whoami` != "root" ] && echo "please use root" && exit 1
function format() {
    echo -e "\033[32m Success!!!\033[0m\n"
    echo "#########################################################"
}

echo "修改配置文件"
rm -rf /etc/sysconfig/network-scripts/ifcfg-$ethold
cat > /etc/sysconfig/network-scripts/ifcfg-eth0 << EOF
TYPE=Ethernet
BOOTPROTO=none
NAME=eth0
DEVICE=eth0
ONBOOT=yes
IPADDR=$NETIP
PREFIX=24
GATEWAY=$NETGATWAY
DNS1=$DNS1
EOF
format

echo "编辑内核信息"
cat > /etc/sysconfig/grub << EOF
GRUB_TIMEOUT=5
GRUB_DISTRIBUTOR="$(sed 's, release .*$,,g' /etc/system-release)"
GRUB_DEFAULT=saved
GRUB_DISABLE_SUBMENU=true
GRUB_TERMINAL_OUTPUT="console"
GRUB_CMDLINE_LINUX="crashkernel=auto rhgb net.ifnames=0 biosdevname=0 quiet"
GRUB_DISABLE_RECOVERY="true"
EOF
format
echo "生成启动菜单"
grub2-mkconfig -o /boot/grub2/grub.cfg
format
reboot

 

posted @ 2018-11-09 08:15  夜辰雪扬  阅读(781)  评论(0编辑  收藏  举报