使用 shell 脚本自动化 CentOS 7 配置

使用 shell 脚本自动化 CentOS 7 配置

我注意到我花了很多时间使用教程来手动配置 CentOS 7 服务器。 如何将教程中的手动步骤转换为可用于使用相同设置配置多个 CentOS 7 服务器的自动 shell 脚本?

让我们使用本教程作为一个例子,但除了简单地提供一个工作 shell 脚本来自动化之外,答案应该可以推广到其他配置 shell 脚本本教程。

这是我第一次尝试 shell 脚本:

#!/bin/bash
yum update
yum install yum-utils bzip2 bzip2-devel wget curl tar
sudo yum install gcc-c++
cd /opt
wget http://nodejs.org/dist/v0.12.7/node-v0.12.7.tar.gz
tar zxf node-v0.12.7.tar.gz
cd node-v0.12.7
./configure --prefix=/usr/local
make
make install  
npm install bower -g  
npm install gulp -g  

如何正确编写上面的shell脚本?例如,我如何检查每个步骤是否正确完成?我必须是 root 才能运行上面的命令。如果我将其作为 sudoer 运行,如何处理定期的密码请求?或者它在 shell 脚本中的事实是否意味着您只需在第一次调用脚本时提供 sudoer 密码?

我对 shell 脚本是全新的,所以请耐心并用其他 shell 脚本新手也能理解的语言进行解释。

另外,这并不是 CentOS 7 特有的,比如yum install等等。

答案1

您的问题有几个部分,我不能声称熟悉您运行的所有命令,但这是我的看法:

以 root 身份(直接)或通过 sudo 运行整个脚本。这样,您就不需要在脚本本身中运行 sudo。如果您需要 sudo 来执行特定步骤,那么您需要在 sudoers 中使用 NOPASSWD 标志设置您的 ID,或者在脚本执行期间接受输入密码的交互式提示。

要回答有关每个步骤正确执行的其他一般问题,方法是检查步骤的返回代码并希望现有程序正确设置返回代码。

举些例子:

简写法:

yum update && \
yum install yum-utils bzip2 bzip2-devel wget curl tar

长手:

yum update
RC=$?
if [ $RC -ne 0 ]
then
  print "Some error message here"
  exit 1 ## or some other identifying error code
fi

yum install yum-utils bzip2 bzip2-devel wget curl tar
RC=$?
if [ $RC -ne 0 ]
then
  print "Some other error message here"
  exit 2 ## or some other identifying error code
fi
...

答案2

正如您提到的,它应该是一个自动 shell 脚本,至少对于您需要添加的两个 yum 命令,-y这样 yum 将假定答案为“是的“对于它会问的所有问题。

请参阅百胜手册页,相关摘录:

   -y, --assumeyes
          Assume yes; assume that the answer to any question which would be asked is yes.
          Configuration Option: assumeyes

有关更多详细信息,包括一些需要注意的重要提示,请参阅现有问题:“yum -y install”安全吗?

相关内容