Enumerating the If... Then: Scripts

Monday, September 21, 2009

VBScript: Sendmail script


main()

function IfYouGetCaught(strErr)

if len(strErr) > 1 then
strErrorLine = strErrorLine + strErr
strErrorLine = strErrorLine + vbnewline + vbnewline
end if

strErrorLine = strErrorLine + "usage: cscript sendmail.vbs /from:[from address] /to:[address1,address2] [/subject:[subject]] [/body:[message] [/attachment:path1,path 2]" & vbnewline & _
vbnewline & _
"The arguments subject and body are optional." & vbnewline & _
vbnewline & _
"If /body:stdin is specified, then body will accept stdin as the body of the Email."
wscript.echo strErrorLine
WScript.Quit
end function

Function IsUsingCscript()
Dim iPosition
iPosition = InStr( LCase(WScript.FullName) , "cscript.exe" )
If iPosition = 0 Then IsUsingCscript = False Else IsUsingCscript = True
End Function


function main()

Set objMessage = CreateObject("CDO.Message")

If Not IsUsingCscript() Then
IfYouGetCaught("You must use cscript.exe to run this script.")
End If


If WScript.Arguments.count < 1 then
IfYouGetCaught("default")
end If

if len(WScript.Arguments.Named("from")) < 1 then
IfYouGetCaught("You need to provide a from address.")
else
objMessage.From = WScript.Arguments.Named("from")
end if

if len(WScript.Arguments.Named("to")) < 1 then
IfYouGetCaught("You need to provide at least one to address.")
else
objMessage.To = WScript.Arguments.Named("to")
' ToAddresses = split(WScript.Arguments.Named("to"), ",")
end if

if len(WScript.Arguments.Named("subject")) < 1 then
else
objMessage.Subject = WScript.Arguments.Named("subject")
' ToAddresses = split(WScript.Arguments.Named("to"), ",")
end if


if len(WScript.Arguments.Named("attachment")) > 1 then

Attachments = split(WScript.Arguments.Named("attachment"), ",")

if ubound(Attachments) >= 0 then
for each item in Attachments
objMessage.AddAttachment item
next
end if

end if



'accept stdin as objMessage.Textbody
if ( WScript.Arguments.Named("body") = "stdin" ) then
objMessage.Textbody = Wscript.StdIn.ReadAll()
else
objMessage.Textbody = WScript.Arguments.Named("body")
end if



objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "www.dynamicfunds.com"
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objMessage.Configuration.Fields.Update

objMessage.Send

end function

Wednesday, April 15, 2009

C#/.NET: Invoke a WMI method on a remote machine

  private void button7_Click(object sender, EventArgs e)
{

string TargetMachine = textBox2.Text;



ManagementPath path = new ManagementPath("\\\\" + TargetMachine + "\\root\\microsoftdfs");

ManagementScope scope = new ManagementScope(path);

SelectQuery msQuery = new SelectQuery("SELECT * FROM DfsrReplicatedFolderInfo");

ManagementObjectSearcher searchProcedure = new ManagementObjectSearcher(scope, msQuery);



object[] methodArgs = { "" };


foreach (ManagementObject item in searchProcedure.Get())
{
try
{
item.InvokeMethod("GetVersionVector", methodArgs);

foreach (string returned in methodArgs)
{
MessageBox.Show(returned.ToString());
}
}

catch (SystemException excep)
{
MessageBox.Show(excep.Message);
}

}
}

Friday, March 20, 2009

C#/.NET: Seriously Refresh Desktop Icons / Clear Desktop Icon Cache

Tested.
In use at work.


using System;
using System.Runtime.InteropServices;
using Microsoft.Win32;

namespace ConsoleApplication1
{
class Program
{

[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern long SendMessageTimeout(
int hWnd,
int Msg,
int wParam,
string lParam,
int fuFlags,
int uTimeout,
out int lpdwResult
);


// http://www.programmingforums.org/post87847-9.html

static void Main(string[] args)
{

// get the the original Shell Icon Size registry string value to 4
RegistryKey k = Registry.CurrentUser.OpenSubKey("Control Panel").OpenSubKey("Desktop").OpenSubKey("WindowMetrics", true);
Object OriginalIconSize = k.GetValue("Shell Icon Size");

// set the Shell Icon Size registry string value to 4
k.SetValue("Shell Icon Size", "33");
k.Flush(); k.Close();

// broadcast WM_SETTINGCHANGE to all window handles
int res = 0;
SendMessageTimeout(0xffff, 0x001A, 0, "", 0x0002, 5000, out res);
//SendMessageTimeout(HWD_BROADCAST,WM_SETTINGCHANGE,0,"",SMTO_ABORTIFHUNG,5 seconds, return result to res)

// set the Shell Icon Size registry string value to original value
k = Registry.CurrentUser.OpenSubKey("Control Panel").OpenSubKey("Desktop").OpenSubKey("WindowMetrics", true);
k.SetValue("Shell Icon Size", OriginalIconSize);
k.Flush(); k.Close();

SendMessageTimeout(0xffff, 0x001A, 0, "", 0x0002, 5000, out res);


}
}
}


Interesting

Wednesday, March 18, 2009

vbs: Query a list of workstations for local administrators

Note that this is for machines that are English language only.

Tested.
In use at work.


Option Explicit

Const LogFile = "LocalAdmins.log"
Const resultFile = "LocalAdministratorsMembership.csv"
Const inputFile = "workstations.txt"


Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")

Dim shl
Set shl = WScript.CreateObject("WScript.Shell")

Dim fil
Set fil = fso.OpenTextFile(inputFile)

Dim results
Set results = fso.CreateTextFile(resultFile, True)

WriteToLog "Beginning Pass of " & inputFile & " at " & Now()
'WScript.Echo "Beginning Pass of " & inputFile & " at " & Now()
On Error Resume Next

Dim grp
Dim line
Dim exec
Dim pingResults
Dim member

While Not fil.AtEndOfStream
line = fil.ReadLine

Set exec = shl.Exec("ping -n 2 -w 1000 " & line)
pingResults = LCase(exec.StdOut.ReadAll)

If InStr(pingResults, "reply from") Then
WriteToLog line & " responded to ping"
'WScript.Echo line & " responded to ping"

'On Error Resume Next

Set grp = GetObject("WinNT://" & line & "/Administrators")

'WScript.Echo line & ", Administrators"
results.WriteLine line & ",Administrators,"

For Each member In grp.Members
'WScript.Echo "Administrators: " & member.Name
WriteToLog line & ": Administrators - " & member.Name
results.WriteLine ",," & member.Name
Next
Else
WriteToLog line & " did not respond to ping"
'WScript.Echo line & " did not respond to ping"
End If
Wend

results.Close

Sub WriteToLog(LogData)
On Error Resume Next

Dim fil
'8 = ForAppending
Set fil = fso.OpenTextFile(LogFile, 8, True)

fil.WriteLine(LogData)

fil.Close
Set fil = Nothing
End Sub

wscript.echo "Stick a fork in me"

Friday, February 20, 2009

batch: remote command prompt with the quickness

Tested.
In use at work.


tini.exe, from ntsecurity.nu, is a telnet server that is a remote command prompt.

Embedded in this script is starting and stopping a process remotely using wmic.


@echo off

:BOF
cls
set /p targethost=Target host:

if [%targethost%] == [] GOTO YOUSTUPID
pause

copy tini.exe \\%targethost%\c$\windows\system32\
WMIC /node:"%targethost%" PROCESS CALL Create "c:\windows\system32\tini.exe"

echo.
echo.

echo In new window, hit enter.
echo.

start "Tiny interactive network telnet" telnet %targethost% 7777

echo To kill remote command prompt...
pause

WMIC /node:"%targethost%" PROCESS where name="tini.exe" CALL Terminate 0

goto EOF


:YOUSTUPID

echo.
echo You must enter a target host
pause
goto BOF

Monday, February 02, 2009

python: TrendMicro Updater + drive scanner + report emailer

Tested.
In use at work.


import urllib, sys, zipfile, time, os, subprocess


def main():
WebPageToSearch = "http://www.trendmicro.com/download/viruspattern.asp"
ToFind_start = "http://www.trendmicro.com/ftp/products/pattern/lpt"
ToFind_end = ".zip"

LocalVirusDefPath = r"C:\Program Files\Trend Micro\Client Server Security Agent" + "\\"

AntiVirusExec = r"C:\Program Files\Trend Micro\Client Server Security Agent\vscanwin32.com"

AntiVirusArgs = ["/S","/C","/Q","/LD"]

AntiVirusDriveToScan = ["d:"]

if os.path.exists("detect.log"):
os.remove("detect.log")

TrendMicroDefURL = urllib.urlopen(WebPageToSearch).read()

VirusDefURL = ""
for i in range(TrendMicroDefURL.find(ToFind_start),TrendMicroDefURL.find(ToFind_end) + 4):
VirusDefURL = VirusDefURL + TrendMicroDefURL[i]


#http://www.trendmicro.com/ftp/products/pattern/lpt795.zip
Filename = VirusDefURL.split("/")
Filename = Filename[len(Filename)-1]
LocalPath = LocalVirusDefPath + Filename

if os.path.exists(LocalVirusDefPath + Filename):
print "File exists: " + LocalVirusDefPath + Filename
else:
print "Retriving " + VirusDefURL + " to " + LocalPath + "..."
urllib.urlretrieve(VirusDefURL, LocalPath)

DefFile = LocalVirusDefPath + "lpt$vpn." + Filename[3:Filename.find(".zip")]

if os.path.exists(DefFile):
print "File exists: " + DefFile
else:
print "Extracting..."
zipFile = zipfile.ZipFile(LocalPath, 'r')
zipFile.extractall(LocalVirusDefPath)
for name in zipFile.namelist():
print name

zipFile = None
## os.remove(DefFile)

for drive in AntiVirusDriveToScan:
print "Performing virus scan on the " + drive + " drive..."
cmd = [AntiVirusExec, AntiVirusArgs, drive]
procexec = subprocess.Popen( cmd )


TaskListCheck( "vscanwin32", True )
EnumerateFile ( "detect.log" )
print "Report will be emailed to email@domain.com"


def TaskListCheck( passSearchStr, ShallIWait ):
cmd = r"c:\windows\system32\tasklist.exe"
TaskListCheck = True

if ShallIWait == True:
while TaskListCheck:
procexec = subprocess.Popen ( cmd, stdout=subprocess.PIPE, universal_newlines=True)
stdout_value = (procexec.communicate()[0]).lower()
if stdout_value.find(passSearchStr) > 0:
print passSearchStr + " found."
time.sleep(5)
else:
TaskListCheck = False
else:
procexec = subprocess.Popen ( cmd, stdout=subprocess.PIPE, universal_newlines=True)
stdout_value = (procexec.communicate()[0]).lower()
if stdout_value.find(passSearchStr) > 0:
TaskListCheck = True
else:
TaskListCheck = False

def EnumerateFile( passFileName ):
objFile = open ( passFileName )

MailMsg = "Scan completed. The following is a list of infected files:/n"

for line in objFile:
MailMsg = MailMsg + line
objFile.close

from socket import gethostname
Mailer( "email@domain.com", "email@domain.com", "Virus Scan Results for " + gethostname(), MailMsg)


def Mailer( passFromAddr, passToAddr, passSubject, passMessage ):

import smtplib

FROM = passFromAddr
TO = passToAddr
SUBJECT = passSubject
TEXT = passMessage

message = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n %s" % (FROM, TO, SUBJECT, TEXT)

server = smtplib.SMTP( "www.domain.com" )
errStatus = server.sendmail(FROM, TO, message)
for errorItem in errStatus:
print ""
print "SMTP Error: " + errorItem
server.quit()
return

main()

Friday, December 19, 2008

python: LogParser + Emailer

Tested.
In use at work.

"If I return too many results, I cause a BSOD. I eat your non-paged pool for breakfast."

to do: if query returns over 50 lines, prompt to continue... option to suppress this prompt. option to suppress command-line output.
Currently, the --parse option must fall before any other option in order to have the program function properly. This is to reduce the use of Global variables.

### input: me.py --file [syslog file] --find [find string] | --parse [comma-seperated list of tokens],[delimiter] | --email [email address]
### --email is an optional argument, and can be a single email address or a semi-colon seperated list
### output: return line(s) where string is located

### handle arguments (requiring both --file and --find)
### check if input file exists
### open file for read
#### read line by line checking to see if --find [string] is located
#### create an array and write the lines to it
### close file
### print contents of array
### if email argument exists, send email to given address

import sys
import getopt
import os


def main():

Arguments()

def Arguments():

# the main purpose of this function is to only evaluate arguments.
# it is not really to be used to perform other functions, but to call other functions.


try:
opts, args = getopt.getopt(sys.argv[1:], "f:,q:,p:,e:,d:,", ["file=", "find=", "parse=", "email=",])
except getopt.GetoptError, err:
YouErroredMe(str(err))


if len(sys.argv) == 1:
YouNeedHelp()


for opt, arg in opts:

if opt in ( "--parse" ): #take delimiter, and tokens
try:
#take the characters in the string to the left of the first : (from the left) :
strTokens = arg[0:arg.find(":")]
#make a list of these comma-seperated tokens, by using the string.split function :
global Tokens
Tokens = strTokens.split(",")
if len(Tokens) < 1:
YouErroredMe("You must give me some tokens. You want me to return nothing?")
#take the characters in the string to the right of the first : (from the left) :
global Delimiter
Delimiter = arg[arg.find(":")+1:len(arg)]
if len(Delimiter) < 1:
YouErroredMe("You must give me a delimiter with your tokens. You want me to return the whole line?")
except:
continue
elif opt in ( "--file" ):
strInputFile = arg
CheckIfFileExists( strInputFile )
elif opt in ( "--find" ):
strFindString = arg
CheckForStringInFile( strInputFile, strFindString )
elif opt in ("--email"):
try: #should be checking if Lines exists/has any members, what the vartype is???
strEmailAddress = arg
strEmailAddress = strEmailAddress.split(";")
Mailer( "ParserAlert", strEmailAddress, "Found " + strFindString + " in " + strInputFile, Lines)
except:
continue



def CheckIfFileExists( passFileName ):

if os.path.getsize( passFileName ) == 0:
YouErroredMe( "The file provided is 0 long. Give me some sugar." )

def CheckForStringInFile( passFileName, passFindString ):
objFile = open ( passFileName )

global Lines
Lines = "\n"
FoundLines = []
for line in objFile:
if line.count( passFindString ) <> 0:
FoundLines.append(line)


for line in FoundLines:

#if parse tokens and delimiter exist...
try:
if len(Tokens) > 0:
for item in Tokens:
Lines = Lines + line.split(str(Delimiter))[int(item)] + "\n"
except:
Lines = Lines + line

print Lines


if len(FoundLines) < 1:
print "String " + passFindString + " not found in file " + passFileName + "."
objFile.close
sys.exit()

objFile.close



def Mailer( passFromAddr, passToAddr, passSubject, passMessage ):

import smtplib

FROM = passFromAddr
TO = passToAddr
SUBJECT = passSubject
TEXT = passMessage

# Prepare actual message
message = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n %s" % (FROM, TO, SUBJECT, TEXT)

# Send the mail
server = smtplib.SMTP( "domain.com" )
errStatus = server.sendmail(FROM, TO, message)
for errorItem in errStatus:
print ""
print "SMTP Error: " + errorItem
## LogMe( "ERROR,smtp,%m,%d,%Y,%H:%M:%S,domain.com," + FROM + "," + TO + "," + errorItem )
server.quit()
return





def YouErroredMe( passError ):

print ""
print passError
print "/\\__/\\"
print ""
YouNeedHelp()
return


def YouNeedHelp():

print ""
print "input: me.py --parse [tokens]:[delimiter] --file [log file] --find [find string] --email [email address]"
print ""
print ""
print "--parse is an optional argument and must be before --file or --find. It can be a comma-seperated list of tokens, followed by a colon, followed by the delimiter. It will return this given subset only."
print "--email is an optional argument. It can be a single Email address, or a semi-colon seperated list."
print ""
print "output: return line(s) where string is located"
print ""
print "Examples:"
print "me.py --file syslog.txt --find subtype=sslvpn --email mbrown@domain.com"
print "me.py --file syslog.txt --find subtype=sslvpn --email mbrown@domain.com;helpdesk@domain.com"
print "me.py --parse 5,6,7:; --file syslog.txt --find subtype=sslvpn --email mbrown@domain.com;helpdesk@domain.com"
sys.exit()
return


main()


Output from a syslog from a Fortinet:


logparser.py --parse 0,4,9,10,11,12,13,14:, --file syslog.log --find sslvpn


Jan 4 13:27:55 192.168.1.1 date=2009-01-04
log_id=0132099601
user="username"
rip="4.2.2.1"
action=login
status=success
reason=none
msg="User username login successfully from 4.2.2.1"

Jan 4 13:36:13 192.168.1.1 date=2009-01-04
log_id=0132099604
user="username"
rip=4.2.2.1
action=logout
status=success
reason=timeout
msg="SSL VPN web access session timeout from 4.2.2.1"