SHELL脚本汇总

用户

修改用户shell

usermod -s /usr/bin/bash username

数组

数据拼接

将多个数组拼接为一个数组

array1=("aaa")
array2=("bbb")
array_list=($array1 $array2)

日志

封装日志函数

function log() {
local level="$1"
local message="$2"
local current_date=$(date +"%Y-%m-%d %H:%M:%S")
if [ "$1" = "ERROR" ]; then
echo -e "\e[31m[$current_date] [$level] $message\e[0m"
elif [ "$1" = "DEBUG" ]; then
echo "[$current_date] [$level] $message"
}

调用日志函数

log "DEBUG" "message"

ssh

sshpass登录

使用sshpass测试ssh登录

sshpass -p "${password}" ssh root@localhost -o StrictHostKeyChecking=no

静默生成rsa

不需要手动确认生成sshkey

ssh-keygen -q -f ~/.ssh/id_rsa -y -t rsa -o -N ''

条件判断

hosts添加记录

判断hosts文件是否存在相同的记录如果不存在则添加

function check_host() {
local ip='192.168.1.1'
local hostname='aaa'
if grep -q "${ip}[[:space:]]*${hostname}" "/etc/hosts"; then
log "WARNING" "记录已存在"
else
echo "${ip} ${hostname}" | tee -a "/etc/hosts" > /dev/null
fi
}

.bash_profile中添加记录

判断.bash_profile中是否存在环境变量如果不存在则添加

function check_profile() {
local bash_profile="~/.bash_profile"
if [ -f "${bash_profile}" ]; then
#获取当前path值
current_path=$(grep -o 'PATH=.*' "${bash_profile}" | cut -d '=' -f2)
DB_PATH="/home/db/bin"
#检查DB_PATH是否在PATH中
if [[ ":${current_path}:" != *":${DB_PATH}:"* ]]; then
# 添加DB_PATH到PATH
new_path="${current_path}:${DB_PATH}"
# 更新bash_profile
sed -i "s|PATH=.*|PATH=${new_path}" "${bash_profile}"
fi
fi
}

添加内核参数

通过读取配置文件中的内核参数,如果/etc/sysctl.conf中存在则不添加否则添加记录

function set_sysctl() {
local param_file="/tmp/sysctl.conf"
#检查内核参数是否存在
while IFS= read -r line; do
if grep -q "${line}" "/etc/syslog.conf"; then
log "WARNING" "记录已存在无需添加"
else
echo "${line}" | sudo tee -a /etc/syslog.conf > /dev/null
log "DEBUG" "内核参数 ${line} 已经添加到 /etc/sysctl.conf"
fi
done < "${param_file}"
}
文章作者: 慕容峻才
文章链接: https://www.acaiblog.top/SHELL脚本汇总/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 阿才的博客
微信打赏
支付宝打赏