Introduction
A script is a user-defined job, you can define your own job tasks by writing code to be included in OS and SQL scripts.
Note: Avoid running an agent-configured task having an output of more than 64KB as the script output is limited to 64KB.
Scripts are partner specific. For example, a script can be created, assigned, and scheduled at the partner-level and the client-level devices.
Creating and applying scripts
In addition to native jobs, a user can create custom scripts and apply them to resources.
To create a script:
- Go to Automation > Scripts. Scheduled Scripts page appears.
- In All Scripts tab, click Add and click Add Script.
- Provide the script details.
- Select the Script Type from the drop-down and provide the Command/File Name.
- If a scripting language is provided as execution type, example VBS, then copy the script in the Script section.
- Click Add Params.
- To validate the script, provide the following values and Save.
- Registry Path
- Registry Value
- Process Name
- Service Name** and click
Note
Once a script is created, it is listed in the Scripts page.To apply and schedule scripts:
- Click the script.
- Click Apply script to devices.
- Select the client and the devices.
- To run the script instantly, click Run Now.
- To schedule a script, click Schedule, provide scheduled time for the script, and Save.
Scenario
In this scenario, as a script is scheduled and assigned.
Scenario: A user wants to create a script using Powershell for monitoring and reporting the disk space, and assign the script to all devices and schedule the script to run every Friday at 6 PM.
Solution: Create a script and assign it to the devices and then provide the schedule.
Samples: Custom scripts
This section provides sample scripts for creating custom jobs.
Custom job using VBS
- Category: Firewalls
- Command/FileName: firewall_disable.vbs
- Description: Disable Firewall
strComputer = "."
Set objWMIService = GetObject _
("winmgmts:{authenticationLevel=pktPrivacy}\\" _
& strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery _
("Select * from Win32_Processor")
For Each objItem in colItems
Wscript.Echo "DeviceID : " & _
objItem.DeviceID
Wscript.Echo "CPU Usage in Percent : " & _
objItem.LoadPercentage
Wscript.Echo "Name : " & _
objItem.Name
Next
Custom job using Python
Get last logged user:
Category: Linux
Command/FileName: python
Description: Get last logged user
#! /usr/bin/env python
import os, re, pwd, sys, time, struct, commands
from datetime import datetime
def executeCommand(cmd, args=[], ignoreOnError=True):
for arg in args:
cmd = cmd + ' ' + str(arg)
try:
result = commands.getstatusoutput(cmd)
except Exception, errmsg:
return 1, 'Exception caught - ' + str(errmsg)
if result[0] != 0 and ignoreOnError == False:
raise Exception("Failed to execute command: " + cmd)
return result[0] >> 8 , result[1]
def formatDateTime(dateStr):
try:
'''
****** Tue Feb 7 10:52:12 IST 2012 ******
%Y-%m-%d %I:%M%p => 2012-02-07 10:20AM
%Y-%m %a%I%p => 2012-02 Tue10AM
%e%b%y => 7Feb12 *Not added in Array*
%d%b%y => 07Feb12
%Y %m %d => 2012 02 07
%d/%m/%y => 07/02/12
%m/%d/%Y %H:%M:%S => 02/07/2012 10:53:26
%Y/%m/%d %H:%M:%S %Z => 2012/02/07 10:53:26 IST
%a %b %d %H:%M:%S %Z => Tue Feb 07 10:56:35 IST
%a %b %d %H:%M %Y %Z => Tue Feb 07 10:53 2012 IST
%a %b %d %H:%M:%S %Y %Z => Tue Feb 07 11:12:48 2012 IST
%a %b %d %H:%M %Y => Tue Feb 07 10:53 2012
%a %b %d %H:%M:%S %Y => Tue Feb 7 11:12:48 2012
%a %d %b %Y %I:%M:%S %p %Z => Tue 07 Feb 2012 10:57:12 AM IST
%Y-%m-%d %Z => 2012-02-07 IST
%Y-%m-%d %H:%M %Z => 2012-02-07 10:58 IST
%m/%d/%y %H:%M %p %Z => 2/7/12 10:58 AM IST
'''
try_formats = ['%Y-%m-%d %H:%M %Z', '%Y-%m-%d %Z', '%a %d %b %Y %I:%M:%S %p %Z', '%a %b %d %H:%M:%S %Y %Z', '%a %b %d :%H:%M:%S %Z', '%a %b %d %H:%M %Y %Z', '%Y/%m/%d %H:%M:%S %Z', '%d/%m/%y', '%Y %m %d', '%Y-%m %a%I%p', '%d%b%y', '%Y-%m-%d %I:%M%p', :'%m/%d/%y %H:%M %p %Z', '%a %b %d %H:%M %Y', '%a %b %d %H:%M:%S %Y', '%m/%d/%Y %H:%M:%S']
UTC_OFFSET_TIMEDELTA = datetime.utcnow() - datetime.now()
parsed = None
for tformat in try_formats:
try:
if sys.version_info >= (2, 6):
parsed = datetime.strptime(dateStr, tformat)
else:
parsed = datetime(*(time.strptime(dateStr, tformat)[0:6]))
break
except:
pass
if parsed != None:
result_utc_time = (parsed - UTC_OFFSET_TIMEDELTA).strftime('%F %T')
return result_utc_time
except:
return dateStr
def parseLastLogRecord(llfile, uid, preserve = False):
""" Returns [int(unix_time), string(device), string(host)] from the lastlog formatted file object, set preserve = True to preserve :your position within the file"""
"""
LastLogFormat
x86_64 : =L32s256s
i386 : =L32s256s or L32s256s
ia64 : ?
Reference : [http://code.activestate.com/recipes/496768-last-login-record-extraction](http://code.activestate.com/recipes/496768-last-login-record-extraction)
"""
position = llfile.tell()
recordsize = struct.calcsize('=L32s256s')
llfile.seek(recordsize * uid)
data = llfile.read(recordsize)
if preserve:
llfile.seek(position)
try:
returnlist = list(struct.unpack('=L32s256s',data))
returnlist[1] = returnlist[1][:returnlist[1].index('x00')]
returnlist[2] = returnlist[2][:returnlist[2].index('x00')]
#returnlist[1] = returnlist[1].replace('x00','')
#returnlist[2] = returnlist[2].replace('x00','')
return returnlist
except:
return False
def getLastLoggedUserDetails():
lastlogfile = '/var/log/lastlog'
lluser = lldate = ""
if os.path.exists(lastlogfile):
try:
llfile = open(lastlogfile, 'r')
except:
logger.error("getLastLoggedUserDetails: Unable to open lastlog file")
llts = 0
try:
for user in pwd.getpwall():
record = parseLastLogRecord(llfile, user[2])
if record and record[0] > 0:
''' Order by time to get the last logged used details '''
print '%16stt%st%s' % (user[0], time.ctime(record[0]), record[2])
if llts < int(record[0]):
lluser = user[0]
llts = int(record[0])
elif record:
''' The user never logged into the device '''
continue
#print '%16st\tNever logged in' % (user[0],)
except:
pass
llfile.close()
lldate_string = time.ctime(llts) + " " + time.tzname[0]
lldate = formatDateTime(lldate_string)
return lluser, lldate
else:
lastlogArr = executeCommand("last | head")[1].split("\n")
for lastlog in lastlogArr:
lastlog = lastlog.strip()
matchObj = re.match(r"^(\S+)\s+\S+\s+\S+\s+(\S+\s+\S+\s+\S+\s+\S+)\s+.*", lastlog, re.M|re.I)
if matchObj:
lluser = matchObj.group(1)
lldateStr = matchObj.group(2)
try:
lldateStr = lldateStr + " " + str(time.localtime().tm_year) + " " + time.tzname[0]
except:
pass
lldate = formatDateTime(lldateStr)
if lluser != 'reboot':
break
return lluser, lldate
lastloggeduser, lastloggedtime = getLastLoggedUserDetails()
print
print "Last Logged User: " + lastloggeduser
print "Last Logged Time: " + lastloggedtime
dtime
Custom job using Powershell
- Category: Quick Books Maintenance
- Command/FileName: RestartQuickBooksService.ps1
- Description: RestartQuickBooksService
$service = Get-Service | where {$_.Name -like "QuickBooksD*" -or $_.DisplayName -like "QuickBooksD*" -or $_.Name -like "QBCF*"}
if($service.Count)
{
Restart-Service -DisplayName $service[0].DisplayName
write-host $service[0].DisplayName " Service Restarted"
Restart-Service -DisplayName $service[1].DisplayName
write-host $service[1].DisplayName " Service Restarted"
}
elseif($service )
{
Restart-Service -DisplayName $service.DisplayName
write-host $service.DisplayName " Service Restarted"
}
else
{
write-host " QuickBooks service Not available"
}