0

I would like to create an array with the variables $user and $host in order to pass them to the ssh command.

I have tried:

my_array=('something1' 'something2' 'user' 'host_ip')
sudo ssh ${my_array[2]}@${my_array[3]}

my_array=('something1' 'something2' 'user' 'host_ip')
sudo ssh host -l ${my_array[2]}  ## here host is not a variable

my_array=('something1' 'something2' 'username' 'host_ip')
my_var="${my_array[2]}@${my_array[3]}"
sudo ssh $my_var

In all cases I get to be asked from the local user password (because of sudo) and my answer is accepted. When I type the remote user password, I get the following output and I get to try agian:

Permission denied, please try again.

Notes:

  • I am using an IP as the host
  • My password is the right one and it is working when I do not use variables (sudo ssh user@host).
  • I recently installed the sshpass package

Thank you very much!

Edit

For some reason the following day all the above and the solutions bellow worked... Can someone explain this?

Phineas
  • 103
  • 3

2 Answers2

0

I think it's quoting problem, add a double quotes to the variables :

my_array=('something1' 'something2' 'user' 'host')
sudo ssh ${my_array[2]}@"${my_array[3]}"
Reda Salih
  • 241
  • 2
  • 7
  • this does not work, because ${my_array[4]} does not correspond to an element, since the index starts from 0. As expected the output `ssh: Could not resolve hostname : Name or service not known` – Phineas Mar 17 '20 at 15:23
  • It worked also like this sudo ssh ${my_array[2]}@"${my_array[3]}". With quotes only to the second part. Please modify your answer and make it straight forward an I will mark it as a solution – Phineas Mar 17 '20 at 15:55
  • Thanks it's done i have edited it, but i have tried these commands with an ip instead of hostname and apparently they are all working. Confusing. – Reda Salih Mar 17 '20 at 15:58
  • today they are working to me also! I already edited my question.. Could you also delete the part before EDIT? It is not help or answer the question – Phineas Mar 17 '20 at 16:01
  • Mmm i see, it's done :) – Reda Salih Mar 17 '20 at 16:03
0

The problem were the quotes in the host element of the array because I am using an IP. It seems a number element is needed when an IP is used as host. So the code should be:

my_array=('something1' 'something2' 'user' host_ip)
sudo ssh ${my_array[2]}@${my_array[3]}
Phineas
  • 103
  • 3