check the dns record for a hostname with nslookup - linux

I have a host list hostfile that i'm doing name lookup just to know if the host has records in DNS or not with the help of Linux native tool nslookup.
Below is what i'm doing and its working, however there is a situation when nslookup don't find anything thus the result is nothing in that case i want to fill "no dns record"
What i'm trying:
$ for i in `cat hostfile`;
> do
> echo $i $result
> result=$(nslookup $i | awk 'FNR==6{print $2}')
> done
OR
for i in `cat hostfile`;
do
printf "$i: %s\\n" $(nslookup $i | awk 'FNR==6{print $2}');
done
Its not giving correct output if there is no nslookup found.
Desired:
myhosts01 192.168.1.1
myhosts02 192.168.1.2
myhosts03 192.168.1.3
myhosts04 192.168.1.4
myhosts03 no dns record
myhosts04 no dns record

You can either use a full if statement to check whether the result is blank (-z for zero-length):
if [[ -z "$result" ]]; then
result="no dns record"
fi
echo "$i $result"
Or use a default value when expanding the variable:
echo "$i ${result:-no dns record}"
In either case, I'd recommend using a while read loop to read the file instead of for (assuming there's one hostname per line), using dig +short instead trying to parse nslookup, doing the lookup before printing the result, and double-quoting all variable references (and probably using more descriptive variable names). Something like this:
while read -r hostname; do
hostIP=$(dig +short "$hostname")
echo "$hostname ${hostIP:-no dns record}"
done <hostfile

Related

Linux/Unix check if VPN connection is Active/Up

I have a code which detects if OpenVPN connection is up or down:
if echo 'ifconfig tun0' | grep -q "00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00"
then
echo "VPN up"
else
echo "VPN down"
fi
exit 0
now I'm trying to re-write the code to work with PPTP or IPSEC connection. I've tried to do:
if echo 'ifconfig ppp0' | grep -q "00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00"
or the same with ipsec but does not work. Is there any other way to detect PPTP or IPSEC connection?
That echo statement is erroneous. As #unwind says, the single quotes (') should be backtics (`). Your current code is sending the literal value ifconfig ppp0 to grep, which doesn't do anything useful.
But you don't actually need the backtics, either. You can just send the output of ifconfig to grep directory; using echo doesn't get you anything:
if ifconfig ppp0 | grep -q "00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00"; then
echo ppp connection is up
fi
The following script will:
Run the ISPConnectivity.sh script every 5 minutes. This will mean that the VPN tunnel will not be down for more than 5 minutes.
Check if the tun interface is down, and start the vpn script if it is.
Check connectivity if the tun0 interface is up. It does ping tests on 2 Public IPs (if I get even a single response from 1 of the IPs tested, I consider this a success ), and all have to fail to run the vpn script. I ran ping tests on multiple hosts to prevent the vpn script from starting in case the ping test failed on 1 IP.
Send all failure output to a file in my home directory. I do not need to see if any test succeeded.
Contents of sudo crontab:
*/5 * * * * /home/userXXX/ISPConnectivity.sh >> /home/userXXX/ISPConnectivity.log 2>&1
Contents of ISPConnectivity.sh script:
#!/bin/bash
# add ip / hostname separated by white space
#HOSTS="1.2.3.4"
HOSTS="8.8.8.8 4.2.2.4"
# no ping request
totalcount=0
COUNT=4
DATE=`date +%Y-%m-%d:%H:%M:%S`
if ! /sbin/ifconfig tun0 | grep -q "00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00"
then
echo $DATE tun0 down
sudo /home/userXXX/startVPN.sh start
else
for myHost in $HOSTS;
do
count=`ping -c $COUNT $myHost | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }'`
totalcount=$(($totalcount + $count))
done
if [ $totalcount -eq 0 ]
then
echo $DATE $totalcount "fail"
sudo /home/userXXX/startVPN.sh start
#else
# echo $DATE $totalcount "pass"
fi
fi
You can also check with the nmcli command, to check if VPN is running or not.
nmcli c show --active | grep vpn
I'm actually looking into more flexible solution eg:
MyIP=$(curl http://api.ipify.org/?format=text)
if [ "$MyIP" != "MYORYGINALIP" ]
then
echo "IPSEC VPN is Running - " $MyIP
else
echo "IPSEC VPN is Not Running - " $MyIP
fi
exit 0
what about that? can I improve it any way?
ip route list table 220 if Ip address shown -> VPN connection established, none -> no VPN
or
if [ "0" == ifconfig | grep wlan0 | wc -l ]; then echo "NO wlan0 has no VPN"; else echo "YES wlan0 has VPN"; fi

Shell Script for Auto IP Change

I am newbie to Linux/Asterisk. I am trying to write a shell script that would look for my SIP trunk registration, if found UNREACHABLE then it would execute a command and check my local IP, if my local IP is 192.168.1.106 then it would change the IP to 192.168.1.150 and vice versa, after that issue the commands, network service restart and amportal restart.
I have written following so far, and just by the looks, it seems wrong. Any help would be highly appreciated. Thanks
#!/bin/bash
asteriskbin=`which asterisk`
interval=10
ippath=/sbin/ifconfig
ip1=192.168.1.106
ip2=192.168.1.150
trunk="siptrunk"
run=true
while [[ "$run" == "true" ]]; do
checktrunk=`$asteriskbin -rx “sip show peer $trunk” | grep Status | grep -wc OK`
if [[ $checktrunk == 0 ]]; then
echo “TEST Trunk Down”
else
echo “SIP trunk registration OK.”
whatip=`$ippath eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'
if [[ $whatip == $ip1 ]]; then
ifconfig eth0 $ip2
else
ifconfig eth0 $ip1
network service restart
amportal restart
fi
sleep $interval
done
exit 1
A few things which spring out:
You should be using " quotes.
The whatip= command substitution is not ended anywhere.
You should use $(cmd) instead of `cmd`
Use More Quotes!
$run and exit 1 are useless since $run is never set to anything other than true.
ifconfig is deprecated in favour of ip.
There's no point in saving which asterisk to a variable. Simply run asterisk; it will perform the exact same lookup.
Why are you doing this in the first place? I don't see how continually changing your IP is useful.

How to find a list of ip addresses in another file

I was given the task to see if we are advertising a list of ip addresses(3000). Not a good idea to do it manually, so I copied all the ip addresses that we are advertising in a file. Now I just have to create a bash script and feed the list of ip address into the script so it can find the ip addresses in the file with the list of ip addresses being advertised. If found save it in one file if not in a different file. This is what I have so far. The problem with this script is that I have to type in manually every ip address. HOW CAN I FEED THE FILE WITH THE LIST OF IP ADDRESSES TO BE SEARCHED IN THE FILE WITH THE LIST OF IP ADDRESSES WE ARE ADVERTISING. Thank you very much in advanced.
#!/bin/bash
while true; do
echo -e "IP address: \c"
read ip
if grep --color "$ip" "ips"; then
echo $ip "was found"
echo $ip >> found
else
echo $ip "was NOT found"
echo $ip >> notFound
fi
done
If you sort the two files, you can use the comm command:
sort all_ip_addresses > all_ip_addresses_sorted
sort adverted_ip_address > advertised_ip_address_unsorted
comm -23 all_ip_addresses_sorted advertised_ip_addresses_sorted
will show the IP addresses that are not advertised, and:
comm -12 all_ip_addresses_sorted advertised_ip_addresses_sorted
will show the advertised IP addresses.
You can also avoid creating the separate sorted files by using process substitution:
comm -23 <(sort all_ip_addresses) <(sort advertised_ip_addresses)
A better script :
while read ip
do
grep "$ip" "$ips" > /dev/null 2>&1 && echo "$ip" >> ip.found || echo "$ip" >> ip.notfound
done
Name the script "searchip.sh"
Assume your input file is "iplist" ,set up variable and call like this:
ips=ips
cat iplist | sh searchip.sh
or
sh searchip.sh < iplist
Then you get two files , one is ip found, other one is ip not found.
What you need is shell I/O redirection.
$ script < list_of_ip_addresses
That's all you need.

Linux bash script that pings multiple IP addresses from a file

I have a file containing multiple hosts and IPs in the format above:
alpha, 192.168.1.1
beta, 192.168.1.2
gamma, 192.168.1.3
I am trying to create a script that says something like:
"Pinging hostname alpha"
ping 192.168.1.1
and jump to the next ip in the list.
I don't want the entire script, just some suggestions.
Thanks,
Alex
If you add a comma to the input field separator, it'll help parse the lines:
IFS=$IFS,
while read name ip; do
echo -n "Pinging hostname $name..."
ping -c2 "$ip" &>/dev/null && echo success || echo fail
done < /tmp/hosts
I'd read in the lines with read. You'll probably also want to give ping an option telling it how many times to ping. The default on most Linux systems for example is to ping forever, which doesn't seem like it would work well in your situation.
You could use AWK:
$ awk '{print "Pinging hostname "$1; system("ping -c 3 "$2) }' ips
Pinging hostname alpha,
PING 192.168.1.1 (192.168.1.1) 56(84) bytes of data.
You can also remove that comma if is it important to you:
$ awk '{sub(/,/,"");print "Pinging hostname "$1; system("ping -c 3 "$2) }' ips
Pinging hostname alpha
PING 192.168.1.1 (192.168.1.1) 56(84) bytes of data.
I might be a bit late to the party, but how about fping? Use -f to read from a file (requires sudo), or pipe the file with < (as suggested on the man page). It won't tell you "pinging alpha", but it will quickly tell you whether or not you can get in touch with the hosts.
Script for hosting 100+ hosts in same scheme like 192.168.xx.xxx
#!/bin/bash
for i in `seq ${2} ${3}`
do
ping -c 1 ${1}.${i} > /dev/null 2>&1
if [ $? -eq 0 ]; then
echo "${1}.${i} responded."
else
echo "${1}.${i} did not respond."
fi
done
command to ping the host
bash test.sh 192.168.1 0 100
Try this
#!/bin/bash
IPLIST="path_to_the_Ip_list_file"
for ip in $(cat $IPLIST)
do
ping $ip -c 1 -t 1 &> /dev/null
if [ $? -ne 0 ]; then
echo $ip ping faild;
else
echo $ip ping passed;
fi
done

Bash Loops: How to execute once, then move to the next iteration

I've never actually had an instance where this was required, but here I am...
What I've (unfortunately) got is an output of netstat -nr (almost 6000 individual static routes).
I need to take that file, and eventually translate each line into a new 'ip route add' command once I've got this working.
Here's my failcode (echos at the bottom are for testing -> I'd want to substitute them for ip route add once this works):
num=`cat $logfile | wc -l`
echo $num
echo " "
for ((i=0; i<=$num; i++))
do
dst=$(awk '{print$1}' $logfile)
gw=$(awk '{print$2}' $logfile)
mask=$(awk '{print$3}' $logfile)
echo $dst
echo $gw
echo $mask
echo " "
done
The output, instead of looking like:
Destination Gateway Netmask
looks like:
Destination Destination Destination Destination
Gateway Gateway Gateway Gateway
Netmask Netmask Netmask Netmask
How do I make it so that each time it runs, each output is a single DST/GW/netmask that I can feed into a command?
Thanks!
Your loops are inside out. Your awk commands process the whole file each time and they're done.
If you need the values in variables replace almost all of your script with this:
#!/bin/bash
while read -r dst gw mask _
do
echo "$dst $gw $mask" # substitute your command here
done < "$logfile"
The answer lies in AWK:
awk '{print "echo",$1,$2,$3}' $logfile | sh -x
Now replace echo with whatever command you need to run

Resources