How to run sudo su in Azure devops pipeline? [duplicate] - linux

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?

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/

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).

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

Related

Can an Azure Machine Learning Compute Instance shut down itself automatically with a bash script executed by crontab?

I have a compute instance that starts at 12:00 with the scheduler of Azure ML and does a job scheduled in the crontab of the CI at 12:10. The thing is that this job doesn't always takes the same time to finish. So i want the CI to shut down itself when done.
The script that the crontab executes is the following:
---------------------------------------------------------
#!/bin/bash
...
# CRREATE FOLDER FOR LOGS
foldername=$PROJECT_PATH/$(date '+%d_%m_%Y_%H_%M_%S')
mkdir $foldername
filename=az_login.txt
path=$foldername/$filename
touch $path
az login -u *<USERNAME>* -p *<PASSWORD>* > $path
filename=acr_login.txt
path=$foldername/$filename
touch $path
# Authenticate to ACR
az acr login --name $ACR_NAME > $path
filename=pull_container.txt
path=$foldername/$filename
touch $path
# Pull the container image from ACR
docker pull $ACR_NAME.azurecr.io/$IMAGE_NAME:$IMAGE_TAG > $path
filename=run.txt
path=$foldername/$filename
touch $path
# Run the container image
docker run -v $CREDENTIALS_PATH:/app/config_privilegies $ACR_NAME.azurecr.io/$IMAGE_NAME:$IMAGE_TAG > $path
filename=rm_container.txt
path=$foldername/$filename
touch $path
# Delete the exited containers
docker rm $(docker ps -a -q --filter "status=exited") > $path
az ml compute stop --name *<CI_NAME>* --resource-group *<RESOURCE_NAME>* --workspace-name *<WORKSPACE_NAME>* --subscription *<SUBSCRIPTION_NAME>*
Everything works great until the stop command. In this particular code, it does nothing.
I've tried to put the last command in a seperate bash script and changing the last line for "./close_ci.sh". However, this doesn't work either, it restarts the CI instead of stopping it.

Run script on remote SUSE Linux with root privilege using WinSCP .NET assembly

I'm trying to execute sh script from Windows on Remote SUSE Linux using WinSCP .NET assembly.
I've created a session as follow:
$sessionOptions = New-Object WinSCP.SessionOptions -Property #
{
Protocol = [WinSCP.Protocol]::Sftp
HostName = "RemoteIp"
UserName = "username"
Password = "password"
}
$session = New-Object WinSCP.Session
I run the sh script
$session.ExecuteCommand("bash /home/script.sh" )
and I get permissions errors, for example:
rm: cannot remove '/somefolder': Permission denied.
Simple command like uname works fine.
Any idea how can I log in as root?
You have to run your command through sudo:
$session.ExecuteCommand("sudo bash /home/script.sh")
Though WinSCP does not support providing input to commands. So your remote system must be configured not to require sudo password (at all, or for that specific command).
Some references:
How do I change user after login (e.g. su root)?
Allowing automatic command execution as root on Linux using SSH.
Go to your WinSCP profile (Session > Sites > Site Manager)
Click on Edit > Advanced... > Environment > SFTP
Insert sudo su -c /usr/lib/sftp-server in "SFTP Server" (note this path might be different in your system)
Save and connect

use powershell and plink to shutdown remote linux computer with sudo command [duplicate]

This question already has answers here:
Execute sudo command on Linux from plink.exe on Windows
(4 answers)
Closed 2 years ago.
I'm attempting to shutdown a RHEL7 linux computer remotely from a windows computer in a non-interactive fashion using powershell and plink.
I can send commands and retrieve the result like so:
$plinkPath = "C:\somePath"
$ipAddress = "192.168.111.1"
$username = "userName"
$password = "password"
$resultPath = "C:\somewhere"
$resultFile = "someFile.txt"
& "$plinkPath\plink.exe" #("$ipAddress", "-l", "$username", "-pw", "$password", "(pwd)" | Out-File "$resultPath\$resultFile"
The command above prints the working directory in linux and saves it to file. However, I can't send a shutdown command like this because the command must be run as root on this computer. I believe there should be some syntax like the below to run a sudo command in a similar way:
& "$plinkPath\plink.exe" #("$ipAddress", "-l", "$username", "-pw", "$password", "(sudo ... shutdown -h now)") | Out-File "$resultPath\$resultFile"
Is there some way to send a shutdown command with sudo using this method?
Thanks.
Make sure that the user can indeed run sudo commands.
The issue might be that the user that is trying to run the command is requested to insert the sudo password.
In the sudoers file insert <YOUR_USERNAME> ALL=(ALL) NOPASSWD

Execute a Linux Command to a Linux Server via Windows Powershell

I would like to execute commands on my Radius Server (Amazon Linux) via Windows Powershell
These are the commands:
useradd -g radius-enabled username
yes -- -1 | sudo -u username google-authenticator -l testlabel -i testissuer -t -d -w 5 --no-rate-limit -f
1 basically adds a user then 2 creates an mfa token for the created user
This needs to be done via Windows Powershell so I can try to make a powershell script later on
First, I tried to manually SSH to the Linux Server via Powershell module SSHSessions:
(i have installed the SSHSession module, configured my sshd_config)
New-SshSession -ComputerName ? -Username -Password
Enter-SshSession -ComputerName
[ServerIPAddress]: /home/username # :
It shows that I have SSHed to the server and I am able to execute some commands such as "df -h"
but when I try to sudo, change directory or execute other commands, It just hangs and I cant stop it.
What would be the proper/best way to execute this? I have tried searching for related topics but it wouldn't fit my situation. I decided to ask a question here to be more specific and maybe gain reputation so I can upvote that other stackoverflow answers that helped me.
Thanks!

Secure way to run `sudo` commands in Azure Devops SSH Task

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?
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/
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).
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

Resources