Sunday, April 28, 2024
 Popular · Latest · Hot · Upcoming
2
rated 0 times [  2] [ 0]  / answers: 1 / hits: 5479  / 2 Years ago, sun, november 6, 2022, 5:18:09

I run this SSH command from server1 on server2 :


ssh server2 echo pasword | su - root  -c "echo this is the  `hostname`" 

I expected the result to be host name of server2 but instead I get host name of server1. How can I manipulate the command to get the hostname of server 2 ?


Thanks.


More From » bash

 Answers
0

Firstly, your command piping is wrong. As it currently stands this is executed in this order:



  1. ssh server2 echo pasword - this goes to Server 2 and logs in and executes the command echo pasword on the remote system. (output would be pasword)



  2. Take the output from #1 ("pasword") and pipe that into this command run locally:


    su - root -c "echo this is the `hostname`"

    ... which echoes your LOCAL hostname, technically (and doesn't do anything with the echoed 'pasword' from the first command). (you don't need 'root' for this though - hostname can be run by anyone on the remote system or your local system, no need for superuser!).




What you need to do is pass the command into SSH and NOT into pipes this way. The way to do this is to use this:


ssh server2 'echo "This is the $(hostname)"'

This will properly send the request to the remote server to get the hostname from that server and execute that on the remote server and tell you the response. You do not need sudo to do this on the remote server.


If you need to provide a password for the SSH session, you should be using ssh-pass instead, and execute this instead:


sshpass -p YourPassword ssh server2 'echo "This is the $(hostname)"'

This is considered the proper approach as it does keyboard-interactive authentication non-interactively and passes the password into the SSH command when prompted for a password. However this is still very insecure, as your password will be in command history or hardcoded in scripts, so you should consider using SSH Key Authentication on your remote servers instead of password authentication where possible.


[#2000] Sunday, November 6, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
avilyexplor

Total Points: 20
Total Questions: 102
Total Answers: 120

Location: Maldives
Member since Mon, Jun 21, 2021
3 Years ago
;