I have to send few gzipped files from local server to SFTP server.
My Server Info
Distributor ID: Ubuntu Description: Ubuntu 12.04.4 LTS Release: 12.04 Codename: precise
Created a bash script and could able to send files to sftp, but i want to send email if transfer is successful.
#!/bin/bash
HOST=hostname.domain
PORT=22
USER=username
PASSWORD=password
SOURCE_FILE=path/filename
TARGET_DIR=PATH
/usr/bin/expect<<EOD
spawn /usr/bin/sftp -o Port=$PORT $USER@$HOST
expect "password:"
send "$PASSWORD\r"
expect "sftp>"
send "put $SOURCE_FILE $TARGET_DIR\r"
expect "sftp>"
send "bye\r"
EOD
Now i want if the above transfer is successfull send Success Email if not Failure email with error message.
Please help!!
Thanks.
You could pipe error info from your script to a file and grep for an error with a second script. The second script could even run the first and might look something like this:
/path/firstscript.sh 2>&1 > results.txt
if [ -n "$(grep 'error expected' results.txt)" ]
then
echo "Found error" | mail -S "Error" [email protected]
else
echo "No error" | mail -s "Okay" [email protected]
fi
Personally, I find it better to check for the file on the target site by doing a second connection and listing the output there. Then I check that second connection log for the existence of the uploaded file.
I can't use rsync or key authentication with three different companies I script file transfers for, so I have some sympathy for people who get the answer "don't do that" when they ask a question. It's worse when you're searching for the answer because you already know that what people are recommending instead won't work.
Here's examples more closely based on what I actually do:
email_result.bash
#!/bin/bash
./uploadfile_example.bash 2>&1 > log.txt
if [ -n "$(grep "$(date +%b' '%d)" log.txt|grep "testfile")" ]
then
echo "File uploaded" |mail -s "Test success" [email protected]
else
echo "File not uploaded" |mail -s "Test fail" [email protected]
fi
uploadfile_example.bash
#!/bin/bash
datestamp=$(date +%s)
/bin/cp -v testfile.txt testfile.${datestamp}.txt
HOST="localhost"
USER="testuser"
PASS="YourPasswordHere"
expect -c "
spawn sftp ${USER}@${HOST}
expect \"password: \"
send \"${PASS}\r\"
expect \"sftp>\"
send \"put testfile.${datestamp}.txt\r\"
expect \"sftp>\"
send \"ls -l testfile.${datestamp}.txt\r\"
expect \"sftp>\"
send \"bye\r\"
expect \"#\"
"
/bin/rm -vf testfile.${datestamp}.txt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With