Friday, December 18, 2015

MySQL trigger that will execute OS command

7:43 AM Posted by Dilli Raj Maharjan 6 comments

Download and Install lib_mysqludf_sys plugin 

Go to URL https://github.com/mysqludf/lib_mysqludf_sys
















Click on Download zip or use wget to download.

wget https://github.com/mysqludf/lib_mysqludf_sys/archive/master.zip

















Extract the downloaded plugin file and change directory to extracted directory.

unzip master.zip
cd lib_mysqludf_sys-master/














Compile module with command below.

gcc -m64 -fPIC -Wall -I/usr/include/mysql -I. \

-shared lib_mysqludf_sys.c -o /usr/lib64/mysql/plugin/lib_mysqludf_sys.so







Login to mysql and create function sys_exec and sys_eval on required database.


mysql -u root -p

use test;

CREATE FUNCTION sys_exec RETURNS int SONAME 'lib_mysqludf_sys.so';
CREATE FUNCTION sys_eval RETURNS int SONAME 'lib_mysqludf_sys.so';











Now for testing purpose we will create trigger that will execute after insert on each row of table tab_trig_test. First create table tab_trig_test.


use test;
create table tab_trig_test(
sn int,
name varchar(100)
);










Drop and create trigger that will execute after insert for each row on table tab_trig_test.
drop trigger if exists trig_test;

DELIMITER @@

CREATE TRIGGER trig_test 
AFTER INSERT ON tab_trig_test 
FOR EACH ROW 
BEGIN
 DECLARE cmd CHAR(255);
 DECLARE result int;
 SET cmd=CONCAT('echo ', new.name, ' > /tmp/haha',new.name);
 SET result = sys_exec(cmd);
END;
@@
DELIMITER ;












Now insert a row on table to verify that trigger has executed as expected.

insert into tab_trig_test values(2,'rajiv');







Verify that OS file has been created with command below.

\! cat /tmp/haha



6 comments:

  1. Thanks for sharing this, Dilli.

    -Prasanna.

    ReplyDelete
  2. My Pleasure. Thanks for the comment.

    -Dilli R. Maharjan

    ReplyDelete
  3. it is not working for me
    when i am writing \! cat /tmp/haharajiv this command it shows no such file or directory.

    if you have any solution for that please let me know ASAP

    ReplyDelete
    Replies

    1. Hi Jaydeep, thank you for pointing out the error. Can you try \! cat /tmp/haha only. I am sure that should work
      - Dilli

      Delete





  4. DELIMITER $$
    CREATE PROCEDURE `callphp`()
    BEGIN
    declare cmd char(55);
    declare result char(100);
    SET cmd = CONCAT('sh /home/sudhir/Desktop/runphp.sh');
    SET result = sys_exec(cmd);
    END $$
    DELIMITER ;

    this is my code i dono whats wrong with this it never executes the .sh file any solution

    ReplyDelete
  5. showing error ERROR 1305 (42000) : FUNCTION test.sys_exec does not exist

    ReplyDelete