How can I automate a Topshelf interactive service install? - topshelf

I have a couple Topshelf services that run under a specific service account. If I install the services manually from a command line, I can use the --interactive flag, and a dialog box comes up allowing me to enter the username and password. I'd like to be able to automate this through a Powershell script.
Does anyone know how to do this? (Not concerned about Powershell specifically, but with how can I provide the username and password in any installation script.)
As Travis mentioned, I took a look at the command line options. Almost working for me, but now I have one escaping issue. To install, you can type, e.g.,
MyService.exe install -username:Foo -password:Bar.
However, I have to provide both the domain and username for the username option (I know this from doing the --interactive route):
MyService.exe install -username:mydomain\$myusername -password:Bar
I cannot find a way to escape this that works! Sorry -- my question has morphed into something else, might need to mark it answered and open a different one.

Travis pointed me in the right direction with the command line options. I had one more problem with the service account username I had, which was prefixed with a "$": domain\$myuser. I could not find a way to escape it so the "install" command would accept it.
We created a similar username "myuser" (without the $). Now this works just fine:
MyService.exe install -username:domain\myuser -password:Bar

The username and password are configuration in the app.config for services in my setting. This is used in the service setup block in the RunAs.
Additionally, there are other command line options for Topshelf. I don't know if the documentation is 100% up to date but it's a good place to start.

For future readers:
See this url:
https://kristofmattei.be/2015/01/15/topshelf-install-powershell-get-credentials/
Here is the important quote from the url above
Start Quote
So the best version is:
$credentialsOfCurrentUser = Get-Credential -Message "Please enter your username & password for the service installs"
$networkCredentials = $credentialsOfCurrentUser.GetNetworkCredential();
$username = $credentialsOfCurrentUser.UserName
$password = $networkCredentials.Password
Now that we have those variables we can pass them on to the install of the Topshelf exe:
. $pathToServiceExe install -username `"$username`" -password `"$password`" --autostart
Notice the backticks (`) to ensure the double quotes are escaped.
End Quote

Related

How to run command as another user

I have a shell script that makes a few calls to Asterisk at some point and shows some output. Calling Asterisk is the first thing I have tried that seems not to work. I determined the user I setup to run the script didn't have the permissions to run Asterisk, so I looked at ways to run it as root which would get around that (the only other user on the system).
I tried using su with no luck. For the past two hours, I've been messing with sudo and sudoers and not been able to get it working.
For example, here is some code called in my script, run by the user com:
printf "\n"
calls=`sudo "asterisk -rx 'core show channels'" | grep "active call"`
lastinboundcaller=`cat /var/log/asterisk/lastcaller.txt`
printf '%s\n' "Current Call Count: $calls"
printf '%s\n' "Last Inbound Caller: $lastinboundcaller"
Output:
[sudo] password for com:
sudo: asterisk -rx 'core show channels': command not found
Current Call Count:
Last Inbound Caller: Unknown
There are two problems here,
It's prompting for a password. Why it's prompting for the current user's password rather than the root password, I have no idea, but it shouldn't prompt for any password at all.
The Asterisk command asterisk -rx "command" is still not working — in other words, it's still failing to run the Asterisk shell, though it should have permission.
I tried updating my sudoers file and creating a new file in /etc/sudoers.d titled asterisk as well and putting my command in there.
My latest modification to that file was:
com ALL = (ALL:ALL) NOPASSWD: /usr/sbin/asterisk
Before that, I tried:
com ALL = (root) NOPASSWD: /usr/sbin/asterisk
My understanding is this should allow the user com to execute asterisk as sudo without a password. Clearly, something is not working.
I have followed the answers to numerous similar SO posts, like:
Use sudo without password INSIDE a script
https://unix.stackexchange.com/questions/18877/what-is-the-proper-sudoers-syntax-to-add-a-user
Unfortunately, despite following all the answers I've been able to find on this issue, none have worked for me.
Can anyone point me in the right direction here or suggest an alternative? I already consulted a Linux expert and this seems to be the right approach. This is all super easy to do in Windows and I'm surprised it's all this convoluted in Linux.
Don't quote the argument to sudo. It expects the first argument to be the name of the command, so it thinks the whole command line is the program name.
It should be
calls=`sudo asterisk -rx 'core show channels' | grep "active call"`
Why it's prompting for the current user's password rather than the root password, I have no idea, but it shouldn't prompt for any password at all.
That's how sudo works. It prompts for the current user's password, and checks /etc/sudoers to see if they're allowed to run the command. You're thinking of su, which prompts for the root password.

Cannot logon windows after changing password via net user newuser command

I was trying to change my windows password via command:
net user Adminstrator newpassword
However, I accidentally did this
net user Administrator "newpassword"
There is no special character in the password
Now I am not able to logon my Administrator account via either newpassword or "newpassword"
Please help.
Thank you.
Best regards,
Apparently it is an issue for Windows password change command, that you cannot put double quotes in the password, and if you did, the command will be executed successfully but nobody knows what the password is.
I resolved this issue via resetting admin password to default following the instruction at:
http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ResettingAdminPassword_EC2Config.html
I was lucky I am having this issue with AWS EC2 instance, otherwise I won't be able to resolve like that.
It happens when using escape sequence in command prompt
Run the following command in command prompt with administrator privilege
echo EnteredPassword >> C:\ActualPassword.txt
EnteredPassword is the password that you entered in the command prompt
And your actual password will be available in C:\ActualPassword.txt

Export Windows credentials with CMDKEY or similar batch equivalent

I am looking to export Windows credentials to another Windows machine. So far in Windows, all I have is the GUI option to backup / restore, but no options in CMDKEY to backup / restore all Windows credentials. Is there a command line equivalent to the following?
First of all, from a security stand point, having an inbuilt command line utility to export security credentials can lead to them being compromised. Someone who gains unauthorized access to your machine remotely to run shell commands or install an program that executes to dump your credentials and then send them somewhere else can do that. That said, I have not come across any inbuilt tools to do that. BUT, that doesn't mean you can't.
cmdkey is a tool that you can use to manage credentials from the command line.
There is a PowerShell tool by Microsoft called PowerShell Credentials Manager that shows all your credentials. You can then pipe that to an output file.
https://gallery.technet.microsoft.com/scriptcenter/PowerShell-Credentials-d44c3cde
Show all: CredMan.ps1 -ShowCred | Out-File **your-file**
Add New
.\CredMan.ps1 -AddCred -Target 'DemoTgt' -User 'DemoUser' -Pass 'DemoPass'
Remove .CredMan.ps1 -RemCred **cred name**
Read on some ways an attacker can compromise your system in blog post Dumping Windows Credentials.

Cannot pass password to sudo su - username using Powershell + plink.exe combination

Project context
I'm currently working in a very restrictive work environment. I know about all the good practices involving SSH: keys, ssh-agent, etc., unfortunately for various reasons I wouldn't really want to go into right now I'm forced to worked within the very strict environment provided.
I realize the "quality" of the work environment and if you read further please try to treat this question as a purely technical question and maybe even a technical challenge (basically don't ask about the politics behind the current situation :) ) .
Context:
A Windows VM with a very limited set of tools available. Limited to no access to the Internet and no approval for installing third-party anythings (extra tools, libraries, etc.).
So, the things I have available are:
Putty (which includes plink.exe as a command line SSH client)
Powershell 2.0
Using these tools I'd like to automate a very restrictive SSH workflow that looks like this, most of the time:
password based-SSH login using personal account (no SSH keys allowed)
only sudo su - application_account to access the application account (no access to /etc/sudoers, no access to additional sudoers commands, I can only su to the application account)
scripts must prompt for password for each execution
I got a working automation setup with Python + Fabric + prompt automation that did almost everything I wanted. Unfortunately for various reasons this setup is in a "gray area" and it might be blacklisted.
So now I'm trying to use only the tools available within the VM, currently Powershell + plink.exe. Unfortunately I can't seem to get to the final step of the automation, running sudo su - application_account.
I've tried everything I could think of, almost everything based on using System.Diagnostics.Process to launch plink.exe and then:
Either redirect stdin and send a series of commands, including responding to prompts like this:
$process.StandardInput.WriteLine($password)
Or send the password using heredocs:
a)
# One-line heredoc.
echo $password | sudo su - application_account<<< ls
b)
# Multi-line heredoc.
echo $password | sudo -S su - <<END
ls
END
c) or almost any combination involving sudo parameters such as -k, -S, heredoc formats, etc.
Or use the -m parameter of plink.exe to create a file containing the list of commands including a sudo su heredoc execution.
Or trying to use event-based inputs.
...
And many, many others.
I either can't control the process if I redirect all input/output (if I redirect both the process locks and debugging is really hard since I don't have a ton of tools on the VM and I can't see why it's locking).
Or sudo plainly just doesn't accept the password input, as the final deathblow step.
Is it really impossible to control plink.exe in such a restrictive context? I have to note that without access to the application account automation is impossible (i.e. simple personal SSH user automation was achieved long time ago and is not enough).
I'm interested in possible solutions using Powershell or any other tools that come directly with Windows on in advice debugging the setup. Basically how could I see why the process deadlocks. Or any idea, really, that does not involve changing administrative settings anywhere or installing extra tools/apps/libraries.
To add insult to injury, my password contains special characters which the shell doesn't seem to like (I think). Any recommendations for escaping them in Powershell/bash?
Edit - code I'm using right now:
$procInfo = New-Object System.Diagnostics.ProcessStartInfo
$procInfo.RedirectStandardInput = $true
$procInfo.FileName="C:\Tools\PuTTY\plink.exe"
$procInfo.Arguments = "-t $sshHost"
$procInfo.UseShellExecute = $false
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $procInfo
[void]$process.Start()
Start-Sleep -m 1000
$process.StandardInput.WriteLine($sshUser)
Start-Sleep -m 1000
$process.StandardInput.WriteLine($password)
Start-Sleep -m 1000
$process.StandardInput.WriteLine("sudo su - $applicationUser")
Start-Sleep -m 5000
$process.StandardInput.WriteLine($password)
It is probably the Windows EOL sequence, that the WriteLine emits, that does not play nicely with the sudo. Try using the CR (*nix EOL) explicitly:
$process.StandardInput.Write("sudo su - $applicationUser`n")
$process.StandardInput.Write(($password + "`n"))

How can i run a sudo command in Bash script?

I want to run the following sample bash script which needs sudo password for a command
#!/bin/bash
kinit #needs sudo password
vi hello.txt
while running the above script it is asking for password.
How can i pass the username and password in the command itself or is there any better way i can skip passing my password in the script ?
TL;DR
You can't—at least, not the way you think.
Longer Answer with Alternatives
You have a couple of options:
Authenticate interactively with sudo before running your script, e.g. sudo -v. The credentials will be temporarily cached, giving you time to run your script.
Add a specific command such as /usr/lib/klibc/bin/kinit to your sudoers file with the NOPASSWD option. See sudoers(5) and and visudo(8) for syntax.
Use gksudo(1) or kdesu(1) with the appropriate keyring to cache your credentials if you're using a desktop environment.
One or more of these will definitely get you where you want to go—just not the way you wanted to get there.
So if you have access to your full system, you can change your sudoers file to allow certain sudo commands to be run w/o a password.
On the command line run visudo
Find your user and change the line to look something like this:
pi ALL=(ALL) NOPASSWD: /path/to/kinit, /path/to/another/command
That should do it. Give it another shot!
Hope that helps
You shouldn't pass username and password. This is not secure and it is not going to work if the password is changed.
You can use this:
gksudo kinit # This is going to open a dialog asking for the password.
#sudo kinit # or this if you want to type your password in the terminal
vi hello.txt
Or you can run your script under root. But note that vi is going to be ran as root as well, which means that it will probably create files that belong to root, that might be not what you want.

Resources