Template MySQL didn't get result in Zabbix - mysql

I'm planning to use Temple MySQL
to monitor MySQL detail instances. Unfortunatelly I can't get result. What am I still missing in configuration. Check it out zabbix-agent log those are piece of log not the whole log.
XECUTE_STR() command:'/usr/lib/zabbix/externalscripts/mysql_check.pl' len:0 cmd_result:''
28786:20160121:141008.072 Sending back []
28786:20160121:141008.072 listener #2 [waiting for connection]
28788:20160121:141008.648 In send_buffer() host:'127.0.0.1' port:10051 values:0/100
28788:20160121:141008.648 End of send_buffer():SUCCEED
28788:20160121:141008.648 active checks #1 [idle 1 sec]
28784:20160121:141008.795 collector [processing data]
28784:20160121:141008.796 In update_cpustats()
28784:20160121:141008.796 End of update_cpustats()
28784:20160121:141008.796 collector [idle 1 sec]
28785:20160121:141009.075 listener #1 [processing request]
28785:20160121:141009.075 Requested [mysql[root,Qwestions,lld]]

1. Add special user for MySQL:
example:
GRANT USAGE ON *.* TO 'zabbix'#'%' IDENTIFIED BY 'superpassword';
FLUSH PRIVILEGES;
2. Add user params into zabbix-agent configuration
Edit /etc/zabbix/zabbix_agentd.conf
UserParameter=mysql.version,mysql -V
UserParameter=mysql.status[*],echo "show global status where Variable_name='$1';" | HOME=/etc/zabbix mysql -N | awk '{print $$2}'
UserParameter=mysql.ping,HOME=/etc/zabbix mysqladmin ping | grep -c alive
# 'sum' on data_length or index_length alone needed when we are getting this information for whole database instead of a single table
UserParameter=mysql.size[*],echo "select sum($(case "$3" in both|"") echo "data_length+index_length";; data|index) echo "$3_length";; free) echo "data_free";; esac)) from information_schema.tables$([[ "$1" = "all" || ! "$1" ]] || echo " where table_schema='$1'")$([[ "$2" = "all" || ! "$2" ]] || echo "and table_name='$2'");" | HOME=/etc/zabbix mysql -N
if you want to extend monitoring items just add another UserParameter with proper SQL-query
3. Add auth-file for MySQL:
create .my.cnf file into /etc/zabbix/
[client]
user = zabbix
password = superpassword
4. Restart agent (and zabbix-proxy if you use it)

Log is useless. We see only script returns no result and can't see why.
Try to connect to MySQL from console using credentials that you provided in mysql_check.pl file. Be sure that user have enough permissions (SUPER at last).
mysql -hhostname -uuser -ppassword
Run script from user zabbix and check result:
perl ./mysql_check.pl

Related

Bash mysql error handling locked tables

i have a shell script that is called with a few parameters very frequently. it is supposed to build a query and execute the statement. in case an error occures, it should write the arguments seperated into a file so the error-handling can take place by calling that script again.
everything works but
the problem is, i catch connection refused error etc but if the statement cannot be executed because the table is locked and i do not want to wait for the timeout.
my code:
...
mysql -u ${username} -p${password} -h ${database} -P ${port} --connect-timeout=1 --skip-reconnect -e "$NQUERY"
mysqlstatus=$?
if [ $mysqlstatus -ne 0 ]; then
echo "[ERROR:QUERY COULD NOT BE EXECUTED:$mysqlstatus: QUERY WRITTEN TO LOG]" >> ${GENLOG}
#echo ${NQUERY} >> ${FQUER}
for i in "$#"; do
ARGS="$ARGS $i|"
done
echo "${ARGS}" >> ${ARGLOG}
else
echo "[OK] $NQUERY" >> ${GENLOG}
fi
...
but when a table is locked, the executing is not canceled and it runs like forever..
its not a solution for me to set the Max_statement_time_set or anything on the mysql server, since im not the only one using the db
You can use the timeout command along with mysql
timeout 3 mysql -u ...
This will wait 3 seconds for the mysql command to return, if the command runs longer then 3 seconds timeout will return exit status 124 to the shell. If you don't have timeout you can use job control with something like this.
#background the process
mysql -u ... &
#get pid of background process
bg_pid=$!
sleep 3
#check if your pid is still running
#using string matching incase pid was re assigned
if [[ $(ps -p $bg_pid -o args --no-headers) =~ "mysql" ]]
then
echo "running to long"
else
echo "OK"
fi

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

Subshell MySQL-query in bash

I'm trying to set variable in the cycle in Ubuntu bash, which is getting recordset from database, but this variable is setting to its previous value.
Here is a code:
#!/bin/bash
PREV_FILE_PATH="127"
while true
do
echo "$PREV_FILE_PATH"
mysql -h$DB_HOST -u $DB_USER -p$DB_PASS $DB_NAME --skip-column-names --default-character-set=UTF8 -e "here is a query" | while read "here is getting variables from recordset";
do
PREV_FILE_PATH="777"
done
done
And this code prints every time:
127
127
127
But whe I replaced this block-:
mysql -h$DB_HOST -u $DB_USER -p$DB_PASS $DB_NAME --skip-column-names --default-character-set=UTF8 -e "here is a query" | while read "here is getting variables from recordset";
with just while true and break at the end of cycle it works fine and prints:
127
777
777
777
Script creates some subshell and running that MySQL query in that subshell. So what should I do to make script change that variable?
As you noted the issue is due to the creation of a subshell which is being caused by piping the output of the mysql command to the while loop. A simple example:
PREV_FILE_PATH=127
echo test | while read _; do
PREV_FILE_PATH=777
done
echo $PREV_FILE_PATH
# output: 127
Since you're using BASH you can move the mysql command from being a pipe to a substituted process fed to the while loop via STDIN redirection. Using the previous simple example:
PREV_FILE_PATH=127
while read _; do
PREV_FILE_PATH=777
done < <(echo test)
echo $PREV_FILE_PATH
# output: 777
So to fix your code, you will want to move your mysql command in the same fashion that I moved the echo command above:
while read "here is getting variables from recordset"
do
PREV_FILE_PATH="777"
done < <(mysql -h$DB_HOST -u $DB_USER [..remaining options..])
Note that process substitution via <() is a BASH-ism and isn't POSIX compliant.

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