# Scripts

## 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.\
&#x20;Types of execution that OpsRamp provides:\
&#x20;![](https://docs.opsramp.com/wp-content/uploads/2017/08/Script-Type.png)

## Scope of Scripts

**Scripts are partner specific**. Example: A script can be created, assigned and scheduled at partner level as well as client level devices.

## Scenario: Schedule and assign a script

**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. See below for instructions to create, assign and schedule a script.

## Create, Validate and Apply a Script

In addition to native jobs, a user can create custom scripts and then apply to devices. Example: See above scenario.

**Instructions for creating a script**

1. Login to OpsRamp.
2. On the drop-down menu, click **Automation**.
3. Select **Scripts**. Scheduled Scripts page appears.\
   &#x20;![](https://docs.opsramp.com/wp-content/uploads/2017/08/New-UI-Automation-1-400x237.png)
4. In **All Scripts** tab, click ![](https://docs.opsramp.com/wp-content/uploads/2017/07/Expand_button.png) Add and then click **Add Script**.
5. Provide the script details.
6. Select the **Script Type** from the drop-down and provide the **Command/File Name**.
7. If a scripting language is provided as execution type, example VBS, then copy the script in the **Script** section.
8. Click **Add Params**.
9. To validate the script, provide the **Registry Path**, **Registry Value**, **Process Name** and **Service Name** and then click **Save**.

**Instructions for applying and scheduling a script**

Once the script is created it is listed in Scripts page. To apply script and to schedule, click on the script.

1. Click **Apply script to devices**.
2. Select the client and the devices.
3. To run the script instantly, click **Run Now**.
4. To schedule a script, click **Schedule** and provide scheduled time for the script and then click **Save**.

## Appendix: Custom Scripts

### Custom Job using VBS Script

**Category**: Firewalls\
&#x20;**Command/FileName**: firewall\_disable.vbs\
&#x20;**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 Script

Get last logged user\
&#x20;**Category**: Linux\
&#x20;**Command/FileName**: python\
&#x20;**Description**: Get last logged user

```
#! /usr/bin/env pytho
    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
        """
      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 '%16s\t\t%s\t%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 '%16s\t\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 Script

**Category**: Quick Books Maintenance\
&#x20;**Command/FileName**: RestartQuickBooksService.ps1\
&#x20;**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"
 }
```
