0

I want to execute cd and scp commands on a remote server which have to be logged in with a different sudo user. Below code snippet asks for the password(echos on screen) for my user but hangs there. It doesn't execute cd

#!/bin/bash
server=myserver.com
ssh $server 'sudo -S -u <user> -i; cd dir1/dir2/; scp file1 user@local-sever'
1
  • i tested with: ssh user@IP 'cd /etc && cat passwd' Commented Jan 21, 2021 at 14:19

2 Answers 2

2

The issue is that you have a semi colon before cd and so sudo has no command to execute. Remove the ; and it should work:

ssh $server 'sudo -S -u <user> -i scp dir1/dir2/file1 user@local-sever'
Sign up to request clarification or add additional context in comments.

3 Comments

Note that the sudo ends with the cd and the default user might not have permissions for the scp.
Good point @Paul Hodges, I've amended the solution.
@RamanSailopal That seems to work but scp command isn't working. It is not even asking for password.
1

There are several ways to address this, but most boil down to wrapping up the commands into a set of instructions. Raman's solution is good since it handles the issue by using full paths, but sometimes that isn't an option. Here's another take -

Assuming your command list can afford the quotes, I like here-strings.

ssh -t sa-nextgen-jenkins.eng.rr.com <<< "
  echo 'set -x; cd /tmp; whoami; touch foo; ls -l foo; rm -f foo;'|sudo -iSu user
"

If you need the quotes, try a here-doc.

ssh -t sa-nextgen-jenkins.eng.rr.com <<END
  echo 'set -x; echo "$RANDOM"; cd /tmp; whoami; touch foo; ls -l foo; rm -f foo;'|sudo -iSu $user
END

You can also write a small script that has arbitrarily complex commands and scp it over, then use a remote ssh call to execute it as the relevant user.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.