6

I have a problem executing a remote command through SSH that has special character in it. I'm trying to export a database from MySQL for back up purposes. This is the command I have in my local script:

#!/bin/bash
ssh user@host "mysqldump -u dbname -p'p$ssw0rd' --lock-tables=false dbname > ~/sites/mysite/backup/dbname.sql"

As you can see I'm using the ' characters around my password. When I execute this script I get the following error:

mysqldump: Got error: 1045: Access denied for user 'dbname'@'localhost' (using password: YES) when trying to connect

However, when I ssh into the machine manually and execute the command it executes just fine. I get the impression that through executing the command through ssh something is lost and the password doesn't come through.

How can I execute my command with special characters through ssh?

masegaloeh
  • 18,236
  • 10
  • 57
  • 106
Luke
  • 3,826
  • 8
  • 36
  • 40

2 Answers2

6

You can try escaping the special characters in the command that you are passing to the ssh. In which case your

p$ssw0rd

becomes

p\$ssw0rd

Since the shell you are using might interpret "\" character differently, I can not vouch for 100% solution to your case, but it won't hurt to try.

MelBurslan
  • 609
  • 6
  • 12
  • This actually worked! I still find it odd that when I run the script when logging in with ssh manually works fine but to run it as a remote command I suddenly need to escape. Any how, all good. – Luke Mar 04 '13 at 03:41
  • when you are typing your password on the login screen, the keyboard scanner, tty, takes each character you type, literally (there are exceptions to that, but not the matter of subject here), but when you send them via ssh, double quotes, the special characters, like \, $, ;, etc., are interpreted with their special meanings. This is the reason why your password was failing. It is a common occurrence. – MelBurslan Mar 04 '13 at 05:01
  • Funny thing is, my password obviously isn't p$ssw0rd but it does have a $ in it. :) – Luke Mar 04 '13 at 06:14
2

Why don't you just specify your credentials in an options file?

Edit ~/.my.cnf and add something like this:

[mysql]
user = 'dbname'
password = 'p$ssw0rd'

Make sure you run $ chmod 600 ~/.my.cnf to restrict access to that file.

Then you don't need to specify those in your SSH command. This is arguably a safer way to do thing anyway, as usernames/passwords don't show up in either your ~/.bash_history or the running process list (which is viewable by all users).

EEAA
  • 109,363
  • 18
  • 175
  • 245