vRO Scriptable task to kill idle vCenter sessions

Update: A new friend provided an update to the script to validate that terminate.keys is populated, I added it to script below.

This is a recommended best practice.  Kill vCenter sessions that are older than 24 hours.   This scriptable task will kill all idle sessions that are older than the variable maxidletime.   Cut and paste and go.

//get connection to gather sessions
var vcenters=VcPlugin.allSdkConnections;

//object to hold sessions we force close
var sessions_closed = [];

for each (vcenter in vcenters)
{
	// array for keys of sessions to terminate per vCenter
	var terminate_keys = [];
	//get session list
	sessions = vcenter.sessionManager.sessionList;
	//go through each session
	for each (session in sessions)
	{
		//Get current time since epoch in seconds
		var currenttime = new Date().getTime() / 1000;
		//Get lastActiveTime since epoch on this session
		var loginTime = session.lastActiveTime.getTime() / 1000;
		//Figure out the amount of idletime in minutes
		idletime = ((currenttime - loginTime)/60);
		// if idletime is longer than maxidletime
		if ( idletime > maxidletime)
		{
			//create a string of userName for compare to remove elements that should not be killed
			username = session.userName;
			
			
				//if a session is going to be killed push into an array for alerting
				sessions_closed.push({user: session.userName, loginTime: session.loginTime, idleTime: session.idleTime, agent: session.userAgent, extention: session.extention, callCount: session.callCount, vcenter: vcenter.id, session: sesstion.key});
				//Load sessions id into kill array
				terminate_keys.push(session.key);
		} // end of sessions that match idletime
	} // end of each session
	// kill all sessions in terminate_keys
        if (terminate_keys.length > 0 ) {
                     System.log("Killing sessions for " +vcenter.name);
                     kill = vcenter.sessionManager.terminateSession(terminate_keys);
        }
        else
        {
                      System.log("No sessions to kill for " + vcenter.name);
        }

} // end of for each vCenter


if (testing)
{
	//Logging to debug
	for each (s in sessions_closed)
	{
		System.log("Name: " + s.user + " agent " + s.agent + " CallCount " + s.callCount + " vcenter " + s.vcenter);

	}

}


Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.