Changing IP log with GPS information and mail. I need robustness - bash

I've created a script in order to receive a mail with wan ip information and GPS location of my macbookpro. The content of the script is this:
#!/bin/bash
# -*- ENCODING: UTF-8 -*-
if [ ! -e /tmp/ip ]; then
curl -s icanhazip.com > /tmp/ip
fi
curl -s icanhazip.com > /tmp/ip2
newip=$(diff /tmp/ip /tmp/ip2 | wc -l)
if [ $newip -ne 0 ]; then
mv -f /tmp/ip2 /tmp/ip
date > IPlog.txt
curl -s icanhazip.com >> IPlog.txt
sudo ./Downloads/whereami >> IPlog.txt
mailx mymailadress#mail.com < IPlog.txt
rm IPlog.txt
else
rm /tmp/ip2
fi
Every minute the sistem executes this script that verifies if the wan ip has changed. If it has changed, the script send me a mail with the new information. The problems are:
1.- The mail is not always correctly sent. Sometimes I don't reveive it.
2.- The mail isn't contain all the info. Sometimes it includes only the new wan ip adress.
3.- Sometimes the mail is qualified as spam and I don't know why because the sender is always the same adress.

I have some suggestions to debug your problems.
First you should use a different location to store the ip than tmp. If your system wipes your tmp folder on boot and your system gets a new WAN ip after boot you would loose the previous recorded ip.
Check the exit code of mailx when sending using $?. 0 is ok. You could do a while loop and keep trying to send it until you get exit code 0.
You could add the info for the mail to a local variable instead of a file.
IPLog=`date`
IPLog+=`curl -s icanhazip.com`
The spam problem might be due to the IP address in the mail. Or whatever ./Downloads/whereami is adding to the file. Adding the sending email address as a trusted sender might do it.
Check the email header for information about spam score.

Related

Bash script with sendmail delivers email when executed manually but not from crontab

I wrote the following bash script to send me an alert if there is a problem with my website:
#!/bin/bash
# 1. download the page
BASE_URL="https://www.example.com/ja"
JS_URL="https://www.example.com/"
# # 2. search the page for the following URL: /sites/default/files/google_tag/google_tag.script.js?[FIVE-CHARACTER STRING WITH LETTERS AND NUMBERS]
curl -k -L ${BASE_URL} 2>/dev/null | grep -Eo "/sites/default/files/google_tag/google_tag.script.js?[^<]+" | while read line
do
# 3. download the js file
if curl -k -L ${JS_URL}/$line | grep gtm_preview >/dev/null 2>&1; then
# 4. check if this js file has the text "gtm_preview" or not; if it does, send an email
# echo "Error: gtm_preview found"
sendmail error-ec2#example.com < email-gtm-live.txt
else
echo "No gtm_preview tag found."
fi
done
I am running this from an Amazon EC2 Ubuntu instance. When I execute the script manually like ./script.sh, I receive an email in my webmail inbox for example.com.
However, when I configure this script to run via crontab, the mail does not get sent via the Internet; instead, it gets sent to /var/mail on the EC2 instance.
I don't understand why this is happening or what I can do to fix it. Why does sendmail behave different if it is being run from bash vs being run from crontab?
Be aware that the PATH environment variable is different for crontab executions than it is for your typical interactive sessions. Also, not all of the same environment variables are set. Consider specifying the full path for the sendmail executable ( which you can learn by issuing the 'which sendmail' command ).

Bash Auto Login Captive portal

#!/bin/bash
if ping -q -c 1 -W 1 8.8.8.8 >/dev/null; then
echo "The network is up"
else
echo "The network is down"
# Starting Login
wget "nonhttpssite.com" --no-check-certificate --keep-session-cookies --no-cache --timeout 30 -O - 2>/dev/null
fi
I try this code but still can't automatic after internet disconnect, using crontab execute every minute
im still confuse on wget line, login page is http://landing6.wifi.id/ but still adding other unique url example : http://landing6.wifi.id/landing/?NG94RktRQ3drZ05SbEZqOW5yenZ1ZmtrUU8xQnRLcnorSmtVNnJhQWFpL1RMRkErVDRjd3U5Q0tJRGFwa05leDBCZ0g5VWExZlRUOFBQNXVkY0E1dUFzcVkzbWxHM0lQd2JKZVJua3NkaU5lRCtwcUhPZHI2V2kyN3JaNExSKzhQVnNYN1RTMXNyT1VUZENVeU5zMG9pcjlEdHRUa0o2T3Rab0FhZERoajhYWTFVc2RtWG9CRzJWSnYzOWhOa0h6VktqNnJKL0pSbWVlTS9NK1FabW5Wdz09
since my mac already bypassed so i only need to open non https site to forwarded landing page, so no need to post data user/password
I will run this script on openwrt
Animate Browsing

getting multiple issues while creating a script to update hostnames in /etc/hosts file?

We've around 3000 VMs & 450 Physical servers which are Linux based servers (few of then ubuntu starting from 9.x & few of them are Susu starting 8.X & majority of them are RHEL starting from 4.x till 7.4) on all of them I need to add few hostname entries with IP details into their respective /etc/hosts files.
I've different users on each server with full sudoers access which I can use
Hence I've created a CSV file with hostname, username & password format. which contains required details to log in. Filename is "hostname_logins.csv"
I need to upload a file (i.e. hostname_list to each of these servers and then update those same details in each of the servers host files.
I'll be running this script using one RHEL 6 server. (All of the other hosts are resolvable from this server & are reachable, I've confirmed it already.)
The script is working but it's asking for accepting the host key once and also asked for the password 2 times however the 3rd time it does not asked for a password it worked automatically I guess, but need to ensure it does not askes to accept the host key or passwords.:
#!/bin/bash
runing_ssh()
{
while read hostname_login user_name user_password
do ssh -vveS -ttq rishee:rishee#192.168.1.105 "sudo -S -ttq < ./.pwtmp cp -p /etc/hosts /etc/hosts.$(date +%Y-%m-%d_%H:%M:%S).bkp && sudo -S bash -c 'cat ./hostname_list >> /etc/hosts' && rm -f ./.pwtmp ./hostname_list"
done < hostname_logins.csv
}
while read hostname_login user_name user_password
do echo $user_password > ./.pwtmp
cat ./.pwtmp
scp -p ./.pwtmp ./hostname_list $user_name#$hostname_login:
runing_ssh
done < hostname_logins.csv
I need to make this as a single script which will work on all these servers. thanks in advance.
You are executing the original copy from /tmp with sudo, but nothing else.
while read hostname_login user_name user_password
do echo $myPW >.pwtmp
scp -p ./.pwtmp ./hostname_list $user_name:$user_password#$hostname_login:
ssh -etS $user_name:$user_password#$hostname_login "sudo -S <.pwtmp cp -p /etc/hosts /etc/hosts.bkp && sudo -S <.pwtmp cat ./hostname_list >> /etc/hosts && rm -f ./.pwtmp ./hostname_list"
done < hostname_logins.csv
I dropped the explicit send to /tmp and the cp back to your home dir, and defaulted the location (to $user_name's home dir) by not passing anything to scp after the colon. Fix that if it doesn't work for you.
I created a password file for improved security and code reuse, and sent it along with the hosts list. I added a sudo -S to each relevant command, reading from the password file.
That [bash -c ...] syntax doesn't work on my implementation, so I took it out.
Hope that helps.
Update
Added -t to ssh call. Try that.

How to get SFTP login alert (email or SMS) on ubuntu?

I want to get Email or/and SMS alert whenever someone logs into my server. I have successfully done this for SSH login by editing .bashrc file.
But this method doesn't work for SFTP login.
I know I can do this by extracting information from log files, but i want a more efficient way (Since users can delete from log file).
I have also tried this, but it doesn't work.(I'm using ubuntu 12.04).
Basically, I want to execute a curl command (SMS API) on successful login.
Please help, thank you.
First, make sure you have the sendmail package (sudo apt-get install sendmail).
You can create or edit the file /etc/ssh/sshrc and give it the following code to achieve this:
ip=`echo $SSH_CONNECTION | cut -d " " -f 1`
logger -t ssh-wrapper $USER login from $ip echo "User $USER logged in from $ip" | sendemail -q -u "Email Title" -f "Sender <from#server.com>" -t "Your Name <you#email.com>" -s smtp.server.com &
Fill the appropriate variables (sender and recipient names and addresses) into this code.

Automatically Wake NAS on Access

I'm trying to get my NAS server to wake from an S3 sleep state when the NAS is accessed by a user. I want to do this to increase the longevity of the server, and also to limit its power usage. I've seen people asking for similar advice but none that I found provide a robust solution, most threads just ended unanswered.
So to just detail my problem quickly:
At my home I have a custom built, from an old PC, NAS server, running Ubuntu server, which stores media and documents mainly. This server is currently set to sleep after a predefined inactive period. Currently the NAS can be brought out of the S3 state with a WOL magic packet. What I would like to achieve is that this magic packet is automatically sent to the server when a user accesses one of the shares from their PC. The users are primarily running windows 7. I'm not sure if this is entirely prevalent but I have a Linksys WRT54G running DD-WRT as my home router/DHCP/DNS.
During my research I came across many articles which just automatically woke the server on a timed loop, no real intelligence. The article given below seems to do what I want:
http://wdtvhd.com/index.php?showtopic=7908
A script is given which attempts to address this problem by using the DD-WRT router to send the wake-on-lan packets when a query is made. This seems like a good way to go about this, however I could not get the script given in the link to operate correctly.
I think that covers most aspects of my problem. Any assistance will be greatly appreciated.
Just thought I would post my eventual solution to the above mentioned problem. To solve the problem I wrote a custom script which runs on my dd-wrt router on a timed cron job. When this script runs it access the file
\proc\net\arp
Within in that file is stored a record of all currently leased IP address and the corresponding mac addresses. Thus my script compared the mac addresses stored within that file to a predefined list of mac address of PCs on my home network. The list is comprised only of the PCs I would like to be able to access the NAS server. If one of the PCs is found to have an active lease the router then sends the wake-on-lan magic packet. Which then wakes the server. At that point I thought I had achieved my goal, as the server switched on with any of the PCs on the network, and the wait was not too long. However, after completing this I found that my timed sleep for the server would initiate every 30 min or so and sleep the server only to be woken again a couples of seconds later.
So to solve that issue I just added another condition to my conditional statement that would sleep the server if none of the required PC had an active lease. To do this I used SSH and the built in dropbear ssh functionality of DD-WRT to sleep the server. Below is the script
#!/bin/ash
NAS="MA:CA:DD:RE:SS:00"
PC="MA:CA:DD:RE:SS:00"
varP='grep -o $PC /proc/net/arp'
while true
do
echo 'Entered Loop'
if ping -c 1 IPADDRESSOFNAS > /dev/null; then
echo 'NAS is Already ON'
if [[ "$varP" != "MA:CA:DD:RE:SS:00" ]]; then
echo 'All Hosts Offline'
echo IPADDRESSOFNAS ssh-rsa NASPUPLICKEY
#HOME=/temp/root/
DROPBEAR_PASSWORD='NASPASSWORD' ssh root#IPADDRESSOFNAS pm-suspend &
fi
exit
fi
if [[ "$varP" == "MA:CA:DD:RE:SS:00" ]]; then
echo 'waking from lan'
/usr/sbin/wol -i BROADCASTADDRESSOFNETORK -p 9 MA:CA:DD:RE:SS:00
/usr/sbin/wol -i BROADCASTADDRESSOFNETORK -p 9 MA:CA:DD:RE:SS:00
exit
fi
exit
done
DISCLAMER: The code is supplied as is. I am aware it is not pretty nor the best solution possible. But it works for me and thats all I really need.
Hope someone finds this useful!
I insprected my NAS from WD and I can tell you that they uses memory drives for the /tmp, /var directories.
So are every logs written to the memory and the harddrive has not to be online. Hope that helps you a bit.
If someone want to access the harddrive the system will automatically upspinn your harddrive. So you will get what you want except that the system is always online.
I made some changes to the script by #Rabid to add support for multiple PCs.
It also checks whether the entries found in ARP have their flag set to 0x2 ( =~ active ), as, for me, the ARP entries would remain listed for too long after the PC had gone offline.
#!/bin/bash
# This script is made to be run on an DD- / Open-WRT device to automatically wake a NAS
# server if client PCs are online
# Settings
# Addresses of NAS that gets woken / put to sleep
MACofNAS="MA:CA:DD:RE:SS:00"
IPofNAS="192.168.2.1"
BroadcastAddress="192.168.2.255"
WOLPort=9
# Location of SSH Private Key on WRT (if used for login)
SSHPrivateKeyFile=~/.ssh/id_rsa
# MAC addresses of PCs of which the online status will be checked
PCs=(
"MA:CA:DD:RE:SS:00" # PC1
"MA:CA:DD:RE:SS:00" # PC2
"MA:CA:DD:RE:SS:00" # PC3
"MA:CA:DD:RE:SS:00" # PC4
)
# Determine if any PCs are on
SomePCisON=false
for index in ${!PCs[#]}; do
# Try to detect PC's MAC address in ARP
## Look for all entries in ARP ...
# PCFound=$(grep -o "${PCs[index]}" /proc/net/arp)
# ... OR look only for entries with flag set to 0x2 ( ~ active )
PCFound=$(grep "0x2" /proc/net/arp | grep -o "${PCs[index]}")
# If MAC address is found, the PC must be ON
if [[ ${PCFound} ]]; then
echo "PC ${PCs[index]} is ON"
SomePCisON=true
else
echo "PC ${PCs[index]} is OFF"
fi
done
if [[ "$SomePCisON" == true ]]; then
echo "Some PCs are turned ON"
else
echo "All PCs are turned OFF"
fi
# Check if NAS is ON
if ping -c 1 $IPofNAS > /dev/null; then
echo 'NAS is ON'
NASisON=true
else
echo 'NAS is OFF'
NASisON=false
fi
# If NAS is ON, but all PCs are OFF, put NAS to Sleep
if [[ "$NASisON" == true ]]; then
# If no PCs are ON, put NAS to sleep
if [[ "$SomePCisON" == false ]]; then
echo 'All Hosts Offline'
echo 'Suspending NAS'
# Log in with password (as in #Rabid's script, didn't work for me) ...
DROPBEAR_PASSWORD='NASPASSWORD' ssh root#IPADDRESSOFNAS pm-suspend &
## ... OR log in with authentication key
# ssh -i $SSHPrivateKeyFile root#$IPADDRESSOFNAS pm-suspend &
fi
# If NAS is OFF and any PCs are ON, wake NAS
elif [[ "$SomePCisON" == true ]]; then
# Use wol package on DD-WRT ...
echo 'Waking NAS from LAN, Broadcasting to '$BroadcastAddress\
'on port '$WOLPort' for '$MACofNAS
/usr/sbin/wol -i $BroadcastAddress -p $WOLPort $MACofNAS
/usr/sbin/wol -i $BroadcastAddress -p $WOLPort $MACofNAS;
## ... OR use etherwake package on Open-WRT
## ( Install with: opkg update && opkg install etherwake )
# echo 'Waking NAS from LAN, '$MACofNAS
# /usr/bin/etherwake $MACofNAS
# /usr/bin/etherwake $MACofNAS
fi
To log in with an authentication key, make a key pair and place the public key in NAS:~/.ssh/authorized_keys:
On WRT (with Dropbear):
mkdir -p ~/.ssh
# Generate a private key and store it in ~/.ssh/id_rsa
dropbearkey -t rsa -f ~/.ssh/id_rsa
# Store the public key in ~/.ssh/id_rsa.pub
dropbearkey -t rsa -f ~/.ssh/id_rsa -y | grep ssh > ~/.ssh/id_rsa.pub
# Copy id_rsa.pub from WRT:~/.ssh/ to NAS:~/.ssh/
scp ~/.ssh/id_rsa.pub root#nas:~/.ssh/OpenWRT.pub
On NAS (with OpenSSH):
# Back up the authorized_keys
cp ~/.ssh/authorized_keys ~/.ssh/authorized_keys_Backup
# Add the new public key to authorized_keys
cat ~/.ssh/OpenWRT.pub >> ~/.ssh/authorized_keys

Resources