How can I pipe an alias that requires sudo through SSH?

I’ve set up so that I can SSH securely into my home PC from my laptop. Today, I tried running an update just to test, but I couldn’t do it from the laptop.

What I basically wanted to do, was to pass the command to the machine without SSH-ing into it while not keeping the connection alive. I tried looking around online to see if I could find something, but nothing seems to work.

These are the commands I tried:

$ ssh myip 'sysupg &'
bash: sysupg: command not found
echo "mypassword" | ssh myip 'sudo -S dnf upgrade -y &'
[sudo] password for myuser:
sudo: no password was provided
sudo: a password is required
echo "mypassword" | ssh myip 'sudo -S -k dnf upgrade -y &'
[sudo] password for myuser:
sudo: no password was provided
sudo: a password is required

When it asks for my password ([sudo] password for myuser:), it doesn’t let me enter anything, just proceeds, giving me the last two sudo errors.

tldr: pass a command that requires sudo through ssh to another machine, "automatically" close the connection as soon as the command is passed and, if possible, execute the command in x amount of minutes.

Asked By: telometto

||

Possible way:

ssh -t myip 'sudo -b dnf upgrade -y >/tmp/aa 2>&1'
  • You want your task to run whilst disconnected; use the 1> and 2> redirections
  • You want your task to run in background; use sudo -b option
  • You want ssh to provide interactivity to sudo; use ssh -t option

Other possible but not recommended way:

echo PASSWORD | ssh myip 'sudo -S -b dnf upgrade -y >/tmp/aa 2>&1'
  • You want sudo to read password on stdin; use sudo -S option instead of ssh -t
  • Having cleartext password in command history is a fault

You missed the sudo -b option, because the & makes password prompt to run in background and not your only desired task.

Also, missing 1> or 2> redirections retains the ssh connection.

However, provided that you use PubkeyAuthentication, a safe way to do the trick is:

ssh root@myip 'dnf upgrade -y >/tmp/aa 2>&1 &'
  • Set PermitRootLogin prohibit-password in sshd_conf
  • Copy your public key in /root/.ssh/authorized_keys
  • Have always your private key passphrase protected, and use ssh-agent

But, the best way is to use screen at the server side:

ssh -t myip screen -RD
sudo -s
...whatever...
Ctrl-A d (detach and disconnect)

Later, reattach the session:

ssh -t myip screen -RD
  • You meet your requirements
  • You reattach your session alive
  • You learn screen
Answered By: Thibault LE PAUL
Categories: Answers Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.