Next Topic

Previous Topic

Book Contents

Sample Script: TLuaSocketSecure

--This function is called by KNM when enumerating a field
function OnEnumerate(sFieldToEnum)

	Enum = LuaScriptEnumResult()

	if sFieldToEnum == "Ignore connection problems" then
		Enum:Add("Yes")
		Enum:Add("No")
	end

	return Enum
end

--This function is called by KNM to retrieve a script configuration
function OnConfigure()

	Config = LuaScriptConfigurator()
	Config:SetAuthor("Robert Aronsson, Kaseya AB") 	
	Config:SetDescription("The script check if a certificate is about to
expire within the configured number of days.")
	Config:SetMinBuildVersion(5280)
	Config:SetScriptVersion(1,0)
	
	Config:AddArgument("Port number","Port number to connect on", LuaScriptConfigurator.CHECK_NOT_EMPTY)
	Config:AddArgument("Number of days","Check if certificate expres within this period",LuaScriptConfigurator.CHECK_NOT_EMPTY)
	Config:AddArgument("Ignore connection problems","Do you want thescript to report connection problems as well ?",LuaScriptConfigurator.ENUM_AVAIL + LuaScriptConfigurator.CHECK_NOT_EMPTY)

	Config:SetEntryPoint("main")
	
	return Config
end

--This is the entry point
function main()

	local iPort = GetArgument(0)
	local iNumDays = GetArgument(1)
	local bReportConnectionProblem = false;
	if GetArgument(2) == "Yes" then
		bReportConnectionProblem = true
	end

	--Timeperiod that the certificate should be valid within
	local iOffsetTime = (60 * 60 * 24) * iNumDays

	--Default values for test eval
	local bTestOk = true;
	local sText = "Certificate ok";

	--Open socket
	Socket = TLuaSocketSecure()
	if Socket:Open(iPort) ~= 0 then
	
		CurrentTime = TLuaDateTime();

		--The time was retrieved during the connect
		Time = Socket:GetCertificateExpiryDate();

		print("Certificate expires ("..Time:GetDate() .." " .. Time: GetTime()..")");

		--Check time
		iExpiryTime = Time:Get() -iOffsetTime;
		if Time:Get() < CurrentTime:Get() then
			bTestOk = false;
			sText = "Certificate have already expired ("..Time: GetDate() .." " .. Time:GetTime()..")";
		else
			if iExpiryTime < CurrentTime:Get() then
				bTestOk = false;
				sText = "Certificate is about to expire in less than "..iNumDays.." days"
			end
		end
	else
		--Failed to open the socket, server down ?
		if bReportConnectionProblem == true then
			bTestOk = false;
		end
		sText = "Cannot connect to host.";
	end

	--Report status and exit
	SetExitStatus(sText,bTestOk);
end