proper way to sudo over ssh

2020-01-26 03:20发布

I have a script which runs another script via SSH on a remote server using sudo. However, when I type the password, it shows up on the terminal. (Otherwise it works fine)

ssh user@server "sudo script"

What's the proper way to do this so I can type the password for sudo over SSH without the password appearing as I type?

标签: ssh sudo
9条回答
放荡不羁爱自由
2楼-- · 2020-01-26 03:40

Depending on your usage, I had success with the following:

ssh root@server "script"

This will prompt for the root password and then execute the command correctly.

查看更多
ゆ 、 Hurt°
3楼-- · 2020-01-26 03:42

The best way is ssh -t user@server "sudo <scriptname>", for example ssh -t user@server "sudo reboot". It will prompt for password for user first and then root(since we are running the script or command with root privilege.

I hope it helped and cleared your doubt.

查看更多
SAY GOODBYE
4楼-- · 2020-01-26 03:44
echo $VAR_REMOTEROOTPASS | ssh -tt -i $PATH_TO_KEY/id_mykey $VAR_REMOTEUSER@$varRemoteHost 
echo \"$varCommand\" | sudo bash
查看更多
老娘就宠你
5楼-- · 2020-01-26 03:46

I was able to fully automate it with the following command:

echo pass | ssh -tt user@server "sudo script"

Advantages:

  • no password prompt
  • won't show password in remote machine bash history

Regarding security: as Kurt said, running this command will show your password on your local bash history, and it's better to save the password in a different file or save the all command in a .sh file and execute it. NOTE: The file need to have the correct permissions so that only the allowed users can access it.

查看更多
成全新的幸福
6楼-- · 2020-01-26 03:47

Another way is to use the -t switch to ssh:

ssh -t user@server "sudo script"

See man ssh:

 -t      Force pseudo-tty allocation.  This can be used to execute arbi-
         trary screen-based programs on a remote machine, which can be
         very useful, e.g., when implementing menu services.  Multiple -t
         options force tty allocation, even if ssh has no local tty.
查看更多
forever°为你锁心
7楼-- · 2020-01-26 03:50

I faced a problem,

user1@server1$ ssh -q user1@server2 sudo -u user2 rm -f /some/file/location.txt

Output:
sudo: no tty present and no askpass program specified

Then I tried with

#1
vim /etc/sudoers
Defaults:user1    !requiretty

didn't work

#2
user1   ALL=(user2)         NOPASSWD: ALL

that worked properly!

查看更多
登录 后发表回答