Spoofing MAC Addresses

I developed this bash script for my MacBook Air to simply the process of getting devices without a keyboard and mouse authenticated to a wireless network that requires a userid and password, which in my case were an Amazon Echo and Amazon Fire TV Cube that we wanted connected at our rental condo.  This was accomplished by setting the MacBook Air’s MAC address to the MAC address of each of the Amazon devices, which allowed the MacBook Air to complete the authentication process.

-------------
#!/usr/bin/env bash
#
# This script is used to temporarily change the Macbook Air's MAC address
# to the Amazon Echo 3 and the Amazon Fire TV Cube.  This will allow the
# Macbook Air to authenticate to networks that require a userid and password
# by spoofing their MAC addresses.
#

echo Do you want to configure the Amazon Echo 3? [y/n]
read answer
if [ $answer == 'y' ]
then
  echo Make sure the Amazon Echo 3 is powered off, then press Enter.
  read enter
  echo Disconnect from the current Wifi network by holding the Option Key, clicking the Wifi icon at the top and clicking Disconnect from ...
  echo Press enter when completed.
  read enter
  echo Changing the MAC address to the Amazon Echo 3.  Enter the sudo password if prompted.

  sudo ifconfig en0 ether 08:84:9D:17:F3:B7

  echo Now spoofing the Amazon Echo 3 MAC address.  Connect and authorize to the wireless network, then press Enter.
  read enter
fi

echo Do you want to configure the Amazon Fire TV Cube? [y/n]
read answer
if [ $answer == 'y' ]
then
  echo Make sure the Amazon Fire TV Cube is powered off, then press Enter.
  read enter
  echo Disconnect from the current Wifi network by holding the Option Key, clicking the Wifi icon at the top and clicking Disconnect from ...
  echo Press enter when completed.
  read enter
  echo Changing the MAC address to the Amazon Fire TV Cube.  Enter the sudo password if prompted.

  sudo ifconfig en0 ether 00:71:47:77:80:0F

  echo Now spoofing the Amazon Fire TV Cube MAC address.  Connect and authorize to the wireless network, then press Enter.
  read enter
fi

echo Resetting the Macbook Air to its regular MAC address.

echo Disconnect from the current Wifi network by holding the Option Key, clicking the Wifi icon at the top and clicking Disconnect from ...
echo Press enter when completed.
read enter

echo Changing the MAC address to the Macbook Air.  Enter the sudo password if prompted.

sudo ifconfig en0 ether 7C:D1:C3:DF:EC:1F

echo The Macbook Air MAC address has been reset.  Connect to the wireless network.

echo Press enter when completed.
read enter

echo An ifconfig will be performed.  Verify the MAC address is 7C:D1:C3:DF:EC:1F
ifconfig

Remove PDF Restrictions

The Java code below removes any PDF restrictions if they exist on the document .  The program accepts two arguments, the input and output file names, which can be the same if desired.  The program requires a couple pieces from the PDFBox subproject library, available at https://pdfbox.apache.org/download.cgi

This code will not open a PDF that requires a master password, but it's a simple addition to add that to the PDDocument.load().


import java.io.File;
import java.io.IOException;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;

public class pdfRemove {

  public static void main(String[] args) throws InvalidPasswordException, IOException {
    File file = new File(args[0]); 
PDDocument document = PDDocument.load(file);

    if (document.isEncrypted()) {
      document.setAllSecurityToBeRemoved(true);
}

    document.save(new File(args[1]));
document.close(); 
    }
  
}

Adding Text To PDF Files

The Java code below uses a number of classes from PDFBox, an Apache open source project that allows for working with PDF documents.  In the code below, an existing PDF ,"C:\Template.pdf", is loaded, the first page (i.e. 0) is accessed and a ContentStream is built in APPEND mode.  The font is set to 20 point Times Roman and three lines are added to the PDF using the text in the first three passed arguments.  The fourth argument is used to make the output filename unique by appending it, and ".pdf", to "C:\Page-".  The file is saved with its new name and the document closed.

The purpose of this code is to add mailing addresses to a newsletter, but could to modified to customize any type of document, making it both personal and professional.


import java.io.File;
import java.io.IOException;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.PDPageContentStream.AppendMode;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

public class labels {

public static void main(String[] args) throws InvalidPasswordException, IOException {
  File file = new File("C:\Template.pdf"); 
  PDDocument document = PDDocument.load(file);
  PDPage page = document.getPage(0);
  PDPageContentStream contentStream = new PDPageContentStream(document, page, AppendMode.APPEND, true);
  contentStream.setFont(PDType1Font.TIMES_ROMAN, 20);

  contentStream.beginText();
  contentStream.newLineAtOffset(280, 630);
  String text1 = args[0];
  contentStream.showText(text1);
  contentStream.endText();

  contentStream.beginText();
  contentStream.newLineAtOffset(280, 600);
  String text2 = args[1];
  contentStream.showText(text2);
  contentStream.endText();

  contentStream.beginText();
  contentStream.newLineAtOffset(280, 570);
  String text3 = args[2];
  contentStream.showText(text3);
  contentStream.endText();

  contentStream.close();
  String outputfile = "C:\Page-" + args[3] + ".pdf";
  document.save(new File(outputfile));
  document.close(); 
  }
}

R - Prime Numbers

This R code will generate tables containing the first 2 million numbers, whether that number is prime (divisible only itself and 1) or not, its lowest divisor (or 0 for primes).  The final two statements result in displaying the percent of non-prime numbers (92.55%) and prime numbers (7.45%).


num <- 1:2000000
prime <- rep("Prime", 2000000)
divisor <- rep(0, 2000000)
for (x in seq(from=2, to=2000000, by=1)) {
  z <- sqrt(x);
  for (y in 2:z) {
     if (x%%y == 0) {
       prime[x] <- "Non-Prime";
       divisor[x] <- y;
       break;
       }    
    }
}
ptable <- table(prime)
prop.table(ptable)


PowerShell - Summary Of Files By Extension

Knowing in advance all the possible file types is a more efficient way to produce this type of report, but letting the code figure that out is more practical.  This report will start at the given $Target directory and summarize the number of files and total bytes by extension, in alphabetical order, to the whatever $ReportFile you select.

# Note: This report was written and tested using PowerShell V3
#
# Change the starting directory and report name to suit your needs
#
$Target = "C:\YourChoiceOfDirectory"
$ReportFile = "C:\YourChoiceOfReportName.txt"
$AllTypes = @()
#
# Write Report Header Lines
#
$Message = "All File Summary Report"
($Message) | Out-File $ReportFile
$Message = "                       "
($Message) | Out-File $ReportFile -Append
$Message = "FileType        Files                    Bytes"
($Message) | Out-File $ReportFile -Append
$Message = "---------  ----------  -----------------------"
($Message) | Out-File $ReportFile -Append
#
# Get every filename and produce an array of unique extensions
#

$List = Get-ChildItem $Target -File -Recurse
Foreach ($Item in $List) {
   $FileName= $Item.FullName
   $FileSplit = $FileName.split(“.”)
   $FilePieces = $FileSplit.Count
   $FileType = $FileSplit[$FilePieces-1]
   $AllTypes += $FileType
   }
$extensions = $AllTypes | Sort-Object -Unique
#
# Get a list of files for a specific extension, count the number of
# files and their total size and write that info to the report file.

# Repeat for each extension found.
#
Foreach ($ext in $extensions)  {
   $Filename = Get-ChildItem $Target -File *.$ext -Recurse
   $Files = 0; $Size = 0;
   Foreach ($Item in $Filename) {
     $Files++
     $Size = $Size + $Item.Length
      }
   $ext = $ext.PadRight(10,' ')
   $Files = $Files.ToString('N0').PadLeft(11,' ')
   $Size = $Size.ToString('N0').PadLeft(25,' ')
   $Message = "$ext$Files$Size"
   ($Message) | Out-File $ReportFile -Append

SQL Statements

At some point in the past I've used each of the following SQL statements to accomplish some required task and not wanting to Google Search for the same things twice, staring collecting them in a list for faster reference.  Some of these may not work with all versions of SQL Server and as new features are introduced may not be the best way to perform a specific task.  


Row Counts for Every Table in a Database
SELECT o.name, rows
FROM sysindexes i join sysobjects o on o.id=i.id
WHERE indid < 2 and type='U'
ORDER BY rows DESC


Get Information on All Columns for All Tables in a Database
SELECT table_schema, table_name, column_name, ordinal_position,
      column_default, data_type, character_maximum_length
FROM information_schema.columns


The Last Time a Table was Updated For All Tables in a Database
SELECT DISTINCT OBJECT_NAME(object_id,database_id) as TableName, last_user_update
FROM database name.sys.dm_db_index_usage_stats
WHERE database_id = DB_ID('database name')
GROUP BY OBJECT_NAME(object_id,database_id), last_user_update
ORDER BY TableName


Find String in Any Object in a Database
SELECT DISTINCT so.name
FROM syscomments sc
INNER JOIN sysobjects so ON sc.id=so.id
WHERE sc.TEXT LIKE '%string%'


Backup a Database
BACKUP DATABASE databasename
TO DISK = 'path\name.bak';


Restore Database to Another Location
RESTORE DATABASE databasename
FROM DISK = 'path\name.bak'
WITH RECOVERY,
MOVE 'databasename_Data' TO 'newpath\databasename_Data.MDF'
MOVE 'databasename_Log'  TO 'newpath\databasename_Data.LDF'


Copy Results from a Query to a Pipe-Delimited File
BCP "SELECT * FROM [database].[owner].[table_name]" queryout filename -Uuserid -Ppassword -t"|" -c -S server_name\instance


Change User Password
EXEC sp_password 'old password', 'new password', 'userid’


Select Rows Between Two Datetimes
SELECT *
FROM tablename
WHERE field BETWEEN '10/15/2015 00:00:00.00'
               AND '10/15/2015 23:59:59.999'


Select Yesterday's Data
SELECT *
FROM table
WHERE date_field >= dateadd(day,datediff(day,1,GETDATE()),0)
  AND date_field < dateadd(day,datediff(day,0,GETDATE()),0)


Count the Number of Occurances of Each Value
SELECT DISTINCT column_name, count(column_name) as CountOf
FROM tablename
GROUP BY column_name


Count Rows By Year
SELECT DISTINCT YEAR(datetime_field) as Year, COUNT(*) as Rows
FROM tablename
GROUP BY YEAR(datetime_field)
ORDER BY YEAR(datetime_field) DESC


Update Rows Based on a Time Difference in Minutes
UPDATE tablename
SET field = field
WHERE DATEDIFF(MINUTE,datetime,CURRENT_TIMESTAMP) < minutes


Replace String in a Field
UPDATE tablename
SET field = REPLACE(field, 'text', 'newtext')
Replace Substring in a Column
UPDATE tablename
SET field = CAST(REPLACE(CAST(field as NVarchar(4000)),'string1','string2') AS NText)
WHERE field LIKE '%string1%'


Delete Rows from a Table Between Two Datetimes
DELETE FROM tablename
WHERE date_field BETWEEN 'mm/dd/yyyy 00:00:00.00' AND 'mm/dd/yyyy 23:59:59.999'


Left Join
SELECT A.field1, A.field2, B.field3
FROM tablename1 A
LEFT JOIN tablename2 B
ON A.field1=B.field1

AWK - Directory to Rows

This AWK script parses the output of the Windows "DIR *.* /s" command and puts in columnar format with column titles. This makes it easy to open in your favorite spreadsheet program using a fixed column format.



#
BEGIN {
   record="  ";                               # Start output record at 2 spaces
   for (i = 1; i <= 7; ++i) {record=record record;}   # Expand output record to 256 spaces
   record=repl(record,1,14,"Date");                   # Date goes starts at column 1
   record=repl(record,12,26,"Size");                  # File size starts at column 12
   record=repl(record,28,87,"Filename");              # File name starts in column 28
   record=repl(record,89,148,"Fullpath");             # Full path starts in column 89
   print record;                                      # Print the header line
}
function repl(s,f,t,v)                                 # Custom function to add data to the output record
{ return substr(s,1,f-1) sprintf("%-*s", t-f+1, v) substr(s,t+1) }
{
if ( substr($0,2,9) == "Directory" ) {                 # If this line contains the directory name,
   dir=substr($0,15,60);                              # save the name
   }
else if (substr($0,3,1) == "/" &&                   
        substr($0,6,1) == "/" &&
        substr($0,25,1) != "<")   { # If this line contains a file ...
   date=substr($0,1,10);                              # Date
   size=substr($0,24,15);                             # File size
   file=substr($0,40,60);                             # File name
   name=dir "\\" file;                                # Full path
   record="  ";                               # Start output record at 2 spaces
   for (i = 1; i <= 7; ++i) {record=record record;}   # Expand output record to 256 spaces
   record=repl(record,1,10,date);                     # Date goes starts at column 1
   record=repl(record,12,26,size);                    # File size starts at column 12
   record=repl(record,28,87,file);                    # File name starts in column 28
   record=repl(record,89,148,dir);                    # Full path starts in column 89
   print record;                                      # Print the output line
   }
}

Spoofing MAC Addresses

I developed this bash script for my MacBook Air to simply the process of getting devices without a keyboard and mouse authenticated to a wir...