草庐IT

干货!超实用的 Linux 初始化脚本

edisonfish 2023-03-28 原文

咸鱼今天给大家分享一个无论是学习还是工作中都很实用的 Linux 系统初始化脚本,其实就是各种命令的集合

 

完整代码在文章最后哦

 

定义相关变量

 

 

 

配置 yum 镜像源

 

 

获取阿里云 yum 镜像源

 

 

判断函数是否执行成功

 

 

写入一行配置

 

 

修改配置

 

 

配置系统时区

 

 

配置 dns 服务器

 

 

修改最大文件描述符限制

 

 

关闭系统不需要的服务

 

 

内核参数优化相关

 

 

安装常用工具

 

 

关闭 SELinux

 

 

主函数

 

 

完整脚本

#环境变量
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
export PATH

#当前时间
current_time=$(date +%Y%m%d)

#阿里的DNS
dns_server=223.5.5.5 

if [[ ! -z `uname -r|grep 'el6'` ]]
  then
  kernel_version=el6
  yum_repo=http://mirrors.aliyun.com/repo/Centos-6.repo
elif [[ ! -z `uname -r|grep 'el7'` ]]
  then
  kernel_version=el7
  yum_repo=http://mirrors.aliyun.com/repo/Centos-7.repo
else
  echo -e "\e[31mUnidentified Kernel version: $(uname -r). Only support for kernel el6/el7\e[0m"
  exit
fi

function add_yum_repo(){
  local item="Add Aliyun Yum Mirrors"
  yum clean all
  cp /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.${current_time} && \
  curl -o /etc/yum.repos.d/CentOS-Base.repo ${yum_repo} > /dev/null 2>&1
  show_result $? "${item}"
  yum makecache
}

function show_result(){
  if [ "$1" -eq 0 ]
    then
      echo -e "\e[32m$2 is Success .   [ OK ] \e[0m"
    else
      echo -e "\e[31m$2 is Fail .   [ FAIL ] \e[0m"
  fi
}

function add_newconfig_tofile(){
  local SearchResult=`grep "$1" "$2"`
  if [ -z "${SearchResult}" ]
    then
    echo "$1" >> $2
  fi
}

function add_config_tofile(){
  local keywords=`echo $1| awk -F "[= ]+" '{print $1}'`
  local SearchResult=`grep "^${keywords}" "$2"`
  if [ -z "${SearchResult}" ] #空为真,非空为假
    then
    echo $1 >> $2
  else
    sed -i "s/^${keywords}.*/$1/" $2
  fi
}

function config_localtime(){
  local item="Config SH As Location"
  rm -f /etc/localtime
  ln -s  /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
  show_result $? "${item}"
}

function config_dns_addr(){
  local item="Config DNS Address"
  cp /etc/resolv.conf /etc/resolv.conf.${current_time} && \
  echo "nameserver ${dns_server}" > /etc/resolv.conf
  show_result $? "${item}"
}

function maximum_file_dspt(){
  local item="Maximum File Descriptor"
  cp /etc/security/limits.conf /etc/security/limits.conf.${current_time} && \
  echo "*           soft    nofile          100000
*           hard    nofile          100000
*           soft    nproc           65535
*           hard    nproc           65535
*           soft    core            unlimited
*           hard    core            unlimited" > /etc/security/limits.conf
  show_result $? "${item}"
}


function shutdown_nonuse_srv(){
  local item="Shutdown Unused Services"
  if [[ "${kernel_version}" == el6 ]]
      then
    for i in `chkconfig --list | awk '{print $1}'`
      do
      chkconfig --level 2345 $i off > /dev/null 2>&1
      done
    for ii in crond network rsyslog sshd sysstat haldaemon
      do
      chkconfig --level 2345 $ii on > /dev/null 2>&1
      done
    show_result $? "${item}"
  elif [[ "${kernel_version}" == el7 ]]
    then
    systemctl disable postfix > /dev/null 2>&1
    show_result $? "${item}"
  else
    echo -e "\e[31mUnidentified Kernel version: $(uname -r). Only support for kernel el6/el7\e[0m"
  fi
}

function optimize_kel_args(){
  local item="Optimize Kernel Arguments"
  cp /etc/sysctl.conf /etc/sysctl.conf.${current_time} > /dev/null 2>&1
  arch_ratio=$([[ ! -z $(uname -a | grep x86_64) ]] && expr 64 / 32 || expr 32 / 32)
  memory_size=$(free -b| awk 'NR==2{print $2}')
  nf_conntrack_size=$(expr ${memory_size} / 16384 / ${arch_ratio})
  #开启反向路径过滤
  add_config_tofile "net.ipv4.conf.default.rp_filter = 1" /etc/sysctl.conf
  add_config_tofile "net.ipv4.conf.all.rp_filter = 1" /etc/sysctl.conf
  #处理无源路由包
  add_config_tofile "net.ipv4.conf.all.accept_source_route = 0" /etc/sysctl.conf
  add_config_tofile "net.ipv4.conf.default.accept_source_route = 0" /etc/sysctl.conf
  #core文件名中添加pid作为扩展名
  add_config_tofile "kernel.core_uses_pid = 1" /etc/sysctl.conf
  #开启syn洪水攻击保护
  add_config_tofile "net.ipv4.tcp_syncookies = 1" /etc/sysctl.conf
  #修改消息队列长度
  add_config_tofile "kernel.msgmnb = 65536" /etc/sysctl.conf
  add_config_tofile "kernel.msgmax = 65536" /etc/sysctl.conf
  #修改最大内存共享段大小bytes
  add_config_tofile "kernel.shmmax = 68719476736" /etc/sysctl.conf
  add_config_tofile "kernel.shmall = 4294967296" /etc/sysctl.conf
  #timewait数量默认18000
  add_config_tofile "net.ipv4.tcp_max_tw_buckets = 600" /etc/sysctl.conf
  add_config_tofile "net.ipv4.tcp_sack = 1" /etc/sysctl.conf
  add_config_tofile "net.ipv4.tcp_window_scaling = 1" /etc/sysctl.conf
  add_config_tofile "net.ipv4.tcp_rmem = 4096 87380 16777216" /etc/sysctl.conf
  add_config_tofile "net.ipv4.tcp_wmem = 4096 65536 16777216" /etc/sysctl.conf
  add_config_tofile "net.core.rmem_default = 8388608" /etc/sysctl.conf
  add_config_tofile "net.core.wmem_max = 16777216" /etc/sysctl.conf
  #未收到客户端确认信息连接请求的最大值
  add_config_tofile "net.ipv4.tcp_max_syn_backlog = 262144" /etc/sysctl.conf
  #放弃建立连接之前发送的synack包
  add_config_tofile "net.ipv4.tcp_syn_retries = 2" /etc/sysctl.conf
  #开启重用,允许time—wait socket 重新用语新的tcp连接
  add_config_tofile "net.ipv4.tcp_tw_reuse = 1" /etc/sysctl.conf
  add_config_tofile "net.ipv4.tcp_fin_timeout = 1" /etc/sysctl.conf
  #防止简单的ddos攻击
  add_config_tofile "net.ipv4.tcp_max_orphans = 3276800" /etc/sysctl.conf
  #启用timewait快速收回
  add_config_tofile "net.ipv4.tcp_tw_recycle = 0" /etc/sysctl.conf
  #keeptime启用时tcp发送keepalive消息的频度,默认2h
  add_config_tofile "net.ipv4.tcp_keepalive_time = 600" /etc/sysctl.conf
  #允许系统打开的端口范围
  add_config_tofile "net.ipv4.ip_local_port_range = 1024 65535" /etc/sysctl.conf
    #资源回收
    add_config_tofile "net.ipv4.tcp_tw_recycle = 0" /etc/sysctl.conf
    #路由转发
    add_config_tofile "net.ipv4.ip_forward = 1" /etc/sysctl.conf 
  #修改防火墙连接跟踪表大小,默认65535
  add_config_tofile "net.netfilter.nf_conntrack_max = ${nf_conntrack_size}" /etc/sysctl.conf
  add_config_tofile "net.nf_conntrack_max = ${nf_conntrack_size}" /etc/sysctl.conf
  #解禁ping
  add_config_tofile "net.ipv4.icmp_echo_ignore_all = 0" /etc/sysctl.conf
      modprobe bridge
  sysctl -p > /dev/null 2>&1
  show_result $? "${item}"
}

function install_pkgs(){
  local item="Install Common Pkgs"
  yum -y groupinstall "Development libraries" > /dev/null 2>&1
  yum -y groupinstall "Development tools" > /dev/null 2>&1
  yum -y install sysstat  tree  lrzsz  telnet wget net-tools tcpdump lsof vim ntp > /dev/null 2>&1
  show_result $? "${item}"
}

function shutdown_selinux(){
  local item="Shutdown Selinux "
  setenforce 0 > /dev/null 2>&1
  cp /etc/selinux/config /etc/selinux/config.${current_time} && \
  sed -i 's:SELINUX=enforcing:SELINUX=disabled:g' /etc/selinux/config
  show_result $? "${item}"
}

function main(){
  echo -e '\033[34;1m开始初始化操作系统中......\033[0m'
  add_yum_repo
  install_pkgs
  config_localtime
  config_dns_addr
  maximum_file_dspt
  shutdown_nonuse_srv
  shutdown_selinux
  optimize_kel_args
  echo -e '\033[34;1m服务器系统初始化已完成!\033[0m'
}

main

 

有关干货!超实用的 Linux 初始化脚本的更多相关文章

  1. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  2. ruby-on-rails - 未初始化的常量 Psych::Syck (NameError) - 2

    在我的gem中,我需要yaml并且在我的本地计算机上运行良好。但是在将我的gem推送到ruby​​gems.org之后,当我尝试使用我的gem时,我收到一条错误消息=>"uninitializedconstantPsych::Syck(NameError)"谁能帮我解决这个问题?附言RubyVersion=>ruby1.9.2,GemVersion=>1.6.2,Bundlerversion=>1.0.15 最佳答案 经过几个小时的研究,我发现=>“YAML使用未维护的Syck库,而Psych使用现代的LibYAML”因此,为了解决

  3. ruby - 在 Ruby 中编写命令行实用程序 - 2

    我想用ruby​​编写一个小的命令行实用程序并将其作为gem分发。我知道安装后,Guard、Sass和Thor等某些gem可以从命令行自行运行。为了让gem像二进制文件一样可用,我需要在我的gemspec中指定什么。 最佳答案 Gem::Specification.newdo|s|...s.executable='name_of_executable'...endhttp://docs.rubygems.org/read/chapter/20 关于ruby-在Ruby中编写命令行实用程序

  4. ruby-on-rails - 独立 ruby​​ 脚本的配置文件 - 2

    我有一个在Linux服务器上运行的ruby​​脚本。它不使用rails或任何东西。它基本上是一个命令行ruby​​脚本,可以像这样传递参数:./ruby_script.rbarg1arg2如何将参数抽象到配置文件(例如yaml文件或其他文件)中?您能否举例说明如何做到这一点?提前谢谢你。 最佳答案 首先,您可以运行一个写入YAML配置文件的独立脚本:require"yaml"File.write("path_to_yaml_file",[arg1,arg2].to_yaml)然后,在您的应用中阅读它:require"yaml"arg

  5. ruby-on-rails - 未在 Ruby 中初始化的对象 - 2

    我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调

  6. ruby-on-rails - ActionController::RoutingError: 未初始化常量 Api::V1::ApiController - 2

    我有用于控制用户任务的Rails5API项目,我有以下错误,但并非总是针对相同的Controller和路由。ActionController::RoutingError:uninitializedconstantApi::V1::ApiController我向您描述了一些我的项目,以更详细地解释错误。应用结构路线scopemodule:'api'donamespace:v1do#=>Loginroutesscopemodule:'login'domatch'login',to:'sessions#login',as:'login',via::postend#=>Teamroutessc

  7. ruby - 这两个 Ruby 类初始化定义有什么区别? - 2

    我正在阅读一本关于Ruby的书,作者在编写类初始化定义时使用的形式与他在本书前几节中使用的形式略有不同。它看起来像这样:classTicketattr_accessor:venue,:datedefinitialize(venue,date)self.venue=venueself.date=dateendend在本书的前几节中,它的定义如下:classTicketattr_accessor:venue,:datedefinitialize(venue,date)@venue=venue@date=dateendend在第一个示例中使用setter方法与在第二个示例中使用实例变量之间是

  8. postman——集合——执行集合——测试脚本——pm对象简单示例02 - 2

    //1.验证返回状态码是否是200pm.test("Statuscodeis200",function(){pm.response.to.have.status(200);});//2.验证返回body内是否含有某个值pm.test("Bodymatchesstring",function(){pm.expect(pm.response.text()).to.include("string_you_want_to_search");});//3.验证某个返回值是否是100pm.test("Yourtestname",function(){varjsonData=pm.response.json

  9. ruby - 为什么当我调用类的实例方法时,初始化不显示为方法? - 2

    我正在写一篇关于在Ruby中几乎一切都是对象的博客文章,我试图通过以下示例来展示这一点:classCoolBeansattr_accessor:beansdefinitialize@bean=[]enddefcount_beans@beans.countendend所以从类中我们可以看出它有4个方法(当然,除非我错了):它可以在创建新实例时初始化一个默认的空bean数组它可以计算它有多少个bean它可以读取它有多少个bean(通过attr_accessor)它可以向空数组写入(或添加)更多bean(也通过attr_accessor)但是,当我询问类本身它有哪些实例方法时,我没有看到默认

  10. ruby-on-rails - 为什么在 Rails 5.1.1 中删除了 session 存储初始化程序 - 2

    我去了这个website查看Rails5.0.0和Rails5.1.1之间的区别为什么5.1.1不再包含:config/initializers/session_store.rb?谢谢 最佳答案 这是删除它的提交:Setupdefaultsessionstoreinternally,nolongerthroughanapplicationinitializer总而言之,新应用没有该初始化器,session存储默认设置为cookie存储。即与在该初始值设定项的生成版本中指定的值相同。 关于

随机推荐