How To Sudo Over SSH Without Being Asked Your Password

As systems age, it’s not uncommon for them to become less convenient to work with. Infrastructure as code and containerization tools like Ansible and Docker have become industry standards, but sometimes, you’ll find yourself dealing with systems that don’t have these tools in place. When that happens, you’ll likely find yourself doing a lot of manual work, such as deployments, middleware updates, and general maintenance.

At first, it may be exciting to do some “shell hacking”, but as time goes on, the thrill wears off and you start looking for ways to automate the operations. In this article, we’ll show you how to automate privileged operations using SSH and Sudo, so you can perform tasks with just one click.

The Problem

Let’s say your usual shell hacking involves the following steps:

  1. SSH into the server
  2. Gain elevated privileges using sudo
  3. Perform privileged operation or run script

For example, you might run the following commands to list the files in a directory:

ssh user@host
sudo ls

The Solution

Now, let’s say you want to run this from a Jenkins job on another server. This is great! It means you don’t have to keep typing the commands to log into the system and execute your commands or scripts. With one click, you can perform the task.

But when you try to run the script from Jenkins, it fails because it prompts you to enter the sudo password. So, how can you avoid being prompted for the password? You might think it would be great if you could send it as part of the command. A quick Google search leads you to the solution:

set +x
ssh user@host "echo <password> | sudo -S <command>"
set -x

The “set +x” stops outputting to the console so your password won’t get printed. The “-S” causes sudo to read the password from STDIN. This will ensure your job executes the command as sudo without prompting you for the password. Your goal of one-click execution is now complete!

Security Concern

It’s important to note that hard-coding the password in the Jenkins job, as shown above, will reveal your password to anyone who has access to Jenkins or the server itself. To avoid this, you should amend the job to ask for the password as an input parameter (basically making a parameterized job). Alternatively, you can put the password in the Jenkins credential store and have it injected into the job as a variable.

Finally

Automating privileged operations with SSH and Sudo can save you a lot of time and effort. By following the steps outlined in this article, you can perform tasks with just one click, without having to manually log into the system and enter the sudo password. Remember to always be mindful of security concerns when working with sensitive information like passwords.

Useful Info