Archive for the ‘Scripts’ Category

Script for concatenating first_name, last_name and address into ResourceName column, and return column which contain Dylan Dog Craven Road rows.

 

Capture

Import-Csv "C:\1.csv" | Select-Object  @{n='ResourceName';e={$_.FIRST_NAME + "," + $_.LAST_NAME + "," + $_.ADDRESS}} `
| Where-Object {$_.ResourceName -like "Dylan*Dog*Craven Road 7"}

Result:

ResourceName
------------------
Dylan,Dog,Craven Road 7

Recently i got long list of linux machines and had to check which of them support password authentication.

I found a tool Hydra , if it finds machine which do not support password authentication, it will print it in output

Hydra v8.2-dev (c) 2016 by van Hauser/THC - Please do not use in military
or secret service organizations, or for illegal purposes. Hydra
(http://www.thc.org/thc-hydra) starting at 2019-11-25 14:49:59 [DATA]
max 4 tasks per 4 servers, overall 64 tasks, 5 login tries (l:1/p:5),
~0 tries

per task [DATA] attacking service ssh on port 22
[ERROR] target ssh://1.1.1.1:22/ does not support password authentication.
[ERROR] target ssh://2.2.2.2:22/ does not support password authentication.

ERROR] target ssh://3.3.3.3:22/ does not support password authentication.

[ERROR] target ssh://4.4.4.4:22/ does not support password authentication.

4 of 4 targets completed, 0 valid passwords found Hydra 

(http://www.thc.org/thc-hydra) finished at 2019-11-25 14:50:01

So i created simple batch script which captures Hydra output into $command variable, then get string between [ERROR] target ssh:// and :22/ does not support into $out variable.

Then get IP address of masines – $filtered variable. Then print every IP into new line and write it to output.txt file.

Installing hydra (CentOS 7)

rpm -Uvh http://www6.atomicorp.com/channels/atomic/centos/7/x86_64/RPMS/atomic-release-1.0-21.art.noarch.rpm
yum install hydra

Put all your passwords to file pws.txt and machines IP into targets.txt

file: put every password/IP into new line

command=$((hydra -l root -P pws.txt -M targets.txt ssh -t 4) 2>&1)
echo $command
out=$(echo $command | grep -oP '(?<=ERROR] target ssh://).*(?=:22/ does not support)')
filtered=$(echo "$out" | sed 's|does not support password authentication.||g ; s|/||g ; s|ERROR||g ; s|target ssh||g ; s|:22||g ; s/[][]//g ; s|/||g ; s|:||g')
echo $filtered | xargs -n1 > output.txt

output.txt will contain IPs of machine which don’t support password authentication.

This script will ping IP 1.1.1.1, if ping fails, and if ping to 2.2.2.2 is successful, and if there is host A record for IP 1.1.1.1,it will change DNS record to match 2.2.2.2

function Switch-IP {
    [CmdletBinding()]
    param (
    
    [Parameter(Mandatory=$true][string]$IP,[Parameter(Mandatory=$true][string] $newIP
        )
  
    $currentIP = $oldobj.RecordData | select IPv4Address
    if ($currentIP.IPv4Address.IPAddressToString -eq $IP) {
         
    $newobj = get-dnsserverresourcerecord -name "nagios" -zonename "test.local" -rrtype "A"
    $updateip = $newIP
    $newobj.recorddata.ipv4address=[System.Net.IPAddress]::parse($updateip)
    Set-dnsserverresourcerecord -newinputobject $newobj -OldInputObject $oldobj -zonename "test.local" -passthru > C:\dnsfailover.log
    add-content -path C:\dnsfailover.log -Value $(Get-Date)
    }
    }

 $IP = "1.1.1.1"
 $newIP = "2.2.2.2"
 
    if (-Not (test-connection $IP -Quiet -Count 1)) {
    if (test-connection $newIP -Quiet -Count 1) { 

    $oldobj = get-dnsserverresourcerecord -name "nagios" -zonename "test.local" -rrtype "A"
 
    $currentIP = $oldobj.RecordData | select IPv4Address
    if ($currentIP.IPv4Address.IPAddressToString -eq $IP) {
         
    Switch-IP $IP $newIP
      
    }
 
}}
 
 
elseif ((test-connection $newIP -Quiet -Count 1) -and (test-connection $IP -Quiet -Count 1)) {
 
  
    $oldobj = get-dnsserverresourcerecord -name "nagios" -zonename "test.local" -rrtype "A"
 
    $currentIP = $oldobj.RecordData | select IPv4Address
    if ($currentIP.IPv4Address.IPAddressToString -eq $newIP) {
       
    Switch-IP $newIP $IP    
        
  }
 }
 

Next example assumes that there are 2 DNS records with same name (nagios), one record has IP 1.1.1.1, and second one is 2.2.2.2.

If ping to 1.1.1.1 fails, and if there are 2 DNS entries for host nagios, remove DNS entry for IP 1.1.1.1. When connection is restored, add back DNS entry for 1.1.1.1

$dnszone = "test.local"
$currentRecord = Get-DnsServerResourceRecord -name "nagios" -ZoneName $dnszone -RRType A 
$currentIP = $currentRecord.RecordData | select IPv4Address
$primaryIP = "1.1.1.1"
$secondaryIP = "2.2.2.2"    
    
    if (-Not (test-connection $primaryIP -Quiet -Count 1)) {
 
       if (test-connection $secondaryIP -Quiet -Count 1) { 
 
 
             if ($currentIP.Count -eq 2)  {
 
          try {
 
         Remove-DnsServerResourceRecord -name "nagios" -ZoneName $dnszone -RRType A -RecordData $primaryIP -Force -ErrorAction Stop -PassThru  > C:\dnsfailover.log  
         add-content -path C:\dnsfailover.log -Value "$(Get-Date):DNS entry removed" 
            }
 
          catch { 
          $Error[0].Exception.Message
                 }
 
 
    }}}
 
 
 
    elseif ((test-connection $secondaryIP -Quiet -Count 1) -and (test-connection $primaryIP -Quiet -Count 1)) {
 
  
           $currentRecord = Get-DnsServerResourceRecord -name "nagios" -ZoneName $dnszone -RRType A 
           $currentIP = $currentRecord.RecordData | select IPv4Address
    
        if  ($currentIP.Count -ne 2) {
 
        try {
 
         Add-DnsServerResourceRecord -A -Name "nagios" -ZoneName $dnszone -IPv4Address $primaryIP -TimeToLive 00:00:10 -PassThru  > C:\dnsfailover.log  
         add-content -path C:\dnsfailover.log -Value "$(Get-Date):DNS entry added" 
         }
 
         catch {
         $Error[0].Exception.Message
              }
       
      
  }
  
}

Following script will loop through all Partner Center customers, will export them in batches of 100 and every “chunk” will be exported to separate CSV file.

 

$custIDs = Get-PartnerCustomer
$chunks = [System.Collections.ArrayList]::new()
for ($i = 0; $i -lt $custIDs.Count; $i += 100) {
    if (($custIDs.Count - $i) -gt 99  ) {
        $chunks.add($custIDs[$i..($i + 99)])
    }
    else {
        $chunks.add($custIDs[$i..($custIDs.Count - 1)])
    }
}
$today = [datetime]::Today.ToString("yyyy-MM-dd")
$count = 1
foreach ($chunk in $chunks) {
    $path = "c:\Reports\$today Chunk $count of $($chunks.Count).csv"
    $chunk | Export-Csv $path -Append
    $count++
}

This script will check if user password expires in 1,3 or 7 days and if yes, it will send email to user

 

First, encrypt password and store it in file

$password = "somepass"
$secureStringPwd = $password | ConvertTo-SecureString -AsPlainText -Force
$secureStringText = $secureStringPwd | ConvertFrom-SecureString
Set-Content "C:\temp\ExportedPassword.txt" $secureStringText

 

$mailuser = "userc@example.com"

$pwdmail = Get-Content "C:\temp\ExportedPassword.txt"
$securemailPwd = $pwdmail | ConvertTo-SecureString

$EmailCreds = New-Object System.Management.Automation.PSCredential -ArgumentList $mailuser, $securemailPwd

$from = "user@xample.com"

# OU to search 

$path = "CN=Users,DC=example,DC=com"

$users = Get-ADUser -SearchBase $path -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False -and PasswordLastSet -gt 0} `
-Properties "Name", "EmailAddress", "msDS-UserPasswordExpiryTimeComputed" | Select-Object -Property "Name", "EmailAddress", `
@{Name = "PasswordExpiry"; Expression = {[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed").tolongdatestring() }}

# Days remaining until password expiration
$WarningDays = 1,3,7

# Get current day
$today = (Get-Date).ToLongDateString()
try {
foreach ($user in $users)
{
 foreach ($WarnDay in $WarningDays){
 if ($user.PasswordExpiry -eq (get-date).adddays($WarnDay).ToLongDateString()) 
 {
  # Calculate days beteween today and date when password will expire
  $ts = New-TimeSpan -Start $today -End $user.PasswordExpiry
  $days = $ts.Days
  $subject = "Password expiration notification - " + $user.Name
  $body = "Dear " + $user.name + ",`nYour Password will expire in " + $days + " days"
  Send-MailMessage -to $user.EmailAddress -from $from -Subject $subject -Body $body -BodyAsHtml -SmtpServer smtp.office365.com -UseSsl -Credential $EmailCreds -Port 587

 }}}}
catch {
$Error[0].Exception.Message
}
exit $LASTEXITCODE
    from itertools import islice 

    def getListOfFiles(dirName):
    
    # create a list of file and sub directories 
    # names in the given directory 

    listOfFile = os.listdir(dirName)
    allFiles = list()
    # Iterate over all the entries
    for entry in listOfFile:
        # Create full path
        fullPath = os.path.join(dirName, entry)
        # If entry is a directory then get the list of files in this directory 
        if os.path.isdir(fullPath):
            allFiles = allFiles + getListOfFiles(fullPath)
        else:
            allFiles.append(fullPath)
                
    return allFiles  



dirName = "C:\SIEMLogs\Email"
 
listOfFiles = getListOfFiles(dirName)


# sort filenames by creation date (ascending)

sorted_files = sorted(listOfFiles, key=os.path.getmtime)

# select top 5 elements from sorted list

top_files = islice(sorted_files,5)
 

# Print top 5 files
for elem in top_files:
    print(elem)

# Number of files in sub directories

cpt = sum([len(files) for r, d, files in os.walk("C:\SIEMLogs\Email")])

print cpt
 

Listing files in directory (without sub directories),sorting by creation date (ascending) and count of total files:

path = "C:\SIEMLogs\Email"
name_list = os.listdir(path)
full_list = [os.path.join(path,i) for i in name_list]
time_sorted_list = sorted(full_list, key=os.path.getmtime)

for a in time_sorted_list:
    print a


# Number of files in Directory only

path, dirs, files = next(os.walk("C:\SIEMLogs\Email"))
file_count = len(files)

print file_count

This function will print registry value for specific key, in this case HPATH value

import _winreg

def getPath():
    # Open the key and return the handle object.
    hKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
                          "COMODO")
    
    # Read the value.                      
    result = _winreg.QueryValueEx(hKey, "MachineId")
    # Close the handle object.
    result = result[0]
    return result
    _winreg.CloseKey(hKey)

Another solution:

def regkey_value(path, name="", start_key = None):
    if isinstance(path, str):
        path = path.split("\\")
    if start_key is None:
        start_key = getattr(_winreg, path[0])
        return regkey_value(path[1:], name, start_key)
    else:
        subkey = path.pop(0)
    with _winreg.OpenKey(start_key, subkey) as handle:
        assert handle
        if path:
            return regkey_value(path, name, handle)
        else:
            desc, i = None, 0
            while not desc or desc[0] != name:
                desc = _winreg.EnumValue(handle, i)
                i += 1
            return desc[1]


posread = regkey_value(r"HKEY_LOCAL_MACHINE\COMODO", "MachineId")

3rd way:

import _winreg

reg_connection = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)

key_value = _winreg.OpenKey(reg_connection, r"COMODO")

print _winreg.QueryValueEx(key_value, "MachineId")[0]

Reading registry keys from x64 versions of Windows using x86 Python installation:

import _winreg

def get_path(name):
    try:
        registry_key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\\COMODO', 0, (_winreg.KEY_WOW64_64KEY + _winreg.KEY_READ))
        value = _winreg.QueryValueEx(registry_key, "MachineId")[0]     
        return value
    except WindowsError:
        return None