Working with firewall rules

Needed to be able to work with firewall rules on servers at work, so decided to start by getting the actual rule query and update part done, so I can add them to a more fleshed out script later.

#NetFirewallRule method for newer versions of Powershell

#Create a new test rule
New-NetFirewallRule -DisplayName "BLACKLIST_IN" -RemoteAddress 9.9.9.9 -Direction Inbound -Protocol TCP -LocalPort Any -Action Block

#Get the IP addresses in the current rule for the remote address field
$curIP = (Get-NetFirewallRule -DisplayName "BLACKLIST_IN" | Get-NetFirewallAddressFilter).RemoteAddress

#Define the new IP addresses to add, and then merge the lists
$newIPs = "9.9.9.10-9.9.9.11","9.9.9.14/31"
$addIPs = @($newIPs) + @($curIP)

#Set the rule with the new list
Set-NetFirewallRule -DisplayName "BLACKLIST_IN" -RemoteAddress $addIPs
Code language: PowerShell (powershell)
#netsh version for older versions of Powershell

#Get the current rule and convert it from comma separated to a list
$netshout = netsh advfirewall firewall show rule name="BLACKLIST_IN"
$nshIP=($netshout | findstr RemoteIP).trim("RemoteIP: ").split(",")

#Define the new IP addresses to add, and then merge the lists
$newnshIPs = "9.9.9.13","9.9.9.14/31"
$nshaddIPs = @($nshIP) + @($newnshIPs)

#Take the new list and convert back to comma separated
$IPList = ($nshaddIPs | Select-Object) -join ","

#Set the rule with the new list
netsh advfirewall firewall set rule name ="BLACKLIST_IN" new remoteip=$IPList
Code language: PowerShell (powershell)

Adding list entry to the Python script

Next up is adding the ability to enter a comma separated list to the script, so that multiple values can be processed at once. The list will still be validated, and if there are values that are not positive integers they will be ignored.

calculation_to_units = 24
name_of_unit = "hours"


def days_to_units(number_of_days):
    if number_of_days > 0:
        return f"{number_of_days} days are {number_of_days * calculation_to_units} {name_of_unit}"
    else:
        return "You did not enter a positive integer..."

def validate_and_execute(validated_days):
    if validated_days == "quit":
        quit()
    try:
        print(days_to_units(int(validated_days)))
    except ValueError:
        print("Please enter a positive integer value...")

days_entry = 0
while days_entry != "quit":
    days_entry = input("Enter the number of days, and enter 'quit' to exit the program: ")
    for num_of_days in days_entry.split(","):
        validate_and_execute(num_of_days)
Code language: Python (python)

Even more Python in the mix

Added a very simple while loop to the script, as well as a check for the word ‘quit’ which will exit the program cleanly. It will still catch any negative, 0, string or null (enter key with no value) and prompt to enter an integer again.

calculation_to_units = 24
name_of_unit = "hours"

def days_to_units(number_of_days):
    if number_of_days > 0:
        return f"{number_of_days} days are {number_of_days * calculation_to_units} {name_of_unit}"
    else:
        return "You did not enter a positive integer..."

def validate_and_execute():
    days_entry = 0
    try:
        days_entry = input("Enter the number of days, and enter 'quit' to exit the program: ")
        print(days_to_units(int(days_entry)))
    except ValueError:
        if days_entry == "quit":
            quit()
        else:    
            print("Please enter a positive integer value...")

while True:
    validate_and_execute()
Code language: Python (python)

Getting the hang of Python

Following a Python video on Youtube, and think I am doing pretty good so far. Finally got the following compacted as much as I can do for now, but really happy with it.

calculation_to_units = 24
name_of_unit = "hours"

def days_to_units(number_of_days):
    if number_of_days > 0:
        return f"{number_of_days} days are {number_of_days * calculation_to_units} {name_of_unit}"
    else:
        return "You did not enter a positive integer..."

def validate_and_execute():
    try:
        days_entry = int(input("Enter the number of days: "))
        print(days_to_units(days_entry))
    except ValueError:
        print("Please enter a positive integer value...")

validate_and_execute()
Code language: Python (python)

Editors

I thought I would share images of my development setups. I have Visual Studio Community set up in a virtual machine running Windows 10 to do my Powershell and Windows C++ stuff on, and then have Visual Studio Code set up on my main desktop, and interfaced with the Windows Subsystem for Linux, so that I can work on a lot of the languages that can be set up in Linux. I even threw Haskell in there for fun.

The differences between languages…

I’ve been learning how a few different languages can do the same task, so decided to put up the examples below.

#!/usr/bin/python

number = 5
counter = 1
while (counter <=10):
    if counter < number:
        print (counter, ' is less than ', number)
    elif counter == number:
        print (counter, ' equals ', number)
    else:
        print (counter, ' is greater than ', number)
    counter = counter + 1
Code language: Python (python)
#powershell

$numValue = @(1..10)
$counter = 0

while ($counter -lt $numValue.length){
if ($numValue[$counter] -lt 5){
    write-host "Less than`n"
}
elseif ($numValue[$counter] -eq 5) {
    write-host "Equal`n"
}
else {
    write-host "Greater than`n"
}
$counter += 1
}Code language: PowerShell (powershell)
//C++
#include <iostream>
using namespace std;

int main()
{
    int counter = 1;
    while (counter <= 10) {
        if (counter > 5) { cout << "Greater than\n"; }
        else if (counter == 5) { cout << "Equal\n"; }
        else { cout << "Less than\n"; }
        counter++;
    }
    system("pause>0");
}

Code language: C++ (cpp)

Getting past the basics…

I’ve been watching a C++ tutorial series on Youtube lately, and decided to take some of the basic knowledge that I had of functions, and go into more advanced functions. I was so happy to finally be able to set up a function in an external file, and then pass a variable to that function, and have it be used. Next step will be to manipulate that variable, and pass it back to the main program.

// FunctionExample.cpp : This file contains the 'main' function. Program execution begins and ends there.

#include <iostream>
#include "functions.h"

using std::string;
using std::cout;
using std::cin;
using std::endl;

string name;

int main()
{
    cout << "Please enter your name: ";
    cin >> name;
    function1(name);

    system("pause>0");
}

Code language: C++ (cpp)
//functions.h - This file contains functions declarations for the related cpp file.
#pragma once
int function1(const std::string& name);
Code language: C++ (cpp)
//functions.cpp - User defined functions to be called in the main file.

#include <iostream>
#include "functions.h"

using std::string;
using std::cout;
using std::cin;
using std::endl;

int function1(const string& name)
{
    cout << "Hello " << name << ".";

    return 0;
}
Code language: C++ (cpp)

Hello world!

This felt appropriate…

#include <iostream>
using std::cout;
int main()
  {
    std::cout << "Hello, World!\n";
    return 0;
  }
Code language: C++ (cpp)