Skip to main content

Posts

Showing posts from December, 2024

Python example to use zip built-in function

Python code below use zip built-in function to display the list and display the sequence. The code below just display the list, but using subprocess or fabric module it can be expanded to connect or do remote tasks on the specified servers. Here's an example code on how to use zip built-in function. def main_func(): xservers = ["WebServer", "MailServer", "MonitoringServer", "KibanaServer", "DatabaseServer", "TestServer", "NetboxServer"] xips = ["192.168.25.1", "192.168.25.2", "192.168.25.3", "192.168.25.4", "192.168.25.5", "192.168.25.6", "192.168.25.7"] for indexx, itemx in enumerate(zip(xservers, xips), start=1): print(indexx, itemx[0], "=", itemx[1], " ==> VM with platform services") if __name__ == "__main__": main_func() itemx[0] ===> refers to xservers itemx[1...

Python example using multiprocessing module

With the era of multi-core CPU, parallel, concurrency or multiprocessing is quite possible now. Below is an example of a Python code that shows how to use multiprocessing module to run multiple commands. import multiprocessing import subprocess # Shell command/s Function def multi_run_command(command): try: result = subprocess.run(command, shell=True, capture_output=True, text=True) return f"Command: {command}\nOutput:\n{result.stdout}" except Exception as e: return f"Command: {command}\nError: {e}" if __name__ == "__main__": # List of dig commands to run / Replace the commands as desired commands = ["dig @1.1.1.1 google.com", "dig @8.8.4.4 yahoo.com", "dig @9.9.9.9 bing.com"] # Create and specify limit of pool worker processes with multiprocessing.Pool(processes=3) as pool: #limit to 3 cores or workers results = pool.map(multi_run_command, commands) #use the m...

Python Fabric module run local commands

Fabric is a Python library that simplifies the use of SSH for system administration tasks by running remote commands on remote system. It can be used as well to run local commands on the system. Example code below shows on how to use Fabric module to execute local commands. Below is an example on how to use Fabric. from fabric import Connection # Create a connection to the localhost connx = Connection('localhost') # Run local commands def run_local_commands(): print(f"Executing on {connx.host} as {connx.user}") # Command 1: Get the system name result_uname = connx.local("uname -s", hide=True) print("Output of 'uname':") print(result_uname.stdout) # Command 2: Get memory on the system result_mem = connx.local("free -h", hide=True) print("Output of 'system memory':") print(result_mem.stdout) # Command 3: Display ip route result_ipr = connx.local("ip r", ...

Python subprocess run local commands

Python subprocess module is quite helpful in running local commands. While Fabric module can also be used to run local commands, Fabric module is overkill to run local commands on the system. Fabric module is quite useful in running commands on remote system via SSH. Whereas subprocess mnodule is quite ideal to execute local commands on the VM, device or local server. Python code example below to run local commands with try exception to capture any errors. Code below will run the "xz" command to zip the file on the specified path. xz command will replace the specified file as an xz file. xz file won't create a new file. import subprocess try: # Run the xz command subprocess.run(['xz', '/tmp/app_log.log'], check=True) print("File successfully compressed.") except subprocess.CalledProcessError as e: print(f"Error: Command failed with exit status {e.returncode}") except FileNotFoundError: print("Error: xz comma...

Notepad++ browse to all opened notes

Notepad++ comes in handy when taking quick notes, reading readme files, or just simply browsing all notepad or text files on the system. However, if multiple tabs or notes are open it can be overwhelming to go back to the previous tab or notes. In Notepad++ version 8.7.1, there's a drop down arrow button on top right of the Notepad++ Window which will display all the notes that are currently opened. And simply click the notes to make it active as the current window. Image below shows the drop down button on the top right of Notepad++ window. Having a descriptive name of notes when saved will be helpful using the above method. Since by clicking the title or the name of the notes it will be shown as the current window. There's another method also that can be used to browse or select notes. Notepad++ provides also a left and right button to move the current window. The left and right button to navigate between notes is also on the top right window of Notepad++ and is just...

Basic Python ask user to continue or exit

In a user interactive program there are times that a program might need to ask the user to proceed or exit to determine whether the program needs to continue or not. For this a prompt is necessary, and ask a user to decide and press some keys and depending on the user input, it will determine whether the code or program will continue running or not. Below is a simple Python code that will ask a user to press y or n. The code only shows how to detect the key that was pressed, of course the logic or the code can be inserted to other existing Python codes. Python code snippet, works in Python 3: import sys print("Make a choice press [y] to continue else [n] to exit") proceed_or_exit = input() if proceed_or_exit == 'y' or proceed_or_exit == 'Y': print("Y was pressed") #put some code here pass elif proceed_or_exit == 'n' or proceed_or_exit == 'N': print("N was pressed") #put some code here if necessary ...

PowerShell kill all notepad services or using pid

It's easy to fall into the habit of using multiple Notepad windows for various note-taking and reading needs. The convenience of having separate windows for different types of information can be surprisingly addictive. At the end of the day, you might have quite a few notepad and closing them one by one is not practical or ideal. Scripting or using PowerShell comes in handy in such scenario. Example of a PowerShell code snippet to kill all running notepad on the system. Get-Process -Name "*notepad*" | Stop-Process Above code snippet, get all notepad processes and is pipe to stop-process that will close the notepad. To just list the process of all running processes on the system, run this PowerShell code snippet. Get-WmiObject -Class Win32_Process | select "ProcessName", "ProcessID" To kill or close the process using a PID, run the command beloww: Stop-Process -Id 4365 -Force Or use -whatif parameter to see what will happen. Example: stop-pr...

PowerShell check Windows OS version home or professional

Windows OS version also comes in different editions or releases. The edition that has always been a part of Windows OSes releases are Home or Professional version. Home version is good for personal use, as it name suggested that its a Home version. Pro or Professional version is ideal if the laptop or device is used in a company or corporate environment. Professional version has the ability to join a domain or the device can be enrolled to an Active Directory. Windows 11 also comes with SE version, which is aim for low-end devices sold in the education market. There are other editions or releases such as enterprise, workstation and others. To get or check the Windows OS version via PowerShell, run the following PowerShell code snippet. Example: (Get-WmiObject -Class Win32_OperatingSystem).Caption Sample output: Microsoft Windows 11 Home gwmi -class Win32_OperatingSystem | select caption Sample output: caption ------- Microsoft Windows 11 Home Look forward what is bey...

PowerShell Get OS Install Date

PowerShell One-Liner to get OS/Operating System Install Date. Example: [System.Management.ManagementDateTimeConverter]::ToDateTime((Get-WmiObject -Class Win32_OperatingSystem).InstallDate) Without the DateTimeConverter this will just show the raw output of the date and time. (Get-WmiObject -Class Win32_OperatingSystem).InstallDate Feeling overwhelmed with life's tribulations, sufferings and anxieties. You need to surrender all to Jesus, have a faith of mustard seed and walk in the path of righteousness. Matt. 11 Verses 28 to 30 Take my yoke upon you, and learn from me; for I am gentle and lowly in heart, and you will find rest for your souls. For my yoke is easy, and my burden is light.

Linux find files that requires sudo or root access

Root access on a Linux operating system is needed, if you need to maintain the server or if something goes wrong and requires some changes that only root account is able to do. However, sudo can be used to give certain access to files that can be managed by specific users. For example, for whatever reason the system requires changing the DNS server IP address. Then sudo can be used to grant editing privileges to /etc/resolv.conf If just curious what are the files that require sudo or root access, on a Linux VM or server. Find command be used to locate or identify files that requires root privileges. On Linux VM, by typing: sudo id root This will show the output below: uid=0(root) gid=0(root) groups=0(root) The output shows that the user id for root is 0, and it's the same with group id and any other groups. Technically, 0 (zero) is the id for any files on the Linux system that is owned by root or requires root to modify or make some changes. For example, by typing: cd...

PowerShell execute multiple task on different servers

If you find yourself feeling overwhelmed by the maintenance of hundreds or multiple servers, there is no need for concern; PowerShell can assist you, provided that you have a clear understanding of the required actions. Below is a PowerShell code snippet that can shut down a server, restart a server, restart a service, or stop a service. It is advisable not to attempt this in a production environment unless the necessary actions are permissible and the task has been approve. An example image illustrating the output of the PowerShell script is included below. Ensure to modify the server name or service name as appropriate. And most importantly, used an elevated PowerShell with Admin credentials. Here's the PowerShell code: $servers = @("Admin_server", "DB_Server", "Redis_Server", "Docker_server") $action = @("Shutdown_server", "Restart_server", "Service_restart", "Service_stop") $ix = 0 ...

Linux: Displays Interface Status in Up or Down State

The `ip link show` command, available in more recent versions of Linux that support the `ip` command, provides information about network interfaces and their respective states. Executing `ip link show` yields extensive details regarding the interface, including its MAC address, operational state, IP address, and additional relevant information. The command below identifies the names of interfaces currently in either an UP or DOWN state. The output is piped to `grep` to filter and display only the state alongside the interface name. To display interfaces in a DOWN state, use the following command: ```ip command: echo "Interface on DOWN state: $(ip link show | grep "state DOWN" | grep -oP '^[0-9]+:\s+\K\S+' | cut -d: -f1)" ``` To display interfaces in an UP state, the command is: ```ip command: echo "Interface on UP state: $(ip link show | grep "state UP" | grep -oP '^[0-9]+:\s+\K\S+' | cut -d: -f1)" ``` The follo...

Windows 10/11: "This PC" in Windows Explorer is not displaying or missing

In Windows 10/11 the "This PC" icon, previously known as "My Computer" during the era of Windows XP, may unexpectedly vanish when accessing Windows Explorer or File Explorer. Microsoft has included a feature that allows users to either display or hide the "This PC" icon within the Navigation Pane. To control the visibility of the "This PC" icon, users should open File or Windows Explorer, navigate to the "View" dropdown menu, select "Show," and then click on "Navigation Pane." By default, the "Navigation Pane" option is enabled. If this option is disabled, the "This PC" icon will not be visible in File or Windows Explorer. In summary, if the "Navigation Pane" is enabled, "This PC" will be accessible; conversely, if it is disabled, "This PC" will not be displayed. Please follow image below on how to do it. Open File Explorer or Windows Explorer by pressing ...

How to select single click or double click to open a folders in Windows

How to change settings in Windows to single or double click to open folders or items in Windows 11 or Windows 10? The default in Windows is you need to double click on opening folders or files. However, an option is given on the system to change it to single click. Images below shows how to change the settings to single click or double click when opening items or folders in Windows. Open Windows Explorer by pressing "Windows key + E" or simply right click the Windows icon the four squares on the task bar and choose "File Explorer". Once the "File Explorer" opens click or select the "3 dots ..." on the bread crumbs bar or whatever its called. Please see image below on which one to click. After clicking the "3 dots" select "options" from the drop down menu that will appear on the screen. Please see image below for the guide. After selecting or clicking the "options" button, a Window will appear where you ...

PowerShell: Displaying Local Administrator Accounts

The PowerShell command provided below will enumerate all local accounts that belong to the Administrator group or possess administrative privileges on the system. Here is the PowerShell code to execute: Get-CimInstance Win32_GroupUser | Where-Object {$_.GroupComponent.Name -eq "Administrators"} | Select-Object -ExpandProperty PartComponent | Select-Object -Property Name Example Output: There are other ways to list user accounts with administrator privileges on a Windows System. On a server OS or other OS that supports Microsoft Management Console command will also show the list of users with admin rights, press "windows key + r" and when run box appears type: "lusrmgr.msc" or simply open a command prompt and type the command: "lusrmgr.msc", if the command is supported it will show a window where you can check the list of users with admin access. The MMC is beneficial because it features a graphical interface, but using scripts proves...

PowerShell to Verify BIOS Information

The BIOS Properties contain a wealth of information, with BIOS standing for Basic Input Output System. In technical point of view, a computer cannot start without the BIOS. While the computer may power on, it will only show a blank screen, and the operating system will not load or function or there will be no display. Here’s a straightforward PowerShell script to check details such as the BIOS release date, computer serial number, BIOS version, and additional information. PowerShell script to get BIOS information or data. $biosProperties = Get-WmiObject Win32_BIOS Write-Host "BIOS Name:" $biosProperties.Name Write-Host "BIOS Serial Num:" $biosProperties.serialnumber Write-Host "PrimaryBIOS:" $biosProperties.PrimaryBIOS Write-Host "BIOS ReleaseDate:" $biosProperties.ReleaseDate Write-Host "BIOS Version:" $biosProperties.BIOSVersion Write-Host "BIOS Caption:" $biosProperties.Caption Write-Host "BIOS Language...