Showing posts with label Scripting. Show all posts
Showing posts with label Scripting. Show all posts

Windows 2025 Server #OSConfig and manage Security settings

Windows 2025 server has a new feature called OSConfig that permits you to configure Microsoft"s recommended security settings.

This can be done through powershell, Windows Admin center and Azure Policy

More details and command lines could be found here:

https://techcommunity.microsoft.com/blog/itopstalkblog/using-osconfig-to-manage-windows-server-2025-security-baselines/4415824

https://4sysops.com/archives/osconfig-manage-security-settings-in-windows-server-2025-and-revert-configuration-drift/

TIPS #curl troubleshooting website/connectivity check tool

Today I would like to take note on blog about curl command line tool that allow to send and receive data from servers using URL and for scripts automation too.

It supports various internet protocols like http, https, ftp, ftps, scp, sftp.

Is used for file download, testing and website checking

curl -vvv https://www.google.it

Curl -vvv https://website User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:58.0) Gecko/20100101 Firefox/58.0

curl man page

https://curl.se/docs/manpage.html

SCRIPTING #HOW TO CHANGE PACKET/MTU size on Windows systems

These are ping and windows commands to show network interfaces and change packet size

ping -t app.livewebinar.com -f -l 1400

netsh interface ipv4 show interface

netsh interface ipv4 set subinterface <ID> mtu=1360 store=persistent

Scripting - Get-ADUser - How to retrieve User last logon date

There is an easy and quick way to get .TXT file with all AD Usernames and relatives last logon dates.

  1. You must execute Powershell module with Administrative rights.
  2. Import-Module activedirectory
  3. Get-Help Get-ADComputer
  4. Get-ADUser -filter * -Properties * | Select-Object SamAccountName, Company, @{Name="Manager";Expression={(Get-ADUser $_.Manager).sAMAccountName}}, enabled, LastLogonDate , AccountExpirationDate, displayname, GivenName, surname, custJDEEmployeeID | Export-csv C:\temp\ADUsers.csv

here it is an alternative article related to AD computers

SCRIPTING - HOW TO CHECK SERVER UPTIME WITH SINGLE COMMAND #part 2

In previous article I mentioned a way to check remote client/server uptime.

https://www.alessandromazzanti.com/2022/03/scripting-how-to-check-server-uptime.html

An alternative way is to execute these powershell commands:

$serverName = "NomeDelServer"

$uptime = (Get-WmiObject -Class Win32_OperatingSystem -ComputerName $serverName).ConvertToDateTime((Get-WmiObject -Class Win32_OperatingSystem -ComputerName $serverName).LastBootUpTime)

$uptime

Citrix #how to script PVS (provisioning services) using powershell

 If you have to automate some PVS Citrix actions you could have a look to this article.

It contain several useful information:

https://workspace-guru.com/2017/10/21/scripting-citrix-provisioning-services-pvs-powershell-commandline/

From my side I found useful this command line instructions to automatically publish test to prod Xenapp environment

Invoke-PvsPromoteDiskVersion -DiskLocatorName ““YourDiskName” -StoreName “YourStoreName” -SiteName “YourSiteName” -Test

Scripting - Using telnet through command line or PowerShell

Other than using telnet with this syntax (it is required to install Telnet Client on device using add/remove program or alternative ways)

telnet IP/hostname port_number

telnet 192.168.100.2 443

otherwise you can utilize powershell too with this syntax

PS C:\> Test-NetConnection

or PS C:\> tnc

Example 1: Test ping connectivity

PS C:\> Test-NetConnection

Example 2: Test ping connectivity with detailed results

PS C:\> Test-NetConnection -Port 80 -InformationLevel "Detailed"

Example 3: Test TCP connectivity and display detailed results

PS C:\> Test-NetConnection -ComputerName ayampenyet.com -Port 443

Example 6: Perform route diagnostics to connect to a remote host with routing constraints

PS C:\> Test-NetConnection -ComputerName "www.contoso.com" -ConstrainInterface 5 -DiagnoseRouting -InformationLevel "Detailed"

more examples coud be found here

https://learn.microsoft.com/en-us/powershell/module/nettcpip/test-netconnection?view=windowsserver2022-ps

PowerShell #delete specific folders through script

In case you need to search recursively  folders in a specific path and then delete them you can use below powershell script. (these example folders are related to teams cache cleaning topic)

Be aware that -whatif option permits to see output without really deleting folders. 

Get-ChildItem "diskdrive:\path\*\AppData\Roaming\Microsoft\Teams\*" -directory | Where name -in ('application cache','blob storage','databases','GPUcache','IndexedDB','Local Storage','tmp', 'cache') | ForEach{Remove-Item $_.FullName -Recurse -Force -whatif}


CISCO - Show the Complete Configuration without Breaks/Pauses on Cisco Router/Switches, ASA Firewall and WLC

On Cisco Network devices you could have necessity to show running configuration withouth breaks/pauses:

switches/router:

show terminal | in Length

terminal length 0

show run

show run brief 

WLC

config paging disable

show run-config" to display the config.

Cisco ASA

Pager (saved)

terminal pager (telnet session not saved)

The default is 24 lines; 0 means no page limit.

1. Type "pager 0" in priviledged mode to set your terminal to display without any breaks.

2. Type "show run-config" to display the config.

3. Type "pager 20" in priviledged mode to set your terminal to display with breaks every 20 lines.


full article:

https://community.cisco.com/t5/networking-knowledge-base/show-the-complete-configuration-without-breaks-pauses-on-cisco/ta-p/3115114

Command line - findstr paramater

There is an easy way to find string internally command output.

This command is Findstr known.

systeminfo | findstr /i "system model" 

To find local server/pc network connection in plase below command it could be very useful

nestat -ano | findstr /i "x.y.z.w"

Scripting - Enumerate file extension, count them and indicate total size

If you have necessity to analyze single folder (and relatives subfolders), identifying all files extensions, count files numbers and indicate total size this script will assist you on this requirement

$directory = "D:\foo"

#Get all items

Get-ChildItem -Path $directory -Recurse |

#Get only files

Where-Object { !$_.PSIsContainer } |

#Group by extension

Group-Object Extension |

#Get data

Select-Object @{n="Extension";e={$_.Name -replace '^\.'}}, @{n="Size (MB)";e={[math]::Round((($_.Group | Measure-Object Length -Sum).Sum / 1MB), 2)}}, Count

https://stackoverflow.com/questions/22616634/determine-recursively-both-count-and-sum-of-all-extensions-in-a-folder


SCRIPTING - HOW TO SCHEDULE SERVER REBOOT

If you need to plan one shot (fixed time and date) reboot you could use this command.

It will create a scheduled task, that can be executed with or without any one logged on.

(no password saving is required)

Obviously any other customization is easily to be rearranged.

schtasks /create /sc once /tn taskname /tr "shutdown -r -f” /st hh:mm /sd dd/mm/yyyy /NP

 

/NP   No password is stored.  The task runs non-interactively

            as the given user.  Only local resources are available.      

 /SC   schedule    Specifies the schedule frequency.

                                    Valid schedule types: MINUTE, HOURLY, DAILY, WEEKLY,

                                    MONTHLY, ONCE, ONSTART, ONLOGON, ONIDLE,                                     ONEVENT.                                                          

 

/SD   startdate    Specifies the first date on which the task runs. The

                                   format is dd/mm/yyyy. Defaults to the current

                                    date. This is not applicable for schedule types: ONCE,

                                    ONSTART, ONLOGON, ONIDLE, ONEVENT.                           

                                                                               

/ST   starttime     Specifies the start time to run the task. The time

                                    format is HH:mm (24 hour time) for example, 14:30 for

                                    2:30 PM. Defaults to current time if /ST is not

                                    specified.  This option is required with /SC ONCE.

               

/TN   taskname    Specifies the string in the form of path\name

                                    which uniquely identifies this scheduled task.

                                                                               

/TR   taskrun      Specifies the path and file name of the program to be

                                    run at the scheduled time.

                                    Example: C:\windows\system32\calc.exe            

[UPDATE 2023.08.08]

Windows 2003/2008/2008 R2/2012/2012 R2 this is correct syntax.

schtasks /create /sc once /tn taskname /st hh:mm /sd dd/mm/yyyy /NP /tr "shutdown -r -f”

schtasks /create /sc once /tn "Server Reboot" /st 19:00 /sd 19/05/2025 /NP /tr "shutdown -r -f”


SCRIPTING - HOW TO CHECK SERVER UPTIME WITH SINGLE COMMAND

If you must check server uptime (or any other information) systeminfo is an interesting command line tool (Windows builtin)

SystemInfo /s SERVERNAME| find "Boot Time:"

With previous command you could obtain remote server uptime information

Indeed concatenating previous commands, using &&, it will aggregate several server info "one shot"

SystemInfo /s SERVERNAME1 | find "Boot Time:" && SystemInfo /s SERVERNAME2| find "Boot Time:"

Consider that you might launch command line, locally, with AD account with enough permissions on remote servers.

[related article]

Scripting - How to refresh remote client ip

[Update - 2022.11.17]

There is an alternative way to check, remotely, system uptime, it is using psexec in conjunction with wmic command.

About psexec you can review this old blog article:

https://www.alessandromazzanti.com/2014/04/psexec-21-download-and-tutorials.html

  1. execute cmd with Administrative rights
  2. cd c:\patchwherepsexecislocated\
  3. PsExec64.exe \\REMOTEPCNAME cmd
  4. wmic path Win32_OperatingSystem get LastBootUpTime



Scripting - File Server migration using robocopy command

In the past we managed 2008 to 2016 migration and so I am taking note about robocopy syntax that it was useful during this project. (focused on file servers migration)

Approach was replicating root folder on new server, enabling share (on new server), stopping old share folder and finally launching this command (from old file  server) for final folder synchronization.

robocopy local_drive:\localfoldername \\remote_server\remote_share_name /E /COPYALL /SEC /MIR /ZB /W:1 /R:1 /LOG:C:\locallogfolder\SYNC_OLDSERVER_VS_NEWSERVER_DATE_TIME.LOG /TEE 

/SEC it replicate security permissions

/Tee it enable video logging real time display

/SECFIX it fix security permissions

Meanwhile I am adding  old blog articles links:

Backup - Robocopy and real time monitoring of any file changes

https://www.alessandromazzanti.com/2016/09/backup-robocopy-and-real-time.html

Scritping - Using robocopy to replicate files to remote location on scheduled tasks and sending final log and status email

https://www.alessandromazzanti.com/2014/01/scritping-use-robocopy-to-replicate.html

Backup – Lista dei comandi di Robocopy

https://www.alessandromazzanti.com/2013/02/backup-lista-dei-comandi-di-robocopy.html

Tips - How to migrate file server share and permissions

https://www.alessandromazzanti.com/2015/11/tips-how-to-migrate-file-server-share.html

Scripting - Inviare una mail da riga di comando in windows

https://www.alessandromazzanti.com/2011/01/inviare-una-mail-da-riga-di-comando-in.html

Script - How to enumerate/export, to .CSV, shared Folder/Subfolders Security permissions

It is important to verify shared folder permissions to find any misconfiguration.

I found an interesting script that easily enumerates all shared folders and it creates a .csv file (for reporting purposes).

Here it is relative script and link:

https://social.technet.microsoft.com/wiki/contents/articles/51422.how-to-export-folder-permissions-to-excel-or-csv-file.aspx

This powershell script enumerates all folder and subfolders permissions of a folder and exporting it to ,csv file.


An alternative article (that I did no test)





Scripting - Get-ADComputer - How to retrieve computer last logon date

There is an easy and quick way to get .TXT file with all AD computer names and relativse last logon dates.


  1. You must execute Powershell module with Administrative rights.
  2. Import-Module activedirectory
  3. Get-Help Get-ADComputer
  4. Get-ADComputer -Filter * -Properties *  | Sort LastLogonDate | FT Name, LastLogonDate -Autosize | Out-File C:\Temp\ComputerLastLogonDate.txt




Alternative approach could be:
  1. $DaysInactive = 90
  2. $time = (Get-Date).Adddays(-($DaysInactive))
  3. Get-ADComputer -Filter {LastLogonTimeStamp -lt $time} -ResultPageSize 2000 -resultSetSize $null -Properties Name, OperatingSystem, SamAccountName, DistinguishedName
  4. Get-ADComputer -Filter {LastLogonTimeStamp -lt $time} -ResultPageSize 2000 -resultSetSize $null -Properties Name, OperatingSystem, SamAccountName, DistinguishedName | Export-CSV “C:\Temp\StaleComps.CSV” –NoTypeInformation
[original articles]



Cisco - How to backup Cisco switches using TFTP

There are several ways on how backup Cisco switches (or other vendors name) can be done.

One of them is downloading TFTP client server

https://tftp.en.uptodown.com/windows

Launching it and deciding where saving configuration files.

Be aware taking note about client IP.

Later you need to connect to switches using any SSH clients (I warmly suggest using these clients:

  1. Solar-PuTTY Connect to any server or device in your network with Solar-PuTTY for Windows. This is an interesting Putty or PuttyCM alternative.

https://www.alessandromazzanti.com/2018/11/freeware-solarwinds-software-free-tools.html

and execute below commands on switches:

Router#copy running-config tftp: 

Address or name of remote host []? 64.104.207.171

Destination filename [ce_2-confg]? backup_cfg_for_my_router

!!

1030 bytes copied in 2.489 secs (395 bytes/sec)

CE_2#

Where:

  • 64.104.207.171 must be substituted by your client ip address where tftp is under execution.

  • backup_cfg_for_my_router is backup file name that will be created on client where tftp is under execution.
You can configure automatic backups, you simple need to read all article below indicated.

[original article]

https://www.cisco.com/c/en/us/support/docs/ios-nx-os-software/ios-software-releases-122-mainline/46741-backup-config.html