Searching network devices for smb1 using powershell - powershell

Get-WindowsOptionalFeature –Online –FeatureName SMB1Protocol
Will tell me if the machine I run it on is running smbv1
Can this be somehow modified to run on remote machines? I have about 1000 servers, 6000 workstations, and 10,000+ IoT/Network devices (though, they're not running windows).
I know packet capturing is the typical method, however I don't really have a central choke-point to put a packet analyzer in my environment.

I solved this with nmap + powershell
$NmapFolder = Get-ChildItem -Path "U:\nmap reports\Nmap Subnet
Scans\September2019" -Recurse -Directory -Force -ErrorAction SilentlyContinue
$data = ForEach ($item in $NmapFolder){
$Subnet = $item.Name.replace('_','/')
write-host "scanning"$Subnet". Please wait..."
nmap -p 445 --script smb-protocols -oN "U:\\nmap reports\\Nmap Subnet Scans\\September2019\\$item\\SMB_results.nmap" $Subnet
write-host "Done, report written for"$Subnet". Report has been written to: U:\\nmap reports\\Nmap Subnet Scans\\September2019\\"$item"\\SMB_results.nmap"
}
I made a folder (September2019) that contains a bunch of folders named after my subnets:
10.0.0.0_23
10.10.10.0_24
10.100.10.0_24
etc. I have a bout 120 local subnets in my organization.
I then change _ to / (Windows folder names can't have /)
Now I have a CIDR notation that I can throw at nmap.
Nmap has a script to analyze a target for SMB, and it'll tell me what versions it's running.
The output for the whole subnet goes into it's respective folder, and move to the next.
I'll write another script to parse all of the results and only show me targets that have SMB1 enabled.

Related

Powershell Get-EventLog from computers.txt and save data

I have some problems getting EventLog and save data. I am able to get my EventLogs but not logs from network computers.
Here is the code I am running:
$logFileName = "Application"
$path = $MyInvocation.MyCommand.Path +"\Output\"
$path = $PSScriptRoot+"\Output\"
new-item $path -ItemType directory
$array = ("System", "Security")
$file = $PSScriptRoot +"\computers.txt"
$users = ForEach ($machine in $(Get-Content $file)) {
$pathMachine = $path+$machine
new-item $pathMachine -ItemType directory
ForEach ($logFileName in $array){
# do not edit
$logFileName
$exportFileName = (get-date -f yyyyMMdd) + "_" + $logFileName + ".evt"
$logFile = Get-WmiObject Win32_NTEventlogFile -ComputerName $machine | Where-Object {$_.logfilename -eq $logFileName}
$logFile
$exportFileName
$pathMachine
$temp = $pathMachine + "\"+ $exportFileName
$temp
$fff = $logFile.BackupEventLog($temp)
}
}
This could e considered a duplicate of this.
Reading event log remotely with Get-EventLog in Powershell
# swapped from this command
get-eventlog -LogName System -computername <ServerName>
# to this
invoke-command {get-eventlog -LogName System} -ComputerName <ServerName>
Don't struggle with writing this from scratch. Well, unless it's a learning exercise. There are pre-built script for you to leverage as is and or tweak as needed.
Running commands on Remote host require using the Invoke cmdlet, and or an established PSRemoting session to that host.
Get Remote Event Logs With Powershell
Gather the remote event log information for one or more systems using wmi, alternate credentials, and multiple runspaces. Function supports custom timeout parameters in case of wmi problems and returns Event Log information for the specified number of past hours.
Download: Get-RemoteEventLogs.ps1
The script is too long (it's 100+ lines) to post here, but here in the Synopsis of it.
Function Get-RemoteEventLogs
{
<#
.SYNOPSIS
Retrieves event logs via WMI in multiple runspaces.
.DESCRIPTION
Retrieves event logs via WMI and, if needed, alternate credentials. This function utilizes multiple runspaces.
.PARAMETER ComputerName
Specifies the target computer or comptuers for data query.
.PARAMETER Hours
Gather event logs from the last number of hourse specified here.
.PARAMETER ThrottleLimit
Specifies the maximum number of systems to inventory simultaneously
.PARAMETER Timeout
Specifies the maximum time in second command can run in background before terminating this thread.
.PARAMETER ShowProgress
Show progress bar information
.EXAMPLE
PS > (Get-RemoteEventLogs).EventLogs
Description
-----------
Lists all of the event logs found on the localhost in the last 24 hours.
.NOTES
Author: Zachary Loeber
Site: http://www.the-little-things.net/
Requires: Powershell 2.0
Version History
1.0.0 - 08/28/2013
- Initial release
#>
Or this one.
PowerShell To Get Event Log of local or Remote Computers in .csv file
This script is handy when you want to extract the eventlog from remote or local machine. It has multiple filters which will help to filter the data. You can filter by logname,event type, source etc. This also have facility to get the data based on date range. You can change th
Download : eventLogFromRemoteSystem.ps1
Again, too big to post here because the length is like the other one.
I am working on some assumptions but maybe this will help.
When I Ran your Code I got
Get-Content : Cannot find path 'C:\computers.txt' because it does not exist.
I had to make the C:\computers.txt file, then I ran your code again and got this error.
Get-Content : Cannot find path 'C:\Output\computers.txt' because it does not exist.
I made that file in that location, then I ran your code again and I got the event log file. Maybe try creating these two missing files with a command like
Get-WmiObject Win32_NTEventlogFile -ComputerName $machine
mkdir C:\Output\$machine
$env:computername | Out-File -FilePath c:\Output\Computers.txt
You may also want to setup a Network share and output to that location so you can access the event logs from a single computer. Once the share is setup and the permissions just drop the unc path in.

Bulk IP configuration using CSV input

I have a CSV file with the following values for each machine I want to remotely reconfigure using static IP
name,nic,ip,mask,defaultgw
I was hoping to be able to reconfigure the IPs for each listed but if I have more than one machine listed the script gets stuck. This is because at the end of the first loop iteration, unless I manually do an ipconfig /flushdns on the server the script is running from, I will lose connection to the server being configured and the script just hangs leaving the rest of the servers. What I have so far is this:
$csv = import-csv "c:\scripts\builds\machines.csv"
foreach ($Row in $csv) {
$machine = $Row.name
$Nic = $row.Nic
$address = $row.IP
$mask =$row.mask
$defaultgw = $row.gw
invoke-command -computername $machine -scriptblock { Get-NetIpAddress - InterfaceAlias $using:nic | New-NetIPAddress -ipaddress $using:address -PrefixLength $using:mask -DefaultGateway $using:defaultgw | Register-DnsClient}}
}
Can this be done using workflows or just simple start-job?
I suspect you're losing the connection to the remote machine once you change the IP address, while the local machine hangs trying to keep the connection.
Try making the call, and dropping off a payload, then running it after you disconnect.
That is, upload the code, then spawn it, then disconnect before it has a chance to run (add a sleep to the remote code maybe?). This way, you can launch your payload and disconnect before it affects you.
For example, you could copy a file to that machine with the values it needs, then schedule a task to run in 5 seconds in the future, then disconnect before it runs. The task will then run, and since you're already disconnected, you won't be affected by it.
You might also consider DHCP with static reservations. It's far easier to manage than what you're trying to do here.

New-NetLbFoTeam: Unknown or Random InterfaceAlias names

I'm trying to automate the create of a NIC team during an unattended Windows Server 2012 R2 install.
I've got the following PowerShell code:
New-NetLbFoTeam -Name "LANTeam" -TeamMembers "Ethernet", "Ethernet 2" -TeamNicName "LAN" -TeamingMode SwitchIndependent -LoadBalancingAlgorithm TransportPorts -Confirm:$false -ErrorAction SilentlyContinue
That works well for my Dell servers, but the HP servers Windows randomly gives InterfaceAliases to. One install Ethernet 2 could be the Broadcom, the next it could be the NC373i card.
What I'm trying to accomplish is set the -TeamMembers parameter to be the two NICs that match "HP NC373i*" wildcard for the InterfaceDescription, or have a valid DHCP address. The other team I'll do something similar, but don't retrieve a valid IP address.
I've tried setting a hash table, but not getting it to stick in there correctly.
Any assistance would be greatly appreciated!
I was able to figure it out on my own. I output the get-netadapter output to a variable, and added that:
$adapters = Get-netAdapter –InterfaceDescription “HP NC*”
$nicList = #()
Foreach ($nic in $adapters) {$nicList += $nic.Name}
$team = New-NetLbfoTeam -Name “LANTeam” -TeamNicName “LAN” -TeamMembers ($nicList) -TeamingMode SwitchIndependent -LoadBalancingAlgorithm HyperVPort -Confirm:$false

How to Wait till a DHCP server assign's IP to a first time boot VM with a Sysprepped vhd attached to it using PowerShell in Hyper-V version 3.0

I'm going through a scenario where i boot a Newly built VM with a sysprepped vhd attached, once the setup process completes with installing devices etc and the OS gets loaded i wanted to wait till this entire process finishes and the VM is assigned an IP address via DHCP.
PS C:\Users\Administrator> Start-VM -Name dv.VMWIN2K8R2-3.Hng
PS C:\Users\Administrator> while ((Get-VM -Name dv.VMWIN2K8R2-3.Hng | select -ExpandProperty networkadapters).ipaddress[0] -match $null)
{
Start-Sleep 3
Write-Host "Waiting to Acquire IP Address" -ForegroundColor green
}
$ipaddress=(Get-VM -Name dv.VMWIN2K8R2-2.Hng | select -ExpandProperty networkadapters).ipaddresses[0]
Write-Host "VM has acquired an IPAddress of $ipaddress"
I Tried the above snippet but the while loop never run's, i have noticed that while VM is shutdown the ip address parameter is blank so i thought to match it till it shows Null and when i boot up the VM and once the server gets an IP address by DHCP it should exit the while loop and print the IP address on console.
The IP is probably not null, so it's doing exactly what it should. The IP is probably 169.254.x.x, or at least that's what happens to me before I pick up DHCP. How about choosing the first octet of the address it should have after it picks up an address and using that?
EDIT: Maybe it's not 169 as I thought, after re-reading your post. My advice still applies. Try using something like this: While (!($ip -like "10.*")
If there is no network stack there are no addresses and I think you'll find the array is not there. Chris is on the right track. I think you'll need to not do what you're doing but first test to see if ipaddress is a property, is an array, and has at least 1 item in it before checking the value of that item.
Hi Guys i was able to solve the issue, i used the Get-VMNetworkAdapter Cmdlet and it solved the issue
while (((Get-VMNetworkAdapter $vmname | select -ExpandProperty ipaddresses) -eq $null -or ((Get-VMNetworkAdapter $vmname | select -ExpandProperty ipaddresses) -match "169.")))
{
Write-Progress -Activity "Waiting for VM to Aquire an IPAddress"
}

Find SCVMM Management Server within a VM Host/VM

Is it possible to locate a SCVMM Management server from within a Hyper-v host? Is this possible via powershell? I am trying to find which machine manages one of my Hyper-v hosts. I've had no luck searching through registry/wmi. Any ideas?
Thanks in advance!
Not sure about powershell, but I just had to do this today.
1) looked up the port config for scvmm. So far, 5985 looks like the one: Link
2) On your host, run netstat -ano |find "5985"
3) That should return a list scvmm management servers connected.
As far as I know, no. What you could do is to query all of your SCVMM servers and see which happens to know the guest.
Load up the VMM module and connect to your VMM.
# VM name, might or might not be hostname
$guestToLook = "myLostVM"
# A list of all of your VMM servers
$VMMServers = #("vmmsrv01", "vmmsrv02", "vmmsrv03")
$VMMServers | % {
# Connect to VMM server
Get-VMMServer $_
# Get a VM from the VMM host by guest name
$vm = Get-VM -name $myLostVM
# If VM object is returned, you got the VM from current VMM host.
if($vm.Name -eq $myLostVM) { "{0} is managed by VMM host: {1}" -f $vm.Name, $_}
}
Here's a solution via PowerShell.
First we need the registry path on the host for SCVMM config values.
$scvmmAgentKeys = 'HKLM:\SOFTWARE\Microsoft\Microsoft System Center Virtual Machine Manager Agent\Setup'
Now we grab the SCVMM agent port from the registry path.
$wsManTcpPort = (Get-ItemProperty -Path $scvmmAgentKeys -Name WSManTcpPort).WSManTcpPort
Finally, collect the addresses which are listening on that port.
$scvmmAddress = (Get-NetTCPConnection -LocalPort $wsManTcpPort).LocalAddress | Get-Unique | where { $_ -ne "::" }
Note that if anything else has a connection established on the same port (default port at time of writing is 5985) then $scvmmAddress will be an array including the addresses of those other established connections, which are not necessarily SCVMMs.
Fantastic . The only correction shall be
3. $scvmmAddress = (Get-NetTCPConnection -LocalPort $wsManTcpPort).**Remoteaddress** | Get-Unique | where { $_ -ne "::" }