Search code examples
rubybashspecial-characters

Escaping an ampersand character ('&') in a password for a Ruby script


I have a password like 'X&Y' and I am trying to run a Ruby script that opens an SSH session, but the script breaks at the & character like :

*server: X *server: bash: Y: command not found

Escaping the character like & doesn't help either. Ideas appreciated!

The code where it happens is at the ssh.exec:

pass="X\&Y"
Net::SSH.start( host_name, user, :password => pass ) do |ssh|
   #do stuff
   command = "sudo -S rm file"
   cmd = "#{pass}|#{command}"
   ssh.exec(cmd) do |ch, stream, data|
     puts "*server:" + data.inspect
   end
end

Solution

  • You can use ssh like without & getting any special meaning:

    ssh -t -t user@localhost "echo 'abc&def'"
    abc&def
    Connection to localhost closed.