linux的os用户密码过期,linux – 如何自动通知用户密码过期?

该博客介绍了如何在Linux环境中利用chage命令结合shell脚本来实现用户密码到期前的自动通知。脚本每天或每周运行一次,检查用户的密码是否将在11天内过期,如果满足条件,将通过邮件通知用户或管理员。内容包括设置警告时间、检查密码过期状态以及发送邮件模板等细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

很高兴见到你.

我在Linux中使用了chage命令来设置用户的密码到期日期.

当到期日期临近时,我想自动通知用户.

这就是我想象它应该发生的方式:

>每天检查以确定密码是否即将过期

>如果密码超过11天,则不执行任何操作

>如果密码剩余10天或更少,请向用户发送通知电子邮件

我是否需要编写脚本来完成上述操作?或者有自动方法来实现这一目标吗?

谢谢

看看这是否符合您的要求.您可以使用chage命令或passwd -w设置警告时间:

#!/bin/bash

# notifypwexp - send mail to users whose passwords are expiring soon

# designed to be run daily or weekly from cron

# call with -w for weekly mode (checks to see if warning period begins in the next 7 days

# use -w for a weekly cron job,avoiding excessive emails

# with no option,it only checks whether we're in the warning period now

# use this for a daily cron job

# by Dennis Williamson

# ### SETUP ###

if [[ $1 == "-w" ]] # check for expiration warnings beginning during the next seven days

then

weekmode=7

else

weekmode=0

fi

admins="root postmaster"

declare -r aged=21 # minimum days after expiration before admins are emailed,set to 0 for "always"

hostname=$(hostname --fqdn)

# /etc/shadow is system dependent

shadowfile="/etc/shadow"

# fields in /etc/shadow

declare -r last=2

#declare -r may=3 # not used in this script

declare -r must=4

declare -r warn=5

#declare -r grace=6 # not used in this script

declare -r disable=7

declare -r doesntmust=99999

declare -r warndefault=7

passwdfile="/etc/passwd"

declare -r uidfield=3

declare -r unamefield=1

# UID range is system dependent

declare -r uidmin=1000

declare -r uidmax=65534 # exclusive

# remove the hardcoded path from these progs to use them via $PATH

# mailx is system dependent

notifyprog="/bin/mailx"

grepprog="/bin/grep"

awkprog="/usr/bin/awk"

dateprog="/bin/date"

# comment out one of these

#useUTC=""

useUTC="-u"

# +%s is a GNUism - set it to blank and use dateformat if you have

# a system that uses something else like epochdays,for example

epochseconds="+%s"

dateformat="" # blank for GNU when epochseconds="+%s"

secondsperday=86400 # set this to 1 for no division

today=$(($($dateprog $useUTC $epochseconds $dateformat)/$secondsperday))

oIFS=$IFS

# ### END SETUP ###

# ### MAIL TEMPLATES ###

# use single quotes around templates,backslash escapes and substitutions

# will be evaluated upon output

usersubjecttemplate='Your password is expiring soon'

userbodytemplate='Your password on $hostname expires in $(($expdate - $today)) days.

Please contact the IT department by email at \"helpdesk\" or at

extension 555 if you have any questions. Help is also available at

http://helpdesk.example.com/password'

adminsubjecttemplate='User Password Expired: $user@$hostname'

adminbodytemplate='The password for user $user on $hostname expired $age days ago.

Please contact this user about their inactive account and consider whether

the account should be disabled or deleted.'

# ### END MAIL TEMPLATES ###

# get real users

users=$($awkprog -F: -v uidfield=$uidfield \

-v unamefield=$unamefield \

-v uidmin=$uidmin \

-v uidmax=$uidmax \

-- '$uidfield>=uidmin && $uidfield

{print $unamefield}' $passwdfile)

for user in $users;

do

IFS=":"

usershadow=$($grepprog ^$user $shadowfile)

# make an array out of it

usershadow=($usershadow)

IFS=$oIFS

mustchange=${usershadow[$must]}

disabledate=${usershadow[$disable]:-$doesntmust}

# skip users that aren't expiring or that are disabled

if [[ $mustchange -ge $doesntmust || $disabledate -le $today ]] ; then continue; fi;

lastchange=${usershadow[$last]}

warndays=${usershadow[$warn]:-$warndefault}

expdate=$(($lastchange + $mustchange))

threshhold=$(($today + $warndays + $weekmode))

if [[ $expdate -lt $threshhold ]];

then

if [[ $expdate -ge $today ]];

then

subject=$(eval "echo \"$usersubjecttemplate\"")

body=$(eval "echo \"$userbodytemplate\"")

echo -e "$body" | $notifyprog -s "$subject" $user

else

if [[ $age -ge $aged ]];

then

subject=$(eval "echo \"$adminsubjecttemplate\"")

body=$(eval "echo \"$adminbodytemplate\"")

echo -e "$body" | $notifyprog -s "$subject" $admins

fi

fi

fi

done

Linux中,可以使用Python的`os`模块和`pwd`模块来创建用户并配置密码、组和到期日期。这里是一个简单的脚本示例,假设您已经安装了Python3: ```python import os import pwd # 用户名和密码 username = "your_username" password = username # 创建用户(如果不存在) try: user = pwd.getpwnam(username) except KeyError: user = pwd.PwEntry() user.pw_name = username user.pw_passwd = password.encode("utf-8") # 设置明文密码,但建议在生产环境中加密存储 user.pw_uid = os.geteuid() # 继承当前用户的ID user.pw_gid = getgrnam('test').gr_gid # 加入test组 with open("/etc/shadow", "a") as f: f.write(f"{username}:{password}::{os.environ['SUDO_DATE']}:18977::::::\n") os.system(f"useradd -m -s /bin/bash -g {user.pw_gid} -G sudo {username}") # 修改用户信息,包括过期日期 with open("/etc/shadow", "r+") as f: lines = f.readlines() for i, line in enumerate(lines): if line.startswith(username + ":"): lines[i] = f"{username}:{password}::{os.environ['SUDO_DATE']}::20251231:::\n" # 过期日期2025年12月31日 break f.seek(0) f.writelines(lines) f.truncate() print(f"{username}用户已创建,并设置了相关配置。") # 清理缓存 os.system("touch /var/lib/dbus/machine-id") # 确认更改 os.system("passwd %s" % username) # 需手动输入新密码一次确认 ``` 注意:这个脚本可能会因系统差异而需要调整,例如`/etc/shadow`文件的写入位置可能不同。此外,脚本中直接处理密码作为明文不太安全,实际应用中应使用更安全的方式存储密码。 运行此脚本前,请确保具有root权限,并谨慎操作,因为它涉及到用户权限的管理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值