Check certificate "valid days" and send email if lover than Xdays

Hello,
first of all, Im bad at scripting :confused:
can I have someone more skilled to do this scenario script? I think Im not the only one who would appreciated this when using certificates in mikrotik (for example for OVPN)

  • check all certificates in store for days valid
  • if any certificate is lower than X days (need to be configurable)
  • get system identity, certificate name, certificate common name, fingerprint, number of days till expired
  • send info via tool email to email address (need to be configurable)


    thank you in advance

replace :put with something that sent that string by mail.

{
:local days 21d ; # Keep the d for days at the end, or can be used w for week
/certificate
:foreach item in=[find] do={
    :if (([get $item expires-after] < $days) and ![get $item expired]) do={
        :put "On >$[/sys id get name]< the certificate $[get $item name] ($[get $item common-name]) \
              [$[get $item fingerprint]] expires after $[get $item expires-after] ($[get $item invalid-after])"
    }
    :if ([get $item expired]) do={
        :put "On >$[/sys id get name]< the certificate $[get $item name] ($[get $item common-name]) \
              [$[get $item fingerprint]] ALREADY EXPIRED on $[get $item invalid-after]"
    }
}
}

Thank you, i have made some changes, but Im not succesful with this

{
edited, fixed in next post
}

Got it working

here it is :slight_smile:

# days - Keep the d for days at the end, or can be used w for week
# mailto - Email where to send info
# subject1 - Email subject for soon to be expired
# subject2 - Email subject for expired certificates

{
:local days 30d;
:local mailto "admin@domain.com";
:local subject1 "Certificate expires soon";
:local subject2 "Certificate expired";
/certificate
:foreach item in=[find] do={
    :if (([get $item expires-after] < $days) and ![get $item expired]) do={
       :tool e-mail send to=$mailto subject=$subject1 body="Hello,\n\nCertificate on Mikrotik named $[/sys id get name] is about to expire \n\ncertificate name:\t$[get $item name] \ncommon name:\t($[get $item common-name])\nfingerpint:\t\t[$[get $item fingerprint]]\n\nexpires after:\t\t$[get $item expires-after]\nexpiration date:\t($[get $item invalid-after])"
    }
    :if ([get $item expired]) do={
        :tool e-mail send to=$mailto subject=$subject2 body="Hello,\n\nCertificate on Mikrotik named $[/sys id get name] expired \n\ncertificate name:\t$[get $item name] \ncommon name:\t($[get $item common-name])\nfingerpint:\t\t[$[get $item fingerprint]]\n\nEXPIRED on:\t\t$[get $item invalid-after]"
    }
  }
}

You may be interested in my script to Renew certificates and notify on expiration. It does what you need, and a lot more.