script to manipulate the dhcp/conf - bash

i want to write a script to manipulate the dhcp.conf file. which in the sense, it has to read the file and it should ping all the lease IP and should give another text file, in which it should give the list of IPs, which devices are now existing.
EDIT: thanks for your swift reply. dhcpd.conf file is like this
lease 172.31.0.10 {
some text
some text1
}
lease 172.31.0.12 {
some text
some text1
}
lease 172.31.0.100 {
some text
some text1
}
so first i need to extract the ip address first and one by one we have to ping

Assumptions
First, there are two things you need to be aware of:
Not all devices respond to ping. Quite a few PC firewalls disable
ping replies. If you're on Ethernet, arping can be used instead and
will even detect firewalled PCs.
dhcpd leaves leases in the file which it /knows/ are no longer valid.
So, here is an example:
lease 192.168.66.132 {
starts 4 2009/01/08 23:58:41;
ends 5 2009/01/09 00:00:41;
binding state free;
hardware ethernet 00:e0:81:28:2d:56;
}
lease 192.168.66.133 {
starts 5 2009/01/09 03:17:17;
ends 2 2038/01/19 03:14:06;
binding state active;
next binding state free;
hardware ethernet 00:e0:81:28:2d:57;
}
You can see that 132 is not in use (binding state free) and 133 is
(binding state active). Another possibility is binding state backup,
but that only occurs in a failover config.
A lease can also be abandoned, which means that the DHCP server was
going to assign that IP, but found it was already in use (via ping).
This is all documented in dhcpd.leases(5).
Why are you wanting this?
The DHCP server already re-uses expired leases. Is there a good
reason that you need to check its work? If you're running out of
leases, have you considered lowering the lease time?
Does nmap -sP <start_ip>-<end_ip> do what you need? That'll also
detect machines with static IP addresses.
Re-writing the question
So, given the above, and assuming you still want this, I'm going to
answer this question instead:
Please write a script to find all leases which are either active or
abandoned and determine if there is currently a machine using that IP
address.
And so:
#!/usr/bin/perl
use File::Slurp qw(slurp);
use Data::Dump qw(pp);
use strict;
1 == #ARGV
or die "Usage: $0 dhpcd.leases\n";
my $leases = slurp($ARGV[0]);
$leases =~ s/^#.*\n//mg;
my #leases = split(/lease (\d.+\d.+\d.+\d+) {/, $leases);
shift #leases;
my %lease = #leases;
while (my ($ip, $rec) = each %lease) {
print $ip;
$rec =~ /^\s*abandoned;\s*$/m and print " abandoned";
$rec =~ /^\s*binding state free;\s*$/m and print " free";
$rec =~ /^\s*binding state active;\s*$/m and print " active";
print "\n";
}
This relatively ugly perl script will give you output like:
192.168.66.132 free
192.168.66.133 active
Which should be pretty easy for you to feed to arping.

the problem is, binding state active; does not means, the device is active. To make sure the device is active, we need to ping the devices first. there is no other way we can do it

Related

Use powershell to find Which Adapter is being used

I have three Ethernet Adapters on my windows machine. All show status connected and up.
I want to understand how can I find from PowerShell which adapter is being used to connect to the internet. Via UI I can see Ethernet0 being the one but how to find that via powershell. Any ideas are welcomed. Especially something that is supported in powershell 2 as well.
PS C:\Users> Get-NetAdapter -physical
Name InterfaceDescription ifIndex Status
Ethernet0 Intel(R) 82574L Gigabit Network Conn... 15 Up
Ethernet1 Intel(R) 82574L Gigabit Network Co...#2 9 Up
Ethernet2 Intel(R) 82574L Gigabit Network Co...#3 4 Up
Get-NetAdapterStatistics will return information such as traffic on the adapter specified which you can use to create a script to listen for a change in value.
Here's some quick and dirty scripting using that cmdlet:
$keySet = #{}
:loop while ($true) {
$adapters = Get-NetAdapter -Physical | Get-NetAdapterStatistics
foreach ($adapter in $adapters)
{
if (-not $keySet.ContainsKey($adapter.Name)) {
$null = $keySet.Add($adapter.Name,$adapter.ReceivedBytes)
}
if ($adapter.ReceivedBytes -ne $keySet[$adapter.Name]) {
Write-Output -InputObject $adapter.Name
Break loop
}
}
}
By creating a hashtable, you can append the Name and ReceivedBytes property to it. Then reference the key values later on in your second iteration to compare from your first iteration. Using a while loop, you can set a constant listener to see which adapter will be the first to receive a packet; this in turn gives a different value of what's stored in $keySet and will break you out of the loop but not before outputting the Name of the adapter.
The issue comes with the adapters that are receiving any other traffic. That's something to be weary of. That is also something you can improve on later on down the road if you want to continue to use this example.
Hopefully this gets you on the right track.

Can any port in the sate of "LISTEN" be seen to the outter?

I execute the command "netstat -tln" in the shell, here is what it outputs.
the 5th field is the foreign address, i dont' know what it means here. Does "0.0.0.0:" mean any address can be connected to this port without the consideration of iptables, if so what does ":::" mean?
The 3 Colons (:::) signifies IPv6.
The 0.0.0.0 means that a given socket is listening on all the available IP addresses the computer has available.
If you wish to not use IPv6 i believe you can remove it.
Verify the Man Page but probably removing "ipv6.o"" will work.

What snmp OID should I watch to see if my printers and switches is up an running

I am new to snmp, and I am trying to figure out what OID's I should get/trap to see if my printers, switches (and servers) is running? I do not need to know the details - just a simple test. I have successfully med get, getbulk, (and walk) request from a device, both from bash and iReasoning MIB browser.
Edit:
Maybe the
.1.3.6.1.2.1.1.3.0
Name/OID: sysUpTime.0; Value (TimeTicks): 194 hours 43 seconds (69844352)
is used for just that!? What happens when something is wrong? -will this be reset immediately? -or will it just stop counting? or is it just the time since last power on?
Printers
You should use the Printer MIBv2 to monitior printer error status for jams...
hrPrinterDetectedErrorState reports printer errors such as low toner, jams, etc... the RFC contains details on what specific codes mean
hrDeviceStatus will reveal the big picture ability of the printer to handle tasks. For more info, see Printer MIBv2, Section 2.2.13.2
sysUpTime.0 is an OID that reports the time a system's SNMP stack has been up (reference RFC 1213: MIB-II). If this value is returned and incrementing, it's a 99% safe bet that a printer is up. Most people use sysUpTime to detect whether the device has rebooted for some reason; if that happens, you'll see a sudden decrease in sysUpTime.0, unless your last value was around 248 days (where a 32-bit counter would roll).
Ethernet Switches
Checking the basic health of ethernet switches is usually done with checks to sysDescr.0 or sysUpTime.0; the problem with this heuristic comes if you care about the up/down status of particular links... at that point, you need to check values from ifOperStatus, which is indexed by ifIndex and uses interface names from ifName. See the following examples...
[mpenning#Hotcoffee ~]$ ## Walk ifName correlated to ifIndex
[mpenning#Hotcoffee ~]$ snmpwalk -v 2c -c Public 172.25.116.6 .1.3.6.1.2.1.31.1.1.1.1
iso.3.6.1.2.1.31.1.1.1.1.1 = STRING: "Fa0/0"
iso.3.6.1.2.1.31.1.1.1.1.2 = STRING: "Nu0"
[mpenning#Hotcoffee ~]$ ## Walk ifOperStatus (up==1)
[mpenning#Hotcoffee ~]$ snmpwalk -v 2c -c Public 172.25.116.6 .1.3.6.1.2.1.2.2.1.8
iso.3.6.1.2.1.2.2.1.8.1 = INTEGER: 1
iso.3.6.1.2.1.2.2.1.8.2 = INTEGER: 1
[mpenning#Hotcoffee ~]$
Thus we know from the example that both interface "Fa0/0" (index: 1) and "Nu0" (index: 2) have an ifOperStatus of "up"; the index value is the last integer returned in the OID of the results.
Scripting
I assume you will use bash for your monitoring scripts; if so, check out Net-SNMP for your SNMP manager

Perl: how to portably reserve a TCP port (so there will be a non-available URL)

I'm the maintainer of the XML-LibXSLT module and one of the tests needs to access a non-existing URL. Problem was that someone reported that on their system the URL existed, so I decided to allocate a random port on localhost where I'm sure there will be no web-service. It was done like that:
# We reserve a random port to make sure the localhost address is not
# valid. See:
#
# https://rt.cpan.org/Ticket/Display.html?id=52422
my $sock = IO::Socket::INET->new(
Proto => 'tcp',
);
my $port = $sock->sockport();
$file = "http://localhost:${port}/allow.xml";
Now, the problem is that $port is defined and valid (to the value of a reserved port) on Linux, but it does not appear to work on Windows - see this bug report - https://rt.cpan.org/Ticket/Display.html?id=71456 . My question is: how can I reserve a new, random, not-yet-occupied port portably across UNIXes, Mac OS X and Windows in Perl 5?
Regards,
Shlomi Fish
You should be able to bind to the loopback address using port 0 (so that a port will be allocated to you). For bonus points you may want to try to connect the socket to itself (probably not needed anywhere, but should guarantee that it has an address)
You want to bind the socket to an address+port. This which will happen if you specify a LocalAddr (or LocalHost). If you don't specify a port (or you specify port zero), a free port will be picked for you.
use strict;
use warnings;
use 5.010;
use IO::Socket::INET qw( INADDR_ANY );
my $sock = IO::Socket::INET->new(
Proto => 'tcp',
LocalAddr => INADDR_ANY,
);
my $port = $sock->sockport();
say $port; # 60110
I think you want to only accept connections from the loopback adapter. If so, use INADDR_LOOPBACK instead of INADDR_ANY.
Try this small tool https://github.com/yegor256/random-tcp-port (I'm a developer). Should work in Windows, since it's ANSI C.
I suspect (but cannot prove from here) that on Windows the port number is not actually allocated until such time as the socket actually starts listening.
However having that socket actually listen will prevent the test from failing as rapidly as it might since the initial TCP connection would actually succeed.
Have you considered just pointing the URL at test.example.com instead, which is guaranteed not to exist?

Find internal IP address with BASH

I am already aware of many ways of getting your internal IP (ifconfig, ip addr, /etc/hosts, etc), but I am trying to write a bash script that will always return the internal IP. The problem is, many one-liners (/sbin/ifconfig|grep inet|head -1|sed 's/\:/ /'|awk '{print $3}') can return multiple IPs, and I need to distinguish the internal one manually.
I suspect that to the computer, there is no difference between and an external IP and an internal IP, and thus no 100%, guaranteed way to get the right IP.
The end result is that this script will return the internal IP, no matter if its a 192 address or a 204 address, etc.
Thanks in advance.
"hostname -i" should hopefully give you the same result
As others have mentioned, a machine is not really guaranteed, or even likely, to have a single IP address. I'm not sure exactly what you mean by "internal IP"; sometimes this can mean "IP address on the local network", i.e. the interface which connects to a NAT-enabled firewall.
I'm thinking that the best way to do this is to connect to a host on the network you want and use the address from which that connection originates. This will be the interface which the machine normally uses to connect to that network. The user Unkwntech had the same idea on this thread. The code below is just taken from that answer.
I don't know if this really qualifies as a "bash" solution, since it's just an inline Python script, but anyway this will get you the local ip address used to reach google.com. So this will give you the IP address of whichever interface the machine uses to reach Internet hosts.
$ python -c 'import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("google.com", 80))
print s.getsockname()[0]'
A more bash-y solution might use tracepath or some similar utility.
Systems can have multiple private IPs too though. You would have to limit your searching on IPs to private IPs. 10.0.0.0/8, 172.16.0.0/12, and 192.168.0.0/16.
Within the RFC 1918 private address spaces, a machine could conceivably have every address in the 10/8 range, the 172.16/12 range, and the 192.168/16 range, for a total of 17891328 IP addresses, and all of them would be legal "internal" IPs.
Oh yes, don't forget IPv6 :) 2^64 possible addresses per network for a single machine, which might participate in multiple networks.
This isn't exactly academic, either: it is quite common for VMWare, VirtualBox, QEMU, etc. host systems to have multiple RFC 1918 addresses assigned; one for the 'usual use', and one that is used specifically to communicate with guest operating systems. Or routers / firewalls, they might have a dozen internal IPs specifically to subnet a network for access control reasons.

Resources