Sending terminal commands via SSH connection: Nested pipes

puttyshellsshunix

Hoi everybody,

I am currently having a problem with sending commands over SSH via command line to a server. To have an easy example, I always send the "pwd" command – which should return the current folder you are in.

I build the initial SSH connection successfully with the following command:

sshg3 user@server#port 'pwd'

which connects to the server and short the home folder.

Afterwards, I use sudo su – user2 – because the user has more rights as user (needed for specific tasks):

sshg3 user@server#port "echo pwd|sudo su - user2"

Here, however, if I want to concat multiple commands after one another, I need to insert "" – otherwise it does not work:

sshg3 user@server#port "echo ""pwd;pwd""|sudo su - user2"

If I have no or only one ", the result is:

pwd
-bash: line 1: {homefolder}: is a directory

Now, afterwards using lftp I need to upload data to that server using yet another user. Using another pipe, I get that to work with a single command the following way:

sshg3 user@server#port "echo ""echo pwd|lftp -u user3 -p 1234 server2""|sudo su - user2"

And now comes the problem: Sending multiple commands to the second server does not work. If I use the same pattern I used before (""), I get this result:

sshg3 user@server#port "echo ""echo ""pwd;pwd""|lftp -u user3 -p 1234 server2""|sudo su - user2"

This prints:

echo pwd
bash: pwd|lftp -u user3 -p 1234 server2: command not found

The most part I got by using the answer in [this][1] thread – but now I am stuck.

Can someone help me with this?

Best Answer

I am not exactly sure what you are trying to do on the remote server. It looks like you want to execute commands which depend on the response of other commands (like pwd, which prints the working directory). Possibly you also want to use a password ("echo pwd") for su, I am not sure which.

I would suggest one of the following approaches:

  • Write a script on the remote server that does what you want. Execute that script via ssh. Give the script additional information, like passwords, as arguments when you call it.

  • If you can't store the script on the remote server permanently: Write the script anyway, and then pipe and execute the whole script through ssh.

  • Use expect to script a complicated interactive session via ssh, where you call various programs, which in turn expect user input.

In any case, I don't think you'll get far messing around with echo.

Related Question