Skip to content

Instantly share code, notes, and snippets.

@Prussia
Created September 16, 2019 07:42
Show Gist options
  • Select an option

  • Save Prussia/7fd515a8a261da6f6a2578707538702c to your computer and use it in GitHub Desktop.

Select an option

Save Prussia/7fd515a8a261da6f6a2578707538702c to your computer and use it in GitHub Desktop.
#!/bin/bash
# kinit helper - 解决单用户并发 kinit 报错问题
# 只有当 expiredTime 剩余时间小于 2 小时才进行 kinit 操作,且只允许一次 kinit
source /etc/profile
# 输入参数 $1=租户 $2=租户密码
proxyUser=$1
passwd=$2
# 是否需要 kinit (默认需要=0)
needKinit=0
# 过期剩余时间阈值 2 小时
let maxLeftTime=2*60*60
# 检查是否需要重新 kinit,存在如下两种情况:
# 1.krb 文件不存在
# 2.klist 过期时间,还剩不到 2 小时
check_if_need_kinit(){
klist > /dev/null
if [ $? -eq 0 ]; then
# check principal is match
principal=$(klist | awk '{print $3}' | sed -n '2p' | cut -d@ -f1)
echo "default principal: $principal"
if [ "$principal" != "${proxyUser}" ]; then
echo "expect principal: $proxyUser, will re-kinit"
return
fi
# check klist has renew info
klist | grep renew
if [ $? -eq 1 ]; then
klist
echo "klist info exception !"
return
fi
expiredTime=$(klist | sed -n "5,1p" | awk '{print $2,$3}')
expiredTimeFT=$(date -d "${expiredTime}" +"%Y-%m-%d %H:%M:%S")
expiredTimestamp=$(date -d "$expiredTimeFT" +%s)
currentTimestamp=$(date +%s)
if [ $expiredTimestamp -gt $currentTimestamp ]; then
let free=$expiredTimestamp-$currentTimestamp
# 剩余时间大于所设阈值,则不需要 kinit
if [ $free -gt $maxLeftTime ]; then
nowTime=$(date "+%Y-%m-%d %H:%M:%S")
echo "NowTime: $nowTime, ExpiredTime: $expiredTimeFT, no need to kinit!"
needKinit=1
fi
fi
else
echo "krb file does not exist!"
fi
}
# 传入参数检查
if [ $# != 2 -o "$proxyUser" = "" -o "$passwd" = "" ]; then
echo "some curtionl params is null ! please check your prams"
exit 1
fi
check_if_need_kinit
if [ $needKinit -eq 0 ]; then
user=$(whoami)
# 抢占独占锁,进行 kinit 操作
echo "try to kinit, command: [ echo password | kinit $proxyUser ]"
flock -xn /tmp/${user}_kinit_lock -c "echo '$passwd' | kinit $proxyUser"
if [ $? -eq 0 ]; then
echo "kinit success!"
else
echo "kinit faild: may be kinit by other concurrent process or password is incorret!"
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment