其他
SHELL编程预留题目解析
1. 判断/tmp/run目录是否存在,如果不存在就建立,如果存在就删除目录里所有文件
#!/bin/bash
if [ -d /tmp/run ];then
rm -rf /tmp/run/*
else
mkdir /tmp/run
fi
2. 输入一个路径,判断路径是否存在,而且输出是文件还是目录,如果是链接文件,还得输出是 有效的连接还是无效的连接
#!/bin/bash
# -d 判断是否是一个目录
# -f 判断是否是一个文件
# -L 判断是否是一个软连接文件
# -e 判断文件是否存在
# ls -L 遇到性质为符号连接的文件或目录,直接列出该连接所指向的原始文件或目录
if [ -d $1 ]
then
echo "$1 is a directory."
exit
elif [ -f $1 ]
then
echo -n "$1 is a file, "
if [ -L $1 ]
then
echo "and it is also a symbolic link."
A=`ls -L $1`
if [ -e $A ]
then
echo "Symbolic link exist."
else
echo "Symbolic link not exist."
fi
exit
else
echo "but it is not a symbolic link."
exit
fi
fi
3. 交互模式要求输入一个ip,然后脚本判断这个IP 对应的主机是否 能ping 通,输出结果类似于:Server 10.1.1.20 is Down! 最后要求把结果邮件到本地管理员root@localhost mail01@localhost
#!/bin/bash
read -p "Please input ip address:" ip
ping -c1 $ip &>/dev/null
if [ $? -eq 0 ];then
echo "Server $ip is okey!" | mail -s "Server State" root@localhost
else
echo "Server $ip is down!" | mail -s "Server State" root@localhost
fi
4. 写一个脚本/home/program,要求当给脚本输入参数hello时,脚本返回world,给脚本输入参数world时,脚本返回hello。而脚本没有参数或者参数错误时,屏幕上输出“usage:/home/program hello or world”
#!/bin/bash
if [ "$1" == "hello" ];then
echo "world"
elif [ "$1" == "world" ];then
echo "hello"
else
echo "usage:/home/program hello or world"
fi
5. 写一个脚本自动搭建nfs服务
#!/bin/bash
#name:auto_build_nfs_serve.sh
#path:/tmp/
#update: 2020-3-11
read -p "Please input Sever Address:" ip
#检测网络连接是否正常
ping -c1 $ip &>/dev/null && echo "Server connection is normal"
#第一步:关闭selinux和防火墙
#selinux是安全增强型 Linux(Security-Enhanced Linux)简称,是linux的一个安全子系统
#临时关闭Selinux: setenforce 0
#永久关闭:vim /etc/sysconfig/selinux
#SELINUX=enforcing 改为 SELINUX=disabled
setenforce 0 &>/dev/null && echo "selinux has closed..."
systemctl stop firewall &>/dev/null && echo "Firewall has been closed ..."
#第二步:确认软件是否安装
#查询指定软件是否已安装:rpm -q <软件名> 或者 rpm -qa <软件名> 或者 rpm -qa | grep <软件名>
rpm -aq | grep rpcbind &>/dev/null
if [ $? -eq 0 ];then
echo "rpcbind has been installed"
else
yum install rpcbind -y &>/dev/null && echo "Intalling the rpcbind..."
fi
#第三步:创建和发布共享目录
read -p "Please enter the directory you want to share:" dir
# 创建目录,-p 确保目录名称存在,不存在的就建一个。
mkdir $dir -p &>/dev/null
chmod 777 $dir
read -p "Please enter the network segment to be shared" NS
read -p "Please enter the permission to share, enter ro or rw:" PERMISSION
cat >> /etc/exports << end
$dir $NS($PERMISSION)
end
#第四步:设置nfs服务开机自启动
systemctl restart rpcbind.service &>/dev/null && echo "rpcbind service has been started..."
systemctl restart nfs.service &>/dev/null && echo "nfs service started successfully"