Top
JohnKlann / scripting

Bash Execute Script At Specific Time Without Cron

#!/bin/bash

#Set Execution time to 3:15:01 PM
TimeToExecute="15:15:01"

while true; do
    #Convert Execution Time to Epoch
    GoalTime=$(date -d "$TimeToExecute" +"%s")
    #Get epoch of 12:00:00 AM
    BaseTime=$(date -d "00:00:00" +"%s")
    #Get the current epoch
    CurrentTime=$(date +"%s")
    #Get the epoch difference between the goal execution time and current time
    TimeDifference=$(date -d "0 $GoalTime seconds - $CurrentTime seconds" +"%s")
    #Get the difference between the "TimeDifference" and 12:00:00 AM 
    BaseDifference=$(( $BaseTime -$TimeDifference ))
    #If BaseDifference is equal to zero then execute script
    if [[ "$BaseDifference" -eq 0 ]]; then
            echo "Executing Script- date"
            /path/to/my/script.sh 
    fi
    sleep 1
done

 

jklann

List Files with their absolute path using Bash

function lsfp(){
local dirpath="$1"
local recurse="$2"

if [[ "$dirpath" == "" ]]; then
echo "no path provided!"
exit
else
local dirpath=$(echo "$dirpath" | sed 's:/$::g')
fi

local DirArr=($(ls -l "$dirpath" | grep -P "^d" | grep -oP "(?<= \d\d\:\d\d ).*"))
local FileArr=($(ls -l $dirpath | grep -oP "(?<= \d\d\:\d\d ).*$"))

for file in "${FileArr[@]}"; do
local fp="$dirpath/$file"
echo "$fp"
done

if [[ "$recurse" != "" ]]; then
for direc in "${DirArr[@]}"; do
lsfp "$dirpath/$direc" "$recurse"
done
fi
}
jklann

Basic Powershell DNS Enumeration Module

This one will allow you too enumerate dns and filter by exclusion or inclusion of different record types.

<# 
    .SYNOPSIS simplifies dns enum and record type filtering 
    .EXAMPLE Ex1: (use default zone and server, return all records found) .\Get-DNSEnum.ps1 or 
            Ex2: (specifiy zone and server, return all except SVR and NS Records) .\Get-DNSEnum.ps1 -Zone domain.local -dc DomainControllerName -Exlcude 'SVR','NS' 
    .DESCRIPTION Detailed Syntax: .\Get-DNSEnum.ps -[Zone|z] dnszone -[Domain|dc] dns or domaincontroller -[ExcludeList|e] 'record','type(s)','to','exclude' -[IncludeList|i] 'record','type(s)','to','include' 
    .NOTES Author: John Klann 
#>
[cmdletbinding()]
Param
(
    [Parameter(Mandatory=$False, HelpMessage='Dns Zone aka domain' )]
    [Alias('z')]
    [string]$Zone = 'default zone / domain',
    [Parameter(Mandatory=$False, HelpMessage='Domain Controller')]
    [Alias('dc')]
    [string]$Domain = 'default domain controller',
    [Parameter(Mandatory=$False, HelpMessage='Record Type Include list')]
    [Alias('i')]
    [string[]]$IncludeList,
    [Parameter(Mandatory=$False, HelpMessage='Record Type Exclude List')]
    [Alias('e')]
    [string[]]$ExcludeList
)

if ($ExcludeList.Count -gt 0)
{
    Get-DnsServerResourceRecord -ZoneName $Zone -ComputerName $Domain | Where-Object { $_.RecordType -notin $ExcludeList }
}
elseif ($IncludeList.Count -gt 0)
{
    Get-DnsServerResourceRecord -ZoneName $Zone -ComputerName $Domain | Where-Object { $_.RecordType -in $IncludeList }
}
else
{
    Get-DnsServerResourceRecord -ZoneName $Zone -ComputerName $Domain
}

 

jklann

How to check if a port is in Use and What Process is running on it

So really simple way to check if a port is in use and by what process.

  1. Method 1 CMD:
  2. Open Admin Command Prompt:
    netstat -ano | findstr "portnumber"
    

     

  3. Example using default rdp port:
    netstat -ano | findstr "3389"
    
  4. Output:
    windows_command_prompt_netstat_ano_rdp_port

 

Method 2 PowerShell:

  1. Open Admin PowerShell Prompt:
    1. Command:
      &amp;nbsp;netstat -ano | findstr "portnumber" | Select-String -Pattern "\d+$" -AllMatches | % {$_.Matches } | foreach { tasklist |select-string -Pattern $_.Value } | Get-Unique
      
    2. Example using port 80:
      1. Note: this could probably be a lot cleaner but hey i did it in 5 minutes in 1 oneline :) !
         netstat -ano | findstr "80" | Select-String -Pattern "\d+$" -AllMatches |  % {$_.Matches } | foreach { tasklist |select-string -Pattern $_.Value } | Get-Unique
        
    3. Output:
      windows_powershell_netstat_ano_port_number_tasklist_processname_process_stats

Method 3 CMD with Cygwin:

  1. This will get all of the process running on a particular port.
    1. Note: you will need (Cygwin bin directory pathed in your environment See how to do this here: How to add environment Paths via command line (cmd, powershell) )
      1. Open Admin cmd Prompt:
        1. Command:
           for /f "delims=" %a in ('netstat -ano ^| grep "portnumber" ^| grep -m1 -oP "[\d]{1,6}$"') do @set pid=%a | tasklist | grep %a 
      2. Example using port 80:
         for /f "delims=" %a in ('netstat -ano ^| grep "80" ^| grep -m1 -oP "[\d]{1,6}$"') do @set pid=%a | tasklist | grep %a 
      3. Output:
        windows_command_prompt_cygwin_netstat_ano_grep_port_number_tasklist_processname
jklann

How to add environment Paths via command line (cmd, powershell)

Here’s a quick one lol.

Quick Note: This will temporarily set the Environment path with in that shell. If you want a more permanent solution you will have to added through windows environment variables config then logoff and back in.

  1. In CMD or Powershell prompt Run this command:
    1. Syntax:
       PATH %PATH%;c:\path\you\want\to\add\ 
  2. Example Using Cygwin Bin directory:
     PATH %PATH%;c:\dev\cyg\bin\ 
  3. Output:

windows_command_prompt_cmd_powershell_prompt_ps_set_environement_path

jklann

Basic Array Syntax, Iteration, Manipulation

So I recently took on a project where one of the requirements is that it has to be completed in Linux Bash and have as little outside dependencies as possible. So As Bash does not support multi-dimensional arrays, i’ll just cover array basics for now lol.

  1. Array Declaration:
    ARR=()
    
  2. Adding to Array
    1. values
      ARR+=('value')
      
    2. variables
      ARR+=("$VAR")
      
  3. Getting Array Length
    ARRLEN=${#ARR[@]}
    
  4. Iterating/Looping through Array (be mindful of your spacing)
    for (( i=0; i&lt;${ARRLEN}; i++ )); do
    	echo "${ARR[$i]}"
    done
    
  5. Putting it all together:
    #!/bin/bash
    
    ARR=()
    
    VAR="World"
    
    echo "adding value to array"
    
    ARR+=('hello')
    
    ARRLEN=${#ARR[@]}
    
    echo "Array length is now: $ARRLEN"
    
    echo "adding variable to array"
    
    ARR+=("$VAR")
    
    ARRLEN=${#ARR[@]}
    
    echo "Array length is now: $ARRLEN"
    
    echo "loop through array"
    
    for (( i=0; i&lt;${ARRLEN}; i++ )); do
            echo "Array Key/Index: $i holds Value: ${ARR[$i]}"
    done
    
  6. Returns:

linux_bash_basic_array_operations

jklann
sqlCode

SQL Convert Size in Bytes to Human Readable Units

Came across a lot of databases that hold size of objects, files, whatever in bytes which is not the easiest to glance at and easily understand. So I wrote a basic SQL function to convert size in bytes to human readable format. The goal being that the output is greater than or equal to 1.0, that is automatically gets loops until it is less than 1.0 then stops at the previous division allowing for an easy to understand yet automatic format. I also have it round to 2 decimal places.

--set database to be used
--USE BEDB;
--checks if function already exists if it does it drops and re-adds it otherwise it adds it
IF OBJECT_ID (N'dbo.f_ConvertSize') IS NOT NULL
    BEGIN
        DROP FUNCTION Dbo.F_ConvertSize;
        PRINT 'Function f_ConvertSize Alread Exists, Deleting it and Adding it back now'
    END
ELSE
    BEGIN
        PRINT 'Function f_ConvertSize Does Not Exist, Adding it now.'
    END

GO
--creates function that
--parameter: size in bytes
--returns: single value nvarchar of converted size to readable format
CREATE FUNCTION Dbo.F_ConvertSize ( @rawSize FLOAT )
Returns NVARCHAR(12)
    BEGIN
        --creates processing variables
        --div = value to divide by
        --counter = number of times divided
        DECLARE @div INT,@counter INT
        --unit is used to capture the unit measure used in the output
        DECLARE @unit NVARCHAR(3)
        --the sizes table variable is used to store the different units
        DECLARE @sizes TABLE (Id INT,Unit NVARCHAR(3))
        INSERT @sizes(Id,Unit)
        VALUES(1,' B'),(2,' KB'),(3,' MB'),(4,' GB'),(5,' TB')
        --sets div and counter
        SET @div = 1024
        SET @counter = 1
        --while loop used to perform the conversion with condition clause that requires the size to be greater or equal to 1
        WHILE @rawSize >= 1 AND @counter <= 5
            BEGIN
                --breaks if the size is less than 1 after division
                --else it sets the rawsize to the rawsize divided by the div then it sets the counter to +=1
                IF @rawSize/@div < 1
                    BREAK
                ELSE
                    SET @rawSize = @rawSize/@div
                    SET @counter += 1
            END
        --gets units used from the units table variable
        SELECT @unit = Unit
        FROM @sizes
        WHERE Id = @counter
        --converts the new size to varchar and rounds it to 2 decimal places then adds the units and returns the output
        RETURN CAST(ROUND(@rawSize,2) AS NVARCHAR(50))+@unit
    END
jklann

How to display HTML code in an adobe flex desktop application the Easy Way

So am very new to adobe flex and really don’t plan on using it that much other than to generate a quick ui for something simple.

In this case I wanted to use flex to create a small desktop app to load a live monitor website. In this case the default <mx:HTML location=”http://site.com” was not loading the site at all so was digging all over the place for a solution. I came across expensive libraries that could do it, and a pretty cool github project called Flex-iFrame if you want to get complicated with it. Needless to say I came up with my own solution.

The idea is that the <mx:HTML location=”  can point to a location html file as well. So I wrote a quick html page with an iframe to the website I wanted to monitor. Next I copied the html file to the /src/ directory of the adobe flex project folder.  Finally I added the line <mx:HTML location=”myhtmlfile.html” /> . This worked great for my application and seems to be the easiest way to perform this process.

Steps:

1.)  Create your adobe flex project:

create_new_flex_project

create_new_flex_project

2.)  Name the projected whatever you want and be sure to select the Application type as Desktop then select finish:

create_new_flex_project_settings

create_new_flex_project_settings

3.)  Next create the html file with the html you want to display in my case an iframe:

<html>
<head>
</head>
<body>
<iframe src=”https://site.com/livemonitoring/stuff/display&type=Grid height=”400px”></ifram>
</body>
</html>

Note:  you can add jquery and css file links as well if they are local to your system make sure you copy them with the html file in the next step.

4.)  Now that you have created the html file copy it and any other dependent files to your flex projects src directory. Typically the path will be something like:

C:\users\username\adobe flash builder 4.7\ProjectName\src

Note: This is also the directory where the projects  .mxml and  -app.xml  will be located.

5.) The last part for this will be to add the flex html location code to view the file add something like the following to your flex project.

<mx:HTML location=”yourhtmlfile.html” />

 

flex_html_code

flex_html_code

 

Note: From  here you can build the rest of your app and style it the way you would like.

6.) Finally run your app!

flex_html_app_running

flex_html_app_running

 

jklann