常用shell脚本
shell脚本在我们工作过程中会起到相当重要的作用,下面是我在一年工作中保存下来的常用的脚本。
多机程序部署脚本
作用及介绍
在某个程序需要完成多机部署,并且路径一致的时候,通过脚本来完成部署,启动,终止是一件很方便的事情。
#!/bin/bash
# Author: zhaoyixing
# @breif 程序部署脚本
#@breif 启动程序
function start_server() {
ssh $1 "do start"
}
#@breif 终止程序
function stop_server() {
ssh $1 "do stop"
}
#@breif 重启程序
function restart_server() {
stop_server $1;
sleep 2
start_server $1;
}
#@breif 查看程序的状态
function status_server() {
ssh $1 "do status" #自定义查看程序状态操作
}
function switch() {
host=$1
cmd=$2
if [ "x$cmd" == "xstart" ]
then
start_server ${host}
elif [ "x$cmd" == "xstop" ]
then
stop_server ${host}
elif [ "x$cmd" == "xrestart" ]
then
restart_server ${host}
else
status_server ${host}
fi
}
cmd=${1:-"status"}
for host in `cat hostlist`;
do
switch $host $cmd
done
go脚本
介绍及作用
多机登录,别名登录,解决纪录长机器名的问题
#! /bin/bash
# @author zhaoyixing
# @breif auto ssh
# @todo 使用expect 来完成密码的自动识别
#@breif 展示简单用法
function show_usage(){
echo -e "=================This is Usage====="
echo -e " -h: which host to go,for example dev"
}
#@breif 你的机器列表展示
function show_hostlist(){
echo "dev => dev.hostname"
}
function ssh_fun(){
if [ $# -ne 1 ];then
show_hostlist
fi
case "$1" in
"dev01" ) ssh user@dev01.abc.zs.shsdcsd ;;
"dev02" ) ssh user@dev02.abc.zs.shsdcsd ;;
"dev03" ) ssh user@dev03.abc.zs.shsdcsd ;;
"dev04" ) ssh user@dev04.abc.zs.shsdcsd ;;
"*" ) ssh $1 ;;
esac
}
if [ $# -eq 0 ];then
echo -e "\e[1;31mParams Error:\e[0m MayBe You Need Use -h"
show_usage
exit 0
fi
#1.The ":" after h mean that h can take values
#2.$OPTARG contains current value
host=''
while getopts "h:" Option;do
case $Option in
h)ssh_fun $OPTARG ;;
*)show_usage ;;
esac
done
总结
上面的两类应用是我在使用中用的比较方便的两个脚本,当然还有监控,上线等一系列shell可以帮你做的事情。代码是为了你的需要而产生的,希望这篇文章能够对你我有帮助