insert sql record by command line ssh - mysql

i try to execute this command line:
ssh root#ip "mysql -u login -ppassword zabbix -e
'INSERT INTO worldmap_latlng (lat,lng,name,value,timestamp)
VALUES (48.891198, 2.2465829, "'test'", 0, now())'"
but i have this response :
ERROR 1054 (42S22) at line 1: Unknown column 'test' in 'field list'
i try with ' and " but not work

you can do that using ssh and bash combo
write bash file on remote machine say insert.sh in ./ path location
#!/bin/bash
lat= echo $1
lng= echo $2
name= echo $3
value= echo $4
# echo $lat
# echo $lng
# echo $name
# echo $value
echo "insert into worldmap_latlng (lat,lng,name,value) values $lat , '$lng', '$name' , '$value' ;" #| mysql -ulogin -ppassword zabbix
exit
ssh root#ip sh ./insert.sh latval lngval nameval valueval
You can also write some python or other languages script that takes args and insert and execute that using ssh

Related

moving mysql values to variables into bash for loops

i have a table that i want to query to that and get some values from my bash script and use it in while loop,when i use one column it works as a champ but i cant use more than one i get error like:
read: `IP, PL_Seq': not a valid identifier
here is my SELECT result
and here is may bash script
sql="SELECT IP,PL_Seq FROM mytabel WHERE FLAG=0 AND CIDR =24";
i=0
while IFS=$'\t' read IP, PL_Seq ;do
IP[$i]=$IP
PL_Seq[$i]=$PL_Seq
((i++))
echo $IP
echo $PL_Seq
done < <(mysql TestDB -u $DB_USER --password=$DB_PASSWD -N -e "$sql")
You are nearly there, you just need to remove the comma from the line:
while IFS=$'\t' read IP, PL_Seq ;do
and so:
sql="SELECT IP FROM mytabel WHERE FLAG=0 AND CIDR =24";
i=0
while IFS=$'\t' read IP PL_Seq ;do
IP[$i]=$IP
PL_Seq[$i]=$PL_Seq
((i++))
echo $IP
done < <(mysql TestDB -u $DB_USER --password=$DB_PASSWD -N -e "$sql")

How do not remove leading zero from variable in a Bash MySQL query?

I am trying to query against the database to validate if a registry exists. I created I bash script to make that:
read -p "`echo $'\n '`-------------`echo $'\n '` Insert a CPF: `echo $'\n '`-------------`echo $'\n '`" CPF
USER_IN_OPTOUT=$(mysql -u $BMB_MYSQL_USER -h $BMB_MYSQL_HOST -NB -se "SELECT cpf FROM optout WHERE cpf = $CPF;")
if [[ ${USER_IN_OPTOUT} == *"${CPF:0}"* ]]; then
echo "----------------------------------------"
echo "User already exists."
echo "----------------------------------------"
else
echo "---------------------------------------"
echo "User does not exists."
echo "---------------------------------------"
exit 1
fi
The variable CPF ($CPF) is equal to 00324323721. As this registry exists it returns the cpf, as expected. However, this query is removing leading zeros returning 324323721. I expect that the returns be exactly 00324323721. How can I do that?

get multiple variables from a line using shell script

i am trying to monitor my hosts through ping. the hosts information are in a mysql table. i m using fping command the code is as followings
#/bin/sh
id=$(mysql -B --column-names=0 -uroot -pPassword -D monitor -e "SELECT ipv4 FROM nics WHERE icmp=1");
result=$(fping -c 10 $id |grep 'xmt/rcv/%loss');
#echo $result;
for line in $result;
do
echo $line
done
the output is
111.125.140.6 : xmt/rcv/%loss = 10/10/0%, min/avg/max = 234/234/235
123.135.140.7 : xmt/rcv/%loss = 10/0/100%
111.125.140.1 : xmt/rcv/%loss = 10/10/0%, min/avg/max = 230/231/231
111.125.130.2 : xmt/rcv/%loss = 10/10/0%, min/avg/max = 234/234/234
now i want to get IP, loss and average record from each line and input the data in a new table
thanks in advance
Using a while loop (instead of a for loop) with awk:
while read -r line
do declare $(awk '{split($0,a,"[%/ ,]"); print \
"ip="a[1],"send="a[8],"rec="a[9],"loss="a[10],"min="a[17],"avg="a[18],"max="a[19]}' <<< $line);
## variables created: [ip, send, rec, loss, min, avg, max]
## test with: echo $ip, $send, $rec, $loss, $min, $avg, $max
## now you can insert the variables into your new SQL table:
echo "INSERT INTO newtable (IP,SEND,REC,LOSS,MIN,AVG,MAX) \
VALUES ('$ip','$send','$rec','$loss','$min','$avg','$max');"
done< <(printf '%s\n' "$result") | mysql -uroot -pPassword foobar
This will to declare individual variables from your $line strings which you can insert into SQL.

Check if mysql user exists in bash script, getting error

I am working on a bash script to check if a mysql user exists, with following commands:
checkuser=`mysql -u $mysqlroot -p$rootpw -e "SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = '$user_name') ;"`
lastchr=${checkuser#${checkuser%?}}
if [ $lastchr == 1 ] ; then
clear
echo "ERROR: mysql user exists"
fi
My problem is, that the terminal always gives me following feedback:
/etc/hosting: line 775: syntax error near unexpected token `('
/etc/hosting: line 775: `checkuser=`mysql -u $mysqlroot -p$rootpw -e "SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = '$user_name') ;"`'
I tried with escaping the "(" and ")", but I didn't success.
What am I doing wrong? I tried all different kinds of escaping, single quotes, ... and it didn't help.
Kind regards
EDIT:
because maybe needed, previous lines:
echo "creating mysql user ..."
echo ""
read -p "enter username: " user_name
if [[ -z "$user_name" ]] ; then
clear
echo "username mustn't be empty!"
create_mysql_user # calls function again
fi
# check username length
if [ ${#my_user} -gt 16 ] ; then
clear
echo "ERROR: the username mustn't be longer than 16 characters"
create_mysql_user
fi
This is an old question but still searchable on internet. I would like to answer it because it doesn't have a proper answer.
To check the existence of mysql user using bash, you can use the following package jq to transform the query result to readable output as list of users in array format:
# Get list of all sql users
sql_users=$(mysql -e "SELECT USER FROM mysql.user;" | jq -rR .)
check_sql_user=$(echo "${sql_users}" | grep "username_to_check")
if [[ -z "${check_sql_user}" ]]; then
echo "No user found"
# Call create user here
else
echo "User found"
fi

Passing multiple parameters from shell script to mysql query

I have to write a unix shell script which will take the parameters for MySQL and export the result into csv file.
I have written to some extent but am unable to pass the multiple parameters from shell script to sql.
Can anyone help me out in this? Thanks!!
assuming you call the script like this
$ ./script param1 param2 param3
in the script
echo $0 #will echo 'script' (the name of the script)
echo $1 #will echo 'param1'
echo $2 #will echo 'param2'
echo $3 #will echo 'param3'
echo $# #will echo '3' the number of params passed to script
echo $# #will echo 'param1 param2 param3' (all the parameters passed)
host="127.0.0.1"
user="root"
password="pass"
result=`mysql -h $host --user=$user --password=$password --skip-column-names -e "select $param1 from $param2 where $param3 = 3"`
echo $result
mysql -e "set #param1:=4897, #param2:=2; source the_script.sql;"
And the script:
SELECT #param1, #param2;
P.S. BTW, I recommend to pass connection parameters using --defaults-extra-file option.