脚本参数
2022/1/9大约 8 分钟语言特性
脚本参数
直接处理
回顾一下
$0 #即命令本身,相当于c/c++中的argv[0]
$1 #第一个参数
$2, $3, $4 ... #第2、3、4个参数,依次类推
$# #参数的个数,不包括命令本身
$@ #参数本身的列表,不包括命令本身
$* #和$@相同,但"$*"和"$@"(加引号)并不同,
#"$*"将所有的参数解释成一个字符串,而"$@"是一个参数数组
getopts
单个字符选项的情况(如:-n 10 -f file.txt等选项)
- getopts是bash的内部命令
- getopts有两个参数,第一个参数是一个字符串,包括字符和“:”
- 每一个字符都是一个有效的选项(option),如果字符后面带有“:”,表示这个选项有自己的argument,argument保存在内置变量OPTARG中
- $OPTIND总是存储原始$*中下一个要处理的元素位置
- 对于while getopts "🅰️bc" opt,第一个冒号表示忽略错误
#!/bin/bash
echo original parameters=[$*]
echo original OPTIND=[$OPTIND]
while getopts ":a:bc" opt
do
case $opt in
a)
echo "this is -a option. OPTARG=[$OPTARG] OPTIND=[$OPTIND]"
;;
b)
echo "this is -b option. OPTARG=[$OPTARG] OPTIND=[$OPTIND]"
;;
c)
echo "this is -c option. OPTARG=[$OPTARG] OPTIND=[$OPTIND]"
;;
?)
echo "there is unrecognized parameter."
exit 1
;;
esac
done
#通过shift $(($OPTIND - 1))的处理,$*中就只保留了除去选项内容的参数,
#可以在后面的shell程序中进行处理
shift $(($OPTIND - 1))
echo remaining parameters=[$*]
echo \$1=[$1]
echo \$2=[$2]
第二个例子
#!/bin/bash
while getopts "a:bc" arg #选项后面的冒号表示该选项需要参数
do
case $arg in
a)
echo "a's arg:$OPTARG" #参数存在$OPTARG中
;;
b)
echo "b"
;;
c)
echo "c"
;;
?) #当有不认识的选项的时候arg为?
echo "unkonw argument"
exit 1
;;
esac
done
getopt
可以处理单个字符选项,也可以处理长选项long-option(如:--prefix=/home等)
- getopt是一个外部命令,不是bash内置命令,Linux发行版通常会自带
- getopt支持短选项和长选项
- 老版本的getopt问题较多,增强版getopt比较好用,执行命令getopt -T; echo $?,如果输出4,则代表是增强版的
- 如果短选项带argument且参数可选时,argument必须紧贴选项,如-carg 而不能是-c - arg
- 如果长选项带argument且参数可选时,argument和选项之间用“=”,如--clong=arg而不- 能是--clong arg
#!/bin/bash
echo original parameters=[$@]
#-o或--options选项后面是可接受的短选项,如ab:c::,表示可接受的短选项为-a -b -c,
#其中-a选项不接参数,-b选项后必须接参数,-c选项的参数为可选的
#-l或--long选项后面是可接受的长选项,用逗号分开,冒号的意义同短选项。
#-n选项后接选项解析错误时提示的脚本名字
ARGS=`getopt -o ab:c:: --long along,blong:,clong:: -n "$0" -- "$@"`
if [ $? != 0 ]; then
echo "Terminating..."
exit 1
fi
echo ARGS=[$ARGS]
#将规范化后的命令行参数分配至位置参数($1,$2,...)
eval set -- "${ARGS}"
echo formatted parameters=[$@]
while true
do
case "$1" in
-a|--along)
echo "Option a";
shift
;;
-b|--blong)
echo "Option b, argument $2";
shift 2
;;
-c|--clong)
case "$2" in
"")
echo "Option c, no argument";
shift 2
;;
*)
echo "Option c, argument $2";
shift 2;
;;
esac
;;
--)
shift
break
;;
*)
echo "Internal error!"
exit 1
;;
esac
done
#处理剩余的参数
echo remaining parameters=[$@]
echo \$1=[$1]
echo \$2=[$2]
测试一下:
#短选项 ./getopt.sh -a -b1 -c2 file1 file2
original parameters=[-a -b1 -c2 file1 file2]
ARGS=[ -a -b '1' -c '2' -- 'file1' 'file2']
formatted parameters=[-a -b 1 -c 2 -- file1 file2]
Option a
Option b, argument 1
Option c, argument 2
remaining parameters=[file1 file2]
$1=[file1]
$2=[file2]
#长选项 ./getopt.sh --along --blong=1 --clong=2 file1 file2
original parameters=[--along --blong=1 --clong=2 file1 file2]
ARGS=[ --along --blong '1' --clong '2' -- 'file1' 'file2']
formatted parameters=[--along --blong 1 --clong 2 -- file1 file2]
Option a
Option b, argument 1
Option c, argument 2
remaining parameters=[file1 file2]
$1=[file1]
$2=[file2]
#长短混合
# ./getopt.sh -a -b1 --clong=2 file1 file2
original parameters=[-a -b1 --clong=2 file1 file2]
ARGS=[ -a -b '1' --clong '2' -- 'file1' 'file2']
formatted parameters=[-a -b 1 --clong 2 -- file1 file2]
Option a
Option b, argument 1
Option c, argument 2
remaining parameters=[file1 file2]
$1=[file1]
$2=[file2]
第二个例子
#!/bin/bash
#-o表示短选项,两个冒号表示该选项有一个可选参数,可选参数必须紧贴选项
#如-carg 而不能是-c arg
#--long表示长选项
#"$@"在上面解释过
# -n:出错时的信息
# -- :举一个例子比较好理解:
#我们要创建一个名字为 "-f"的目录你会怎么办?
# mkdir -f #不成功,因为-f会被mkdir当作选项来解析,这时就可以使用
# mkdir -- -f 这样-f就不会被作为选项。
TEMP=`getopt -o ab:c:: --long a-long,b-long:,c-long:: \
-n 'example.bash' -- "$@"`
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi
# Note the quotes around `$TEMP': they are essential!
#set 会重新排列参数的顺序,也就是改变$1,$2...$n的值,这些值在getopt中重新排列过了
eval set -- "$TEMP"
#经过getopt的处理,下面处理具体选项。
while true ; do
case "$1" in
-a|--a-long) echo "Option a" ; shift ;;
-b|--b-long) echo "Option b, argument \`$2'" ; shift 2 ;;
-c|--c-long)
# c has an optional argument. As we are in quoted mode,
# an empty parameter will be generated if its optional
# argument is not found.
case "$2" in
"") echo "Option c, no argument"; shift 2 ;;
*) echo "Option c, argument \`$2'" ; shift 2 ;;
esac ;;
--) shift ; break ;;
*) echo "Internal error!" ; exit 1 ;;
esac
done
echo "Remaining arguments:"
for arg do
echo '--> '"\`$arg'" ;
done
$ bash test.sh -a -b arg arg1 -c
Option a
Option b, argument `arg'
Option c, no argument
Remaining arguments:
--> `arg1'
可以看到,命令行中多了个arg1参数,在经过getopt和set之后,命令行会变为: -a -b arg -c -- arg1 $1指向-a,$2指向-b,$3指向arg,$ 4指向-c,$5指向--,而多出的arg1则被放到了最后
- 举例 如将前面的ssh.exp、scp.exp封装起来,代码:
#!/bin/bash
###################### proc defination ########################
# ignore rule
ignore_init()
{
# ignore password
array_ignore_pwd_length=0
if [ -f ./ignore_pwd ]; then
while read IGNORE_PWD
do
array_ignore_pwd[$array_ignore_pwd_length]=$IGNORE_PWD
let array_ignore_pwd_length=$array_ignore_pwd_length+1
done < ./ignore_pwd
fi
# ignore ip address
array_ignore_ip_length=0
if [ -f ./ignore_ip ]; then
while read IGNORE_IP
do
array_ignore_ip[$array_ignore_ip_length]=$IGNORE_IP
let array_ignore_ip_length=$array_ignore_ip_length+1
done < ./ignore_ip
fi
}
show_version()
{
echo "version: 1.0"
echo "updated date: 2014-01-09"
}
show_usage()
{
echo -e "`printf %-16s "Usage: $0"` [-h|--help]"
echo -e "`printf %-16s ` [-v|-V|--version]"
echo -e "`printf %-16s ` [-l|--iplist ... ]"
echo -e "`printf %-16s ` [-c|--config ... ]"
echo -e "`printf %-16s ` [-t|--sshtimeout ... ]"
echo -e "`printf %-16s ` [-T|--fttimeout ... ]"
echo -e "`printf %-16s ` [-L|--bwlimit ... ]"
echo -e "`printf %-16s ` [-n|--ignore]"
#echo "ignr_flag: 'ignr'-some ip will be ignored; otherwise-all ip will be handled"
}
# Default Parameters
myIFS=":::" # 配置文件中的分隔符
TOOLDIR=/root/scripts
cd $TOOLDIR
IPLIST="iplist.txt" # IP列表,格式为IP 端口 用户名 密码
CONFIG_FILE="config.txt" # 命令列表和文件传送配置列表,关键字为com:::和file:::
IGNRFLAG="noignr" # 如果置为ignr,则脚本会进行忽略条件的判断
SSHTIMEOUT=100 # 远程命令执行相关操作的超时设定,单位为秒
SCPTIMEOUT=2000 # 文件传送相关操作的超时设定,单位为秒
BWLIMIT=1024000 # 文件传送的带宽限速,单位为kbit/s
# 入口参数分析
TEMP=`getopt -o hvVl:c:t:T:L:n --long help,version,iplist:,config:,sshtimeout:,fttimeout:,bwlimit:,ignore -- "$@" 2>/dev/null`
[ $? != 0 ] && echo -e "\033[31mERROR: unknown argument! \033[0m\n" && show_usage && exit 1
# 会将符合getopt参数规则的参数摆在前面,其他摆在后面,并在最后面添加--
eval set -- "$TEMP"
while :
do
[ -z "$1" ] && break;
case "$1" in
-h|--help)
show_usage; exit 0
;;
-v|-V|--version)
show_version; exit 0
;;
-l|--iplist)
IPLIST=$2; shift 2
;;
-c|--config)
CONFIG_FILE=$2; shift 2
;;
-t|--sshtimeout)
SSHTIMEOUT=$2; shift 2
;;
-T|--fttimeout)
SCPTIMEOUT=$2; shift 2
;;
-L|--bwlimit)
BWLIMIT=$2; shift 2
;;
-n|--ignore)
IGNRFLAG="ignr"; shift
;;
--)
shift
;;
*)
echo -e "\033[31mERROR: unknown argument! \033[0m\n" && show_usage && exit 1
;;
esac
done
################ main #######################
BEGINDATETIME=`date "+%F %T"`
[ ! -f $IPLIST ] && echo -e "\033[31mERROR: iplist \"$IPLIST\" not exists, please check! \033[0m\n" && exit 1
[ ! -f $CONFIG_FILE ] && echo -e "\033[31mERROR: config \"$CONFIG_FILE\" not exists, please check! \033[0m\n" && exit 1
echo
echo "You are using:"
echo -e "`printf %-16s "\"$CONFIG_FILE\""` ---- as your config"
echo -e "`printf %-16s "\"$IPLIST\""` ---- as your iplist"
echo -e "`printf %-16s "\"$SSHTIMEOUT\""` ---- as your ssh timeout"
echo -e "`printf %-16s "\"$SCPTIMEOUT\""` ---- as your scp timeout"
echo -e "`printf %-16s "\"$BWLIMIT\""` ---- as your bwlimit"
echo -e "`printf %-16s "\"$IGNRFLAG\""` ---- as your ignore flag"
echo
[ -f ipnologin.txt ] && rm -f ipnologin.txt
IPSEQ=0
while read IP PORT USER PASSWD PASSWD_2ND PASSWD_3RD PASSWD_4TH OTHERS
do
[ -z "`echo $IP | grep -E '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'`" ] && continue
[ "`python $TOOLDIR/ckssh.py $IP $PORT`" == 'no' ] && echo "$IP" >> ipnologin.txt && continue
let IPSEQ=$IPSEQ+1
# 如果启用了忽略,则进入忽略流程
if [ $IGNRFLAG == "ignr" ]; then
ignore_init
ignored_flag=0
i=0
while [ $i -lt $array_ignore_pwd_length ]
do
[ ${PASSWD}x == ${array_ignore_pwd[$i]}x ] && ignored_flag=1 && break
let i=$i+1
done
[ $ignored_flag -eq 1 ] && continue
j=0
while [ $j -lt $array_ignore_ip_length ]
do
[ ${IP}x == ${array_ignore_ip[$j]}x ] && ignored_flag=1 && break
let j=$j+1
done
[ $ignored_flag -eq 1 ] && continue
fi
####### Try password from here ####
for PW in $PASSWD $PASSWD_2ND $PASSWD_3RD $PASSWD_4TH
do
PASSWD_USE=$PW
$TOOLDIR/ssh.exp $IP $USER $PW $PORT true $SSHTIMEOUT
[ $? -eq 0 ] && PASSWD_USE=$PW && break
done
# 针对一个$IP,执行配置文件中的一整套操作
while read eachline
do
# 必须以com或file开头
[ -z "`echo $eachline | grep -E '^com|^file'`" ] && continue
myKEYWORD=`echo $eachline | awk -F"$myIFS" '{ print $1 }'`
myCONFIGLINE=`echo $eachline | awk -F"$myIFS" '{ print $2 }'`
# 对配置文件中的预定义的可扩展特殊字符串进行扩展
# 关键字#IP#,用$IP进行替换
if [ ! -z "`echo "$myCONFIGLINE" | grep '#IP#'`" ]; then
myCONFIGLINE_temp=`echo $myCONFIGLINE | sed "s/#IP#/$IP/g"`
myCONFIGLINE=$myCONFIGLINE_temp
fi
# 时间相关关键字,用当前时间进行替换
if [ ! -z "`echo "$myCONFIGLINE" | grep '#YYYY#'`" ]; then
myYEAR=`date +%Y`
myCONFIGLINE_temp=`echo $myCONFIGLINE | sed "s/#YYYY#/$myYEAR/g"`
myCONFIGLINE=$myCONFIGLINE_temp
fi
if [ ! -z "`echo "$myCONFIGLINE" | grep '#MM#'`" ]; then
myMONTH=`date +%m`
myCONFIGLINE_temp=`echo $myCONFIGLINE | sed "s/#MM#/$myMONTH/g"`
myCONFIGLINE=$myCONFIGLINE_temp
fi
if [ ! -z "`echo "$myCONFIGLINE" | grep '#DD#'`" ]; then
myDATE=`date +%d`
myCONFIGLINE_temp=`echo $myCONFIGLINE | sed "s/#DD#/$myDATE/g"`
myCONFIGLINE=$myCONFIGLINE_temp
fi
if [ ! -z "`echo "$myCONFIGLINE" | grep '#hh#'`" ]; then
myHOUR=`date +%H`
myCONFIGLINE_temp=`echo $myCONFIGLINE | sed "s/#hh#/$myHOUR/g"`
myCONFIGLINE=$myCONFIGLINE_temp
fi
if [ ! -z "`echo "$myCONFIGLINE" | grep '#mm#'`" ]; then
myMINUTE=`date +%M`
myCONFIGLINE_temp=`echo $myCONFIGLINE | sed "s/#mm#/$myMINUTE/g"`
myCONFIGLINE=$myCONFIGLINE_temp
fi
if [ ! -z "`echo "$myCONFIGLINE" | grep '#ss#'`" ]; then
mySECOND=`date +%S`
myCONFIGLINE_temp=`echo $myCONFIGLINE | sed "s/#ss#/$mySECOND/g"`
myCONFIGLINE=$myCONFIGLINE_temp
fi
# IPSEQ关键字,用当前IP的序列号替换,从1开始
if [ ! -z "`echo "$myCONFIGLINE" | grep '#IPSEQ#'`" ]; then
myCONFIGLINE_temp=`echo $myCONFIGLINE | sed "s/#IPSEQ#/$IPSEQ/g"`
myCONFIGLINE=$myCONFIGLINE_temp
fi
# 配置文件中有关键字file:::,就调用scp.exp进行文件传送
if [ "$myKEYWORD"x == "file"x ]; then
SOURCEFILE=`echo $myCONFIGLINE | awk '{ print $1 }'`
DESTDIR=`echo $myCONFIGLINE | awk '{ print $2 }'`
DIRECTION=`echo $myCONFIGLINE | awk '{ print $3 }'`
$TOOLDIR/scp.exp $IP $USER $PASSWD_USE $PORT $SOURCEFILE $DESTDIR $DIRECTION $BWLIMIT $SCPTIMEOUT
[ $? -ne 0 ] && echo -e "\033[31mSCP Try Out All Password Failed\033[0m\n"
# 配置文件中有关键字com:::,就调用ssh.exp进行远程命令执行
elif [ "$myKEYWORD"x == "com"x ]; then
$TOOLDIR/ssh.exp $IP $USER $PASSWD_USE $PORT "${myCONFIGLINE}" $SSHTIMEOUT
[ $? -ne 0 ] && echo -e "\033[31mSSH Try Out All Password Failed\033[0m\n"
else
echo "ERROR: configuration wrong! [$eachline] "
echo " where KEYWORD should not be [$myKEYWORD], but 'com' or 'file'"
echo " if you dont want to run it, you can comment it with '#'"
echo ""
exit
fi
done < $CONFIG_FILE
done < $IPLIST
ENDDATETIME=`date "+%F %T"`
echo "$BEGINDATETIME -- $ENDDATETIME"
echo "$0 $* --excutes over!"
exit 0