问题
I have to run few commands in Azure VM through Azure Devops release pipeline. I created SSH
step and can successfully connect to remote VM. But having trouble running commands which requires sudo
permissions.
e.g systemctl restart <some service>
errors :
##[error][sudo] password for ***:
##[error]Command failed with errors on remote machine.
i tried echo <password> | sudo -S systemctl restart <some service>
. No luck.
What is secure way to accomplish this?
回答1:
The only way to I was able to run sudo over ssh task was to make the sudoer as root memeber with no password for me as your agent might stuck in STDIN. this article may help https://www.shellhacks.com/how-to-grant-root-access-user-root-privileges-linux/
回答2:
This is exactly what you need, it works in my azure devops pipeline on my ubuntu server:
https://serverfault.com/questions/772778/allowing-a-non-root-user-to-restart-a-service
Command for ssh task in azure pipeline:
sudo systemctl restart <some service>
and in linux machine (ubuntu in my case):
sudo visudo -f /etc/sudoers.d/90-clouding-ubuntu
add these two lines
Cmnd_Alias RESTART_SVC = /bin/systemctl restart <some service>
%<myuser> ALL=(ALL) NOPASSWD: RESTART_SVC
You must write right service name and right username (must have rights for sudo).
回答3:
Had the same problem and found a way without changing root priviliges. My problem with the ssh script was "the agent stucks in the STDIN of the Password". A script like:
echo <password> | sudo -S service solr stop
Works locally on the server, but somehow the agent still stucks on the STDIN. Here is another solution. I used a powershell script with Posh-SSH and not the default ssh step.
First of all you need to install Posh-SSH on your server: https://github.com/darkoperator/Posh-SSH there is also a small youtube tutorial for it. The installation script is:
Install-Module -Name Posh-SSH -force
Get-Module -ListAvailable -Name Posh-SSH
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force -Verbose
You only need to run it once. After you can create your Powershell script and make a SSHSession with your server:
$pass="<password>"|ConvertTo-SecureString -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PsCredential('<user>',$pass)
$session = New-SSHSession -Computername <Server> -Credential $Cred -Force
To test your connection:
Get-SSHSession
And now you can run the script like this:
Invoke-SSHCommand -command "echo <password> | sudo -S service solr stop" -SessionId 0
And at the end close the connection:
Remove-SSHSession 0
来源:https://stackoverflow.com/questions/57903802/secure-way-to-run-sudo-commands-in-azure-devops-ssh-task