windows get IP dynamically - windows

i want to implement the following logic. Does it possible to have such implementation using batch or power shell ? please share with me script for that.
Let say I have a configuration file with the following "config.propertis":
BOOTPRORO=statis or dhcp
IPADDR=192.168.10.10
NETMASK=255.255.255.0
GATEWAY=192.168.10.1
DNS=8.8.8.8
I want that at startup the system will check that file and configure network accordingly:
OS: Windows
if in BOOTPROTO=dhcp, when use DHCP in network configuration and ignore all another in config file, except DNS
if in BOOTPROTO=static, then use all variables from config file to configure IP as static.
So, I have such logic under the Linus, using shell. The script in configured in rc.d and execute before network service. Does it possible to implement such over the Windows ? Guys, please share the script !

We can definitely do this.
First things first, because a lot of systems have more than one network interface, you'll need to determine what the ifIndex is of the adapter that we want to change. Do that by running Get-NetIPInterface. You should see results like this:
In my example and going forward, I'll be using this index, 41. You should change this to match what you find on your own computer.
OK, now to read from the text file. Since you've provided the data in a key=value pair format, commonly called a hashtable, we can easily grab the data from there using ConvertFrom-Stringdata. This will give us a PowerShell hashtable, and we can pull the needed line out like this.
$values = get-content T:\config.properties | ConvertFrom-StringData
$values.BootProro
>statis
We can us this to set the PC in Dynamic IP mode, or to set static addresses. Now, for you to use this in your environment, you need to find the ifIndex, as I mentioned before. replace my index of 41 with your own, and then give it a shot. I've added -WhatIf to every line, so you will see what would happen when you run it. If you're happy with the changes it woudl make, remove -Whatif to make the script actually change the settings.
$values = gc T:\config.properties | ConvertFrom-StringData
if ($values.BOOTPRORO -eq "dhcp"){
Write-Output "---DHCP mode detected in 'config.properties' file"
Write-Output "---Setting Set-NetAdapter -DHCP Enabled"
Set-NetIPInterface –InterfaceIndex 41 –Dhcp Enabled -WhatIf
}
else{
Write-outPut "---static mode detected in 'config.properties' file"
Write-Output "---Removing network configuration"
Remove-NetIPAddress -InterfaceIndex 41 -whatif
Write-Output "---Setting new network configuration equal to"
$values
New-NetIPAddress -DefaultGateway $values.GATEWAY -IPAddress $values.IPADDR -PrefixLength 24 -InterfaceIndex 41 -WhatIf
Set-DnsClientServerAddress -ServerAddresses $values.DNS -InterfaceIndex 41 -WhatIf
}
The output looks like this:

in Windows we can set ip address via batch file or powershell script but when you use dhcp address your ip is Dynamic not static I Imposition you want static ip address
BAtch-file
netsh interface ip set address name=”Local Area Connection” static 192.168.10.10 255.255.255.0 192.168.10.1
netsh interface ip set dns name=”Local Area Connection” static 8.8.8.8
if you want be dhcp You should set
netsh interface ip set address name=”Local Area Connection” source=dhcp
note I Imposition you nic name is Local Area Connection
In powershell V3.0 and Later we Used
New-NetIPAddress –InterfaceAlias “Local Area Connection ” –IPv4Address “192.168.10.10” –PrefixLength 24 -DefaultGateway 192.168.10.1
Set-DnsClientServerAddress -InterfaceAlias “Local Area Connection” -ServerAddresses 8.8.8.8
and for startup you can put script .bat and .ps1 in startup windows but attention you should Set-ExecutionPolicy bypass before U run any script of powershell
for startup any script see link

Related

Why does changing a hostname in the hosts file not change my computer name?

I have to run some servers with different names. So I changed the hostname in Windows 10 inside C:\Windows\System32\drivers\etc\hosts. I changed the name from localhost to brandcil.local:
# localhost name resolution is handled within DNS itself.
# 127.0.0.1 brandcil.local
# ::1 brandcil.local
Now when I am running nslookup 127.0.0.1 in powershell terminal, it is showing this:
Server: UnKnown
Address: 192.168.43.1
Name: localhost
Address: 127.0.0.1
I restarted my machine but it does not take effect. How do I change the hostname then?
Changing the hosts file will not change the hostname. It is only used for hostname-IP-resolution. Besides that, each line that begins with # is a comment and not an active configuration. You can rename a computer with the following PowerShell cmdlet:
Rename-Computer -NewName brandcil -Restart
First of all, any line in the hosts file that begins with # is a comment and will be ignored. The file itself tells you this if you read it. Second, the hosts file has nothing to do with your computer's hostname. All you're doing is creating aliases that will only work on the machines you modify the hosts file on. You're not changing the hostname at all. Third, localhost -> 127.0.0.1 is a static mapping no longer controlled by the hosts file so it will always map to 127.0.0.1. Again, the hosts file tells you this if you read it.
To rename your computer go into Settings --> System --> About. There's a "Rename this PC" button.
If you don't want to use that, then I recommend using the Rename-Computer Powershell command.

What is this command prompt code in MacOS?

I know this code works on Windows, but how do I get workable code executable on MacOS?
netsh -c interface ipv4 add neighbors "(connection name)" "(router
address)" "(mac address)" store=persistent
Any suggestions please...
try typing "man arp" into the terminal. Something like this might work :
arp -s hostname ether_addr
Create an ARP entry for the host called hostname with the Ethernet address ether_addr. The Ethernet address is
given as six hex bytes separated by colons. The entry will be permanent unless the word temp is given in the
command. If the word pub is given, the entry will be ``published''; i.e., this system will act as an ARP server,
responding to requests for hostname even though the host address is not its own. In this case the ether_addr can
be given as auto in which case the interfaces on this host will be examined, and if one of them is found to
occupy the same subnet, its Ethernet address will be used. If the only keyword is also specified, this will cre-
ate a ``published (proxy only)'' entry. This type of entry is created automatically if arp detects that a rout-
ing table entry for hostname already exists.

Windows Powershell Set IP Address on network adapter

I need to be able to take my laptop and plug into several different networks across several locations. Each network requires I use a static address. I currently have a shell script that prompts for a network location and uses netsh to set the IP address. However, Microsoft is warning that they might remove netsh and to use Powershell so I'm trying to recreate my script in Powershell.
The problem I'm having is that if I go from dhcp to a static address I can use:
New-NetIPAddress -InterfaceAlias $myAdapter -AddressFamily IPv4 10.1.2.3 -PrefixLength 24 -Type Unicast -DefaultGateway 10.1.2.1
However, when going from a static address to another static address using New-NetIPAddress just adds another IP address to the adapter (and I cannot connect to anything as it appears to only use the first IP address). To get around that I can use Set-NetIPAddress, but that appears to not accept the -DefaultGateway parameter so I'm assigned the new address, but with the old gateway. I tried using Remove-NetIPAddress, but that appears to leave the gateway parameter so the New-NetIPAddress command fails with "Instance DefaultGateway already exists". How can I either remove the gateway so I can start over with New-NetIPAddress or replace the gateway when using Set-NetIPAddress?
Use Remove-NetRoute to remove the gateway:
# Remove the static ip
Remove-NetIPAddress -InterfaceAlias $myAdapter
# Remove the default gateway
Remove-NetRoute -InterfaceAlias $myAdapter
# Add the new IP and gateway
New-NetIPAddress -InterfaceAlias $myAdapter -AddressFamily IPv4 10.1.2.4 -PrefixLength 24 -Type Unicast -DefaultGateway 10.1.2.255

Windows routes - add many lines to routes table at once

I have to add many lines (rules) to the routes table in Windows.
The regular way is to add it with:
route add 10.0.0.0 mask 240.0.0.0 192.168.0.1
However, if I want to add many lines at once (belive me I have a good reason to do it) - how can I do it quickly (running "route add" is slow)?
I tried running it in some threads and it still slow.
Option 1:
You can use this MS tool: netsh
Netsh is a command-line scripting utility that allows you to, either
locally or remotely, display or modify the network configuration of a
computer that is currently running.
Build a file with all the lines you want to add, like this:
[For more information on "add route" command and its parameters, see here].
# ----------------------------------
# IPv4 Configuration
# ----------------------------------
pushd interface ipv4
add route prefix=10.0.0.0/4 interface="Ethernet" nexthop=192.168.0.1 metric=1 publish=Yes
add route prefix=240.0.0.0/4 interface="Ethernet" nexthop=192.168.0.1 metric=1 publish=Yes
[and so on...]
popd
# End of IPv4 configuration
Save it in a *.dat file, and run this command:
netsh exec file.dat
Option 2:
[As Harry Johnston commented]: You can use CreateIpForwardEntry function to add route (example code in the link).
The CreateIpForwardEntry function creates a route in the local
computer's IPv4 routing table.

PowerShell Script Running as a Service Behaves Strangely

PowerShell Script Running as a Service Behaves Strangely
The Project:
Create a background process that determines if the on board network card is connected. If it is connected, disable the wireless network card. When the onboard network card is not connected, re-enable the wireless card.
Why:
Users hot-dock all the time, getting funky routing tables OR get bound to the wrong DNS servers. When they attempt to access a local resource, say printers, they aren’t able to and then are in my cube (they would file a ticket, but that too would be a local resource). Trying to convince users to disable their own wireless (via switch on laptop) or not hot dock has met with limited success.
The Problem:
The PowerShell script below does run, and does work under my testing conditions. Likely under most testing conditions as the code and wmi queries are pretty generic. Running the script manually yields the expected results, HOWEVER running the script as a service via the only method I could find, srvany.exe, yielded unexpected results and “broke stuff”.
Details:
Running the script as a service, via srvany.exe, works ONCE. When the loop comes back around to test the network connection or tries the method to enable or disable it. The errors indicate that “get-wmiobject” is not a proper Cmdlet. Huh? It works, manually, it works once, but a second time after it disabled the wireless network card it does not. Worse yet MY shell , outside of the service, suddenly can’t do a get-wmiobject, until…. until you go into Device Manager and re-enable the wireless network card yourself.
Debugging attempts:
I rewrote the script and cleaned it up a little to allow for it to get the objects outside of the Do While loop. Nothing changed, but I left the script that way as it seems cleaner anyhow. I enabled “Interact with Desktop” in the service properties and sure enough you can see the script trying to work and getting the before mentioned errors.
Please help. Again the object here is to run a background process, one with enough privileges in Vista or 7 to disable and enable the wireless network card.
#***********************************************************************
# "switch-wifi-srv.ps1"
# This script attempts to identify if a wired network card is in use if
# one is, the Wireless network card is disabled, until the wired network
# card is no longer in use.
#
# Written by Aaron Wurthmann - aaron (AT) wurthmann (DOT) com
#
# 2010.02.10 ver 2 (Service Version)
# If you edit please keep my name or at the very least original author's.
# As of this writing I am unsure if script will work with all scenarios,
# however it has worked for me on Dell laptops running Windows 7 x64.
# -----------------------------------------------------------------------
# This script comes with ABSOLUTELY NO WARRANTY.
# You may redistribute copies of the script under
# the terms of the GNU General Public License.
# -----------------------------------------------------------------------
# Service Installation:
# Aquire and install the Windows 2003 Resource Kit OR the srvany.exe.
# Use sc.exe and srvany.exe to create a service....
# sc create SwitchWifiAuto binPath= "C:\Program Files (x86)\Windows Resource Kits\Tools\srvany.exe" DisplayName= "Switch Wifi Automatically"
# Edit registry entry for SwitchWifiAuto, add a key and a string value...
# HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\SwitchWifiAuto\Parameters]
# "Application"="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -ExecutionPolicy RemoteSigned -File C:\\SwitchWifiAuto\\switch-wifi-srv.ps1"
#************************************************************************
$state=""
$wireStatus=""
$wifiStatus=""
# Get Wired and Wireless Card Objects
$objWire=get-wmiobject -class win32_networkadapter -namespace root\CIMV2 | Where-Object {$_.Name -notmatch "Wireless" -and $_.Name -notmatch "Virtual" -and $_.PhysicalAdapter -eq "True"}
$objWifi=get-wmiobject -class win32_networkadapter -namespace root\CIMV2 | where-object {$_.Name -match "Wireless"}
# Get Name of Service to be Used in totally useless Do While Loop
$objService=get-service -display "Switch Wifi Automatically"
# Begin Do While Loop
Do {
# Get status of wired network card. If enabled and connected set $state to Disable (which will later Disable the Wifi network card)
[string]$wireStatus=$objWire | % {$_.NetEnabled}
if($wireStatus -eq "True") {
$state="Disable"
}
# Get Status of wireless card.
if($objWifi){
[string]$wifiStatus=$objWifi | % {$_.NetEnabled}
# If $state is not set to disable and if the wireless card is currently disabled, enable it.
if($state -ne "Disable") {
if($wifiStatus -eq "False") {
Out-Null -InputOject ($objWifi | % {$_.Enable()})
}
# If $state is set to Disable and if wireless card is currently enabled, disable it.
} else {
if($wifiStatus -eq "True") {
Out-Null -InputOject ($objWifi | % {$_.Disable()})
}
}
}
# Reset Checked Variables for good measure
$state=""
$wireStatus=""
$wifiStatus=""
# Sleep for 120 seconds (two minutes)
Start-Sleep -s 120
# Continuing looping (do while) until the service is not running.
# This is of course technically useless as when the service is not running neither is the script to check if the service is not running.
# I made it this way however because I don't like infinite loops and I thought it would be funny to it this way instead of while $var=0
} while ($objService.Status -eq "Running")
Try to remove any output. Service don't have stdout stream. And when the buffer is full strange thing happens. Just a guess ( I never used powershell ).
Debugging attempts: I rewrote the script and cleaned it up a little to
allow for it to get the objects outside of the Do While loop.
You need to include these within the loop or you will not get updated values and the loop will do nothing.

Resources