Skip to main content

Posts

Showing posts with the label Script

Linux Bash rename multiple files

Bash script/command below shows how to rename multiple files. If the filename shows some pattern, then it will be easier to rename.  Example filename: file_text_a.txt file_text_b.txt file_text_c.txt file_text_etc... ... .txt Script/command below, shows some magic to rename files all at once. The command below can be integrated to a script or simply run the command on the terminal. Create some dummy files for testing before running on actual files to be renamed or in production. find . -name "*.txt" -exec sh -c '   for file; do       newf=$(echo "$file" | sed "s/text/tested/" )  &&   mv "$file" "$newf"   done ' sh {} + Output is: file_tested_a.txt file_tested_b.txt Since the command uses sed, replace 'text' with any string to be searches and replace 'tested' also with any new string for the filename. Till next time.. Enjoy Linux and scripting... Put your trust in God and have Faith. Exodus 14:14, "The...

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", ...

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 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 ...

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...

PowerShell Get ComputerName

Getting computername in PowerShell is quite straight forward using environments variable. Example: $computerName = $env:ComputerName Write-Host "The computer name is: $computerName" With the right credentials and as long as WinRM or Windows Remote Management is enabled we can use the Environment ComputerName variable to shutdown a remote PC. This command runs or shutdown a remote pc, by invoking a local command to shutdown the PC. Invoke-Command -ComputerName remote_computer_name -ScriptBlock {Stop-Computer -ComputerName $env:ComputerName } The above invokes shutdown command locally, just like you were in front of the server or computer. Above is just a demonstration on how to use ComputerName environment variable. Shutting down a remote computer with a valid domain credentials, doesn't need the invoke-command instead command below can be used. Stop-Computer -ComputerName "RemotePC1", "Server2" -Force 1 Peter 5:6: "Humble y...

Basic Ansible understanding when statement

Ansible playbook to illustrate how "when" conditional statement works in Ansible. Ansible playbook below will run a command: "file -s /dev/sdb"  The output of the command will be saved to the variable: save_the_command_output  Yes, the name of the variable can be anything. Just changed it to something that is sensible. save_the_command_output is just a string to illustrate its functionality or usage. After registering or saving the output to a variable, another command will be executed provided the conditional statement "when" is True or the condition is meet or satified. If the conditional statement is not meet then the command will be bypass or will not be executed. On this illustration below, if the conditional statement has been meet. Then a file with a filename "condition_ok" will be written on /tmp directory. Otherwise, if the condition is not meet then no file will be created. Sample playbook below: #=================== --- -  hosts: local...

Ansible comment all existing lines and add new lines

Backing up every configuration before any change is a good idea.  With the Git tool, every revision or change can be keep track and changes can be reversed. However, not everything is in Git. For example, in Linux configuration on /etc configuration or other important location or files is not under Git. To keep track of the changes, old school method can still be applied. Making another copy of the file, or just simply commenting every line and adding changes or new configuration after commenting the existing lines or configuration; are forms of backup. Existing configuration can still be seen, and can put back if there's a need to reverse the configuration. In an environment where there is hundred or more virtualized machines, Ansible is a way to go.  Ansible can do the task to comment all the existing lines and apply new configurations. Ansible script below, are references from multiple sources found on the web to create this Ansible script below. Here's the Ansible, save it...

How to automate Python to use Telnet to check ports

 Checking ports automatically can be stressful if there are quite a few addresses and ports to be checked. And typing manually is prone to error by mistyping the IP Address and Port. This is where automation comes into play. Prepare the IP Address and Port on  a text file, and once all is prepared. Let Python do the job or the task to Telnet and check the port whether the system can successfully connect or not. The tester just need to watch or monitor the terminal or do some other task, while waiting for the Python to do its job. Simple code below shows, how to do this task. #===================================== import sys import telnetlib def get_all_ips(filename_to_check):   with open(filename_to_check, 'r') as entries:     for ip_entries in entries:       ip_and_port=ip_entries.split(" ")                 the_ip=ip_and_port[0]       the_port_num=ip_and_port[1]       the_...

Zip log files via script or cron job

Zipping log files to save disk space is quite a common task for system admin. Logs can be kept for a certain period of time depending on the company policy. To keep logs files and not delete them is quite a good strategy. If something goes wrong, you will be able to trace and go back in time, and check what went wrong. Zipping log files can be done manually, or via Bash or Shell script. If the folder has a standard pattern, which is quite ideal then creating a shell script to automate the zipping of log files will be easier. For example, if  the log files is on this path /mnt/log folder. And it has this pattern, YYYY-MM-DD. Creating a script to avoid manual task can be done easily. Depending on how busy the application is, log files can grow easily and may fill-up the disk quickly. If the log folder structure is based on Year, Month and Date. Then the shell script knows what pattern to look for and the task can be automated. Example Screenshot of the log folder structure: Below is ...

PowerShell query event log last reboot or shutdown

Querying when was the last time the server  or computer is  essential in troubleshooting or auditing the server. Or in production system, computers or servers, must scheduled a downtime and let stakeholders know that at this specific date and time there will be a down time and services will not ne available at the said time and date. Even in development servers or computers, checking when was the last time the computer restarted or shutdown is quite essential. If the application is buggy,  or has some memory leak or other issues then it will cause the system to reboot, shutdown or crash. PowerShell comes in handy in querying event log; when was the last time the computer has shutdown or rebooted. Of course, event log can be checked manually. But scrolling through the 100 or thousands of event logs is quite tedious. So, PowerShell comes to a rescue  and avoid the tedious, manual finding of the event log. Here's a sample code snippet on how to query Windows event log w...

PowerShell Compare and Get Hash File

 Hash File comparison is a good thing to do, to make sure that file in transit, transferred, downloaded, or copied over is not corrupted or has been altered or modified. PowerShell has a built-in module to do this that makes life easier and an easy task to do. Here's an example code snippet to do this: #Path location of the file $file="C:\Users\User1\Downloads\Win10_22H2_EnglishInternational_x64.iso" # Get the file hash $hashSrc = Get-FileHash $file -Algorithm "SHA256" write-output $hashSrc #copy the Hash file  $Display_hash_only = $hashSrc | Select-Object -Property Hash | ft -HideTableHeaders Write-Output $Display_hash_only Output of the write-output $hashSrc command, will show the Algorithm used, the Hash of the file and path location of the file. Algorithm : SHA256  Hash: AC5522F9DB9F4F432A1AADE69FEF268C8C0B5FD3F22D3A6987719752F8A7108   Path : C:\Users\User1\Downloads\Win10_22H2_EnglishInternational_x64.iso  After getting the Hash File run this code...

Parallel Processing example using PowerShell

PowerShell version 7 has option to run tasks in Parallel.  This would mean that task that can be run in Parallel mode and tasks can be done simultaneously and save time.  How to get started or making use of Parallel in PowerShell?  First, PowerShell has to be in version 7.  Version 7 of PowerShell can be downloaded from Microsoft via this link below.  PowerShell 7 download. Choose the version, whether its x86 or x64.  The CPU architecture in your system will determine whether x64 PowerShell can be used or not.  Check out this link to check CPU architecture in your system:  Check if 64 bit processor or 32 bit Sample code below, shows how Parallel processing in PowerShell can be done.    $HostsIPs = '127.0.0.1','8.8.8.8','8.8.4.4','1.1.1.1'    $HostsIPs | ForEach-Object -Parallel {      Test-Connection $_      } -ThrottleLimit 5   The screenshot image below, shows that the commands indee...

Get accounts in O365 with no ATP or Defender license assigned

Advance Threat Protection aka ATP which is now called Microsoft Defender in office 365, is one of the licenses offered by Microsoft. If there are hundred accounts in O365, tracking which account that doesn't have ATP or Microsoft Defender license is just troublesome. Of course, PowerShell will come into rescue for this kind of issue. One liner code below in PowerShell will check which Office 365 accounts does not have ATP or Microsoft Defender license assigned. Get-MsolUser -All | Where-Object {$_.licenses.AccountSkuId -notcontains 'contoso:ATP_ENTERPRISE'} | Select-Object userprincipalname,licenses | export-csv c:\temp\office_365\no_defender_license.csv Replace contoso with your domain. Or run this command to see which licenses are assigned or available in your tenant. Get-MsolAccountSku | select -ExpandProperty ServiceStatus The PowerShell command checks which accounts does not have ATP assigned; which means that if you have 100 of guests or client user...

PowerShell test/check if file exist

One liner code to check if file exists via PowerShell. Code below will check if Winrar.exe exist on the path specified. if (-not (test-path "$env:C:\Program Files\WinRAR\winrar.exe")) {write-host "File not found"; break;} {write-host "File Found" } Output will show "File Found" if winrar.exe exists on the path specified. The "break;" command on the code will cause the script to exit and not to continue to show "File Found" if the file doesn't exist. Or else it will be confusing to see the output. However, if the file can be found then the "File not Found" will not be shown. PowerShell will automatically bypass the first command on the { } curly braces and execute whatever is on the next line. Code below will check if output.txt exist on c:\temp. if (-not (test-path "$env:C:\temp\output.txt")) {write-host "File not found"; break;} {write-host "File Found" } Output ...

Close all open notepad instances or processes in one go

If you’re an admin and manually checking logs for details and opening each file one by one. Then opening multiple instances of notepad is quite an everyday task. Or you just love notepad in making notes, documentations or other endless reasons to use notepad. Then it will be a headache in closing all the notepad instances that were opened. However, PowerShell can be used to close all instances of notepad all at once. No sweat in clicking each file one by one. PowerShell can handle it in one click of a button if you open the file via PowerShell ISE. Here’s a simple PowerShell code snippet to close all files in one shot. #========== $x = ( Get-Process | Where-Object   { $_ . ProcessName -EQ 'Notepad' }) . count   1 .. $x | % {    stop-process -name notepad –force } #=========== Yes, 2 lines of code can save you a lot of time. The above code can be used also to close other processes that has multiple instances open on the system. If uns...

How to use regex in Linux Bash

Regex or regular expression uses a pattern that is compared to a string and will check if the pattern exists or the string matches the pattern. In Bash script a simple if then else and a regex pattern can be used to check if the pattern matches a set of input on a text file. Bash script below is a simple example on how to use regex in Bash using if then else. Script below uses this sample file "number_file.txt" with the sample text or contents shown below. a12567 b23567 c34568 12w678 23908 35107 23469 x1234 y3432 12094x 123y8 ==== #!/bin/sh patx="^[0-9]+$" while IFS= read -r line; do     echo "Text read from file: $line"     if [[ $line =~ $patx   ]]                then                  echo "Hey this one is alpahumeric --> $line."      else ...

Windows CLI get CPU Name, IP, OS, Mem and computer Name

One of the task of a Windows Admin is to know what OSes are running on his or her environment. Aside from checking what type of OSes are running, making sure also that CPU and Memory on users computers are suitable enough, so users can be productive. If the user doesn't have enough resources to run any software to do users tasks won't be  productive at all since and may end up consuming a lot of coffee than doing their work. :) So, as an IT Admin checking all these things will help to have a smooth operations. IP Address is the communication link of the device to the router, and the IP Address also links to the hostname or computer name and will be ultimately linked also to the logged in user. Example, deploying a specific software to a single user. IP Address must be known  in advanced or else the software being deployed might end up in someone else computer and can be disastrous if the license will be tied automatically to the hostname or IP Address.  WMIC command below...

Notepad++ convert multiple lines to a single line and vice versa

Notepad++ is an awesome text editing tool, it can accept regex to process the text data. If the data is in a “.csv” format or comma separated values which is basically just a text file that can either be opened using a text editor, excel or even word. Notepad++ can process the contents of the file using regex. Example if the data has multiple rows or lines, and what is needed is to convert the whole lines of data into a single line. Notepad++ can easily do it using regex. However, if the data is on a single line and it needs to be converted into multiple lines or rows then regex can also be used for this case. Here’s an example on how to convert multiple rows or lines into a single line. Example data: Multiple rows, just a sample data. Press Ctrl+H, and  on "Find what" type: [\r\n]+ and on "Replace with" type with: , (white space) --white space is needed if need to have a space in between the data. See image below, "Regular Expression" must be se...