0

I'm trying to set some automation inside local network and started working with some shell scripting and something that I saw - very strange behaviour SSH inside script according to how script running(with or without sudo):

What I have: ComputerA and ComputerB.

Inside ComputerA:

A shell script script.sh:

cp /dir1/file1 /dir2/file2
ssh username@ComputerB "sudo reboot"

/etc/ssh/ssh_config file with some configurations to work without ssh-keys (they always changes on ComputerB):

StrictHostKeyChecking no
UserKnownHostsFile=/dev/null
GlobalKnownHostsFile=/dev/null

Inside ComputerB:

In /etc/sudoers file:

username ALL=(ALL:ALL) NOPASSWD:ALL

When I connecting through SSH to ComputerA and running script.sh without sudo, I get permission error to write to /dir2 (it's OK) and next command on ComputerB executes normally (reboots ComputerB), but I'm running sudo script.sh. It copy file and then I got strange - SSH asks me username password. Tried different variants to change ssh command to something like:

ssh -t username@ComputerB "echo user_pass | sudo -S reboot"

but nothing helped. So I need help to figure out what happens and what to do to execute sudo script.sh without entering password for ssh command inside. Thanks!

2
  • 1
    You may need to edit the file permissions. Can you go to the directory with script.sh and run ls -l and let me know the results? Commented Dec 30, 2020 at 19:41
  • @mjlitz script.sh have '777' permissions Commented Dec 30, 2020 at 19:47

1 Answer 1

2

Don't run script.sh with sudo on computerA; instead modify the script like so:

sudo cp /dir1/file1 /dir2/file2
ssh username@ComputerB "sudo reboot"

The reason that you're seeing the strange behaviour is that you're actually becoming root on computerA (I assume you have a keypair set-up for your regular user and expect to connect to computerB passwordless?), and that root on computerA doesn't have a keypair that computerB knows about.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, that make sense and sudo cp will do the work, and for some reason I don't want make sudo cp. I don't get why in this two situations I'm connecting through SSH using same username so I expect there is no difference how I run script.sh - with or without sudo.
@Doe - Yes, there is. with sudo it tries to use root's key-pair from computerA, without it yours. The username is only relevant for the remote end and has no impact on the selection of the keys. If you don't want to use sudo inside the script make sure that your normal account has read-/write-access to both dir1 and dir2.

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.