Linux Script & MySql operations not working, When Invoked from other script - mysql

I have written this piece of code to insert rows into table if not there, else, update the 'cnt' by one more. This works very well, when I invoke it from command line, when I invoke it from shell script, this does not work.
file=$1
echo "$0: Path to store $file" ;
res=`mysql -e "use spam_sending_scripts; select * from spamemailcount where path = '$file' limit 0,1"`
echo $res
if [ -z "$res" ]
then
mysql -e "use spam_sending_scripts; INSERT INTO spamemailcount (cnt,path) VALUES(1,'$file');"
echo "Inserting into DB $file , res $res" ;
exit ;
fi
mysql -e "use spam_sending_scripts; update spamemailcount SET cnt=cnt+1 where path = \"$file\"" ;
echo "Updating into DB $file" ;
#mysql -e "use spam_sending_scripts; select * from spamemailcount" >> /var/log/sendmail.log
mysql -e "use spam_sending_scripts; select * from spamemailcount"
root#server [/home]# insertintodb.sh AAA ==> This is working fine.
When I invoke from the other script, this file is executed, But Insert does not work.
I invoke it like: /home/insertintodb.sh $path
The $path variable is getting passed to insertintodb.sh correctly.
I am getting the following Error:
++ mysql -e 'use spam_sending_scripts; select * from spamemailcount where path = '\''hackerssquadron.com/wp-comments-post.php'\'' limit 0,1'
ERROR 1045 (28000): Access denied for user 'root'#'localhost' (using password: NO)

Use chmod command to make it executable
chmod ugo+x insertinodb.sh
Then try calling it same as #Jdamian suggested
bash -x /home/insertintodb.sh "$path"

This problem is solved.
When I try to invoke the script from the command line, It is working fine.
Reason => I am running this script as a root. So no problem
When I invoke the script using another shell script, It is not working.
Reason: This main script is being invoked by apache and It is trying to access the root DB, so permission denied.
Based on input from Skynet & Jdamian, I am able to debug it and resolve it.
Thank you very much for support, As usual this is one of the best place to get the technical queries resolved quickly by experts.

Related

Import SQL dumps trough bash script

I'm trying to import GZiped MySQL databases listed in a folder.
GZiped files are located at .mysqldumps/.
$NAME tries to extract database name (as files are always named database_name.sql.gz) and pass it to mysql command line.
Also, as username and database name are the same, the same argument is passed ($NAME).
As files are GZiped, we try to zcat them (so gunzip -c) before pipe them to mysql.
The full script is:
#!/bin/bash
FILES='.mysqldumps/*'
PASSWORD='MyPassword'
for f in $FILES
do
NAME=dbprefix_`basename $f .sql.gz`
echo "Processing $f"
set -x
zcat $f | mysql -u "$NAME" -p$PASSWORD "$NAME"
done
But, when i run the script it outputs:
./.mysqlimport
Processing .mysqldumps/first_database.sql.gz
+ mysql -u dbprefix_first_database -pMyPassword dbprefix_first_database
+ zcat .mysqldumps/first_database.sql.gz
ERROR 1044 (42000) at line 22: Access denied for user 'dbprefix_first_database'#'localhost' to database 'first_database'
As you can see, the selected database is 'first_database' instead of 'dbprefix_first_database' and this just trowns an error of corse, and i just can't understand why $NAME is not correctly parse as database name.
What i'm doing wrong?
After some investigation, the problem comes from the DUMP and not from the script.
While using mysqldump the option --databases was used which includes the USE 'dbname'; and when importing, that name was used instead of $NAME.
Problem solved!

MySQLSHOW Suppress Warning in Bash Script

I'm working on a simple bash script and one of the things it does is check whether a database already exists before moving on. It's simple enough code, but I'm getting a warning message whenever I try to run the script and I want to suppress that.
Here is the code:
if ! mysql -uroot -proot -e "use $NAME"; then
echo YES
else
echo NO
fi
So, as output, I get the following message when the if statement returns true:
ERROR 1049 (42000) at line 1: Unknown database 'database'
YES
How can I suppress that message? It doesn't stop the script from running, but I would prefer not to see it.
It simply tells you that the DB with the name database (which is apparently passed as a value of the $NAME variable) doesn't exist. Use the correct DB name and there'll be no warning.
To simply mute the warning redirect all the output to /dev/null as usual:
if ! mysql -uroot -proot -e "use $NAME" 2>&1 >/dev/null; then
echo YES
else
echo NO
fi

script for MySQL with user and password entered as a parameter

As another post (Script for MySQL backup to multiple files), I received help to create a Powershell script that creates backup of MySQL databases and generates multiple files, one for each database. As can be seen, the script makes a pipeline between a command mysql and mysqldump.
My intention now is to eliminate the user information and password directly in the script. As another link (How to perform a mysqldump without a password prompt?), I created the my.cnf configuration file MYSQL_HOME, passing the information on [mysqldump], and used the flag --defaults-extra-file. The problem is that this flag does not work for mysql.exe, so could not use this solution.
To avoid leaving the user and password information directly in the script, I used another post (How to handle command-line arguments in PowerShell), which shows how to configure parameters input into Powershell scripts. With that, my script looked like this:
param (
[string]$username = $(throw "-username is required."),
[string]$password = $(Read-Host "Input password, please" )
)
$BACKUPDATE = Get-Date -UFormat "%Y-%m-%d_%H%M%S"
$BKPFOLDER='E:\bkp'
$MYSQL_HOME="C:\MYSQL"
Set-Location "$MYSQL_HOME\bin"
& .\mysql.exe -N -s -r -u $username -p$password -e 'show databases' | % {
& .\mysqldump.exe -u $username -p$password --single-transaction $_ |
Out-File "$BKPFOLDER\${_}_$BACKUPDATE.sql" -Encoding Ascii
}
When I run the following command:
test.ps1 -username bkpuser -password mypass
I get the following message:
ERROR 1045 (28000): Access denied for user 'bkpuser'#'localhost' (using password: YES)
But there is no access permission problem, because if I replace the values โ€‹โ€‹of $usename and $password to call the mysql and mysqldump by correct values โ€‹โ€‹(excluding the parameter), the command works.
What should I change?
PowerShell's parser can't determine where commandline argument ends and vairable name starts. You can see this clearly in ISE, because $password should be red, but it's blue:
Just add space between -p and $password or use "=": --user=$username --password=$password

mysql connection terminates when i logoff from the remote server

I had written a script that connects to the local mysql server every 6 seconds and checks if there is any data in the table .if there is data it runs some php commands and then deletes that data from the table. I logged into my remote server(Shared hosting) through ssh and then copied the script and executed it using command "nohup ./script.sh 0<&- &>alert.log &" so that it runs in background and writes all the output to alert.log file. my problem is that when i log in to the server through SSH and execute the script it runs perfectly , but when i log out from server its not running . when i check the alert.log file after it is showing error "cannot connect to local mysql server". any solutions ??
this is the code
while true
do
res=($(mysql -u root -p123456 --skip-column-names -Dtest -e "select id from temptab"))
if [[ "$res" > 0 ]];then
del=`mysql -u root -p123456 -Dtest -e "delete from temptab;" `
now="$(date +'%d/%m/%Y:%H.%M.%S')"
for ((i=0; i < ${#res[#]}; i++))
do
php -n /var/lib/mysql/trigger.php ${res[$i]}
echo "[$now]:Trigger called with videoid ${res[$i]}"
done
fi
sleep 6
done
and this is the sample output
cat nohup.out
X-Powered-By: PHP/5.4.20
Content-type: text/html
{"multicast_id":8864856209398719411,"success":2,"failure":1,"canonical_ids":0,"results":[{"message_id":"0:1385797766832904%4f0c6467f9fd7ecd"},{"error":"InvalidRegistration"},{"message_id":"0:1385797766832901%4f0c6467f9fd7ecd"}]}81Inserted police info
[30/11/2013:00.49.26]:Trigger called with videoid 65
/etc/bashrc: line 14: whoami: command not found
/etc/bashrc: line 20: grep: command not found
/etc/bashrc: line 59: dircolors: command not found
./alert.sh: line 15: php: command not found
[30/11/2013:07.50.27]:Trigger called with videoid 70
./alert.sh: line 15: /ramdisk/php/54/bin/php54: No such file or directory
[30/11/2013:09.09.52]:Trigger called with videoid 71
screen is what you need. There are plenty of tutorials on google on screen usage.
I suggest to move your code into a crontab even that will run every X minutes (5 minutes, or anything else you like) rather than have your user run it during a live session.
Just place the PHP script inside a call to cron, login, and run crontab -e then add:
*/5 * * * * /home/username/phpscript.php
You could try to run your script like:
/path/to/script.sh </dev/null &>/home/yourname/alert.log &
disown
I
finally i got the solution .... i was using /usr/bin/php to call my php files but .....when i edited it to /usr/bin/php.orig it started working........... but what is that php.orig...?? #all thanks

How can I check the mysql connection for a user/password using batch/shell script

How can I check the mysql connection for a user/password using batch/shell script?
I've user name and password, and I need to authenticate whether they are correct or not, but how?
I tried this way:
I've created a batch file "run.bat" with "mysql -u User--password=UserPassword < commands.sql"
"commands.sql" file contains "\q"
When I run the file "run.bat" the output is nothing when User/Password are correct and "ERROR 1045 (28000): Access denied for user ... " when User/Password are incorrect. Now can we capture this output, and decide whether the connection is successful or not, if yes how?
Regards
I found a solution as below:
#echo OFF
echo \q | mysql -u User --password=UserPassword 2>nul
if "%ERRORLEVEL%" == "0" (
echo CONNECTION SUCCESSFUL
) else (
echo CONNECTION FAILED
)
You can check the return status of mysql. It is stored in the ERRORLEVEL enviroment variable:
mysql -u User--password=UserPassword < commands.sql
if "%ERRORLEVEL%" EQU "0" (
echo OK
) else (
echo FAIL
)
If you are lucky, mysql.exe even returns a specific status for "logon failed" that you can react on. Most applications return 0 on success and something != 0 on failure. Use echo %ERRORLEVEL% right after a command to find out the current value.
A more advanced approach would be to capture and evaluate the STDERR stream of the application. This, however, would be material for a different question.
you could use a ".my.cnf" file
I do this, although id strongly recommend against using your mysql root login
[root#daaorc900c ~]# cat ./.my.cnf
[client]
user=monitoruser
password=whatismonitor
[root#daaorc900c ~]#
Looks like you might be one windows so here is the doc for the "options files" in widnows
http://dev.mysql.com/doc/refman/5.1/en/option-files.html