Run MySQL query on remote machine through ssh in command line

你离开我真会死。 提交于 2019-11-30 11:24:27

问题


I am trying to run MySQL query on remote machine with this command:

ssh user@192.168.2.26 "mysql -uroot -proot -e \"use test";""

I am not able to use that database.

Please suggest a working command.


回答1:


Try this:

mysql -h host -u root -proot -e "show databases;";



回答2:


Try this:

ssh root@host "mysql database -e 'query to run on table_name; more queries to run;'"

Same can be done with user@host if that user has permission to execute SQL queries let alone launch mysql in general. Using -e is the same as --execute, which will run whatever you put within the trailing quotes (single or double) and quit. The standard output format would be the same as you would see using --batch.




回答3:


MySql seems to have a special command line syntax which includes the database.

mysql -u user -p -e 'SQL Query' database

This documentation is rather old but I got it to work

http://www.cyberciti.biz/faq/run-sql-query-directly-on-the-command-line/

Final working command with ssh:

ssh user@host "mysql -u user -e 'show tables;' databasename"




回答4:


This ended up working for me in a bash script:

query='USE [database]; SELECT ...'   
mysql='mysql -u [username] -p[password] -e '"'""$query""'"
ssh [username]@[server] -t "$mysql"

If you want to make it more safe then add a prompt for the password instead of storing it somewhere potentially unsafe.




回答5:


This worked for me after a few tests (basically same answer as @King-Wzrd):

ssh -t kom "mysql -uroot -p -e 'show databases;'"
ssh -t kom "mysql -uroot -p < /home/ling/websites/jin_test/.deploy/tmp.sql"

The "trick" was the quotes around the command.

The -t option allows for prompting password interactively via the remote shell.

The kom here is just a ssh config identifier defined in my ~/.ssh/config file (see more here: https://www.cyberciti.biz/faq/create-ssh-config-file-on-linux-unix/).



来源:https://stackoverflow.com/questions/17544954/run-mysql-query-on-remote-machine-through-ssh-in-command-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!