Start And Stop Windows Service remotely using PSEXEC - windows-services

How to start and and stop a Windows service remotely using PSEXEC? Preferably the syntax to write I tried the cmdlet given below
psexec \\Server -u Administrator -p Somepassword ServiceName

PSService on SysInternals is specifically for remotely controlling services::`
psservice [\\computer [-u username] [-p password]] <command> <options>
where:
query Displays the status of a service.
config Displays the configuration of a service.
setconfig Sets the start type (disabled, auto, demand) of a service.
start Starts a service.
stop Stops a service.
restart Stops and then restarts a service.
pause Pauses a service
cont Resumes a paused service.
depend Lists the services dependent on the one specified.
security Dumps the service's security descriptor.
find Searches the network for the specified service.
\\computer Targets the NT/Win2K system specified.
Include the -u switch with a username and password to login to the remote system if your security credentials do not permit you to obtain performance counter information from the remote system. If you specify the -u option, but not a password with the -p option, PsService will prompt you to enter the password and will not echo it to the screen.

Another alternative to psexec is sc. You can use sc to start or stop services remotely:
sc \\server start ServiceName
sc \\server stop ServiceName
There is no "login" information, so maybe you need to execute
net use \\server password /USER:user
before executing sc command.
One advantage over psexec is that no console window shows in the remote machine.

I can't test this right now, but it ought to be:
psexec \\server -u username -p password net start ArgusCommunityWorkerService
and
psexec \\server -u username -p password net stop ArgusCommunityWorkerService

Using PSEXEC
The below batch file will let you stop and start services on multiple remote machines. Create Computers.txt file in the same directory where the batch file runs from and list PC hostnames one per line.
#echo off
TITLE Manage Services v1.0
SET suffix=%date:~-4,4%%date:~-10,2%%date:~-7,2%_%time:~0,2%%time:~3,2%%time:~6,2%
SET /P username=Enter your admin username:
set "psCommand=powershell -Command "$pword = read-host 'Enter Password' -AsSecureString ; ^
$BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)""
for /f "usebackq delims=" %%p in (`%psCommand%`) do set password=%%p
:service
SET /P servicename=Enter service name:
:begin
echo ========================================
echo 1) Start
echo 2) Stop
echo 3) Choose another service
echo ========================================
ECHO.
set /p op=Select an option:
if "%op%"=="1" SET action=start
if "%op%"=="2" SET action=stop
if "%op%"=="3" goto service
psexec "\\#%~dp0Computers.txt" -u %username% -p %password% -h net %action% %servicename% >>%suffix%.log 2>&1
pause
cls
goto begin
Using PowerShell
# Point the script to the text file with remote computers
$RemoteComputers = Get-Content "$PSScriptRoot\Computers.txt"
# sets service name
$Service = "uvnc_service"
# Counter for progress bar
$counter = 0
ForEach ($Computer in $RemoteComputers) {
$counter++
Try
{
Write-Progress -Activity 'Processing computers' -CurrentOperation $Computer -PercentComplete (($counter / $RemoteComputers.count) * 100)
Start-Sleep -Milliseconds 200
Get-Service -Name $Service -ComputerName $Computer | Restart-Service -Force -ErrorAction Stop
Write-Output "$(Get-Date -format "yyyy-MM-dd hh:mm:ss"),$computer" | out-file -append -filepath "$PSScriptRoot\success.log"
}
Catch
{
Write-Output "$(Get-Date -format "yyyy-MM-dd hh:mm:ss"),$computer" | out-file -append -filepath "$PSScriptRoot\failed.log"
}
}

Refering to Microsoft, an alternative is using psservice, which is part of pstools downloadable under following link:
Download PsTools (2.7 MB)
If someone needs to
Start, stop, restart, etc... a Windows Service remotely
as mentioned in the official reference from Microsoft, the appropriate command using the provided executable
PsService.exe
could be something similar to following (Case 1 and case 2), if you are using Windows PowerShell
Case 1: User, who will perform the wished command (e.g. restart) after signed in, is remote computer user with appropriate rights
.\PsService.exe \\Remote-ComputerName-OR-ServerName -u
'RemoteComputerName-OR-ServerName\Remote-ComputerUser' -p
'Remote-ComputerUser-Password' restart ServiceName
Case 2: User, who will perform the wished command (e.g. restart) after signed in, is domain superuser (e.g. DomainAdministrator)
.\PsService.exe \\Remote-ComputerName-OR-ServerName -u
'DomainShortName\DomainAdministrator' -p
'DomainAdministrator-Password' restart ServiceName
PS: Notice in this case the single quoted parameter values for
username
-u
and password
-p
for complex password and/or username
That's it, your command should get executed smoothly, just be patient!

Related

Prevent systemctl restart mosquitto.service from resetting Dynamic Security

I'm trying out the Dynamic Security module for mosquitto and everything seems to work fine as long as I never systemctl restart mosquitto.service. After install mosquitto and enabling the Dynamic Security module, I ran these two commands:
mosquitto_ctrl dynsec init /etc/mosquitto/dynamic-security.json steve
systemctl restart mosquitto.service
Then I was able to create a user, role, subscribe and publish to a topic like this:
mosquitto_ctrl -u steve -P Pass1234 dynsec createClient john0
mosquitto_ctrl -u steve -P Pass1234 dynsec createRole role0
mosquitto_ctrl -u steve -P Pass1234 dynsec addClientRole john0 role0 1
mosquitto_ctrl -u steve -P Pass1234 dynsec addRoleACL role0 publishClientSend pizza allow
mosquitto_ctrl -u steve -P Pass1234 dynsec addRoleACL role0 subscribeLiteral pizza allow
mosquitto_sub -u john0 -P Pass1234 -t pizza
# then open a second terminal window and do this:
mosquitto_pub -u john0 -P Pass1234 -t pizza -m 'hi'
# result is the word `hi` appears in the first/original terminal window
I can repeatedly publish and subscribe to topics with the john0 user on the pizza topic.
However, the moment I have to reboot my server or if I run a systemctl restart mosquitto.service, then the john0 client no longer exists.
How do I prevent the john0 user and all the roles and access privileges from disappearing after a systemctl restart mosquitto.service?
EDIT
Here's my /etc/mosquitto/mosquitto.conf
persistence true
persistence_location /var/lib/mosquitto/
log_dest file /var/log/mosquitto/mosquitto.log
include_dir /etc/mosquitto/conf.d
allow_anonymous false
per_listener_settings false
plugin /usr/lib/x86_64-linux-gnu/mosquitto_dynamic_security.so
plugin_opt_config_file /etc/mosquitto/dynamic-security.json
Also, in my /etc/mosquitto/dynamic-security.json, the only record taht exists is he one for steve. I do not see any other clients in the dynamic-security.json file.
EDIT
Also, it seems if I manually edit the /etc/mosquitto/dynamic-security.json, it does NOT immediately take effect. I need to run systemctl restart mosquitto.service in order for the changes to take effect.
So I guess now my question is specifically how do I add clients and roles such that it meets all these criteria:
I can add them during run time and they immediately take effect without a systemctl restart mosquitto.service.
After a systemctl restart mosquitto.service, that the clients and roles still exist (ie. they are not deleted)
Mosquitto was configured to store its dynamic security state in /etc/mosquitto/dynamic-security.json.
Unfortunately, /etc/mosquitto is frequently not writable by mosquitto, for security reasons. State is generally meant to be stored in /var/lib/mosquitto, which Mosquitto is able to write to.
To fix this, change the configuration to read:
plugin_opt_config_file /var/lib/mosquitto/dynamic-security.json
If you have an existing dynamic-security.json file in /etc/mosquitto you can move it to /var/lib/mosquitto and retain whatever is currently in it:
mv /etc/mosquitto/dynamic-security.json /var/lib/mosquitto
chown mosquitto /var/lib/mosquitto/dynamic-security.json
chmod 700 /var/lib/mosquitto/dynamic-security.json
The chown line makes sure it's owned by the user mosquitto - if you run mosquitto as a different user, change this line to be the user you run it as.
The chmod line makes sure that only the file's owner (and root) can read the file. Even though the passwords in the file are encrypted, we don't want to make it any easier than necessary for an attacker to access it.
This happens due to permission issues for mosquitto
You can just simply do
chown mosquitto /etc/mosquitto/dynamic-security.json
After this when you use mosquitto_ctrl commands.
It will be visible in the json file.

Getting error .\config.cmd : VS30063: You are not authorized to access https://

Running on premise Azure DevOps server. Trying to setup agent for pipeline.
Error in log file: [2021-12-02 17:21:20Z ERR Terminal] WRITE ERROR: VS30063: You are not authorized to access https://
Have a Basic authentication setup. Have users granted access to site.
Here is the command line in powershell.
\config.cmd --unattended --url https://FQDN_Server/Bill_Test/ --auth negotiate --userName Domain\User --password PASSWORD --token h6mgqztjnx5zbam7rmmdo5gnb4gz3xndvwyqotofxuycx4x74uha --pool SQLServer --agent devAgent --acceptTeeEula
Can you try below steps:
Download the release agent zip file and place it inside the downloads folder of release machine
Then execute below 2 PS scripts to extract in c drive
PS C:> mkdir agent ; cd agent
Add-Type -AssemblyName System.IO.Compression.FileSystem ; [System.IO.Compression.ZipFile]::ExtractToDirectory("$HOME\Downloads\vsts-agent-win-x64-2.153.1.zip", "$PWD")
Point to c drive agent folder and execute below command.
.\config.cmd --deploymentpool --deploymentpoolname "YOUR_DEP_POOL_NAME" --agent $env:COMPUTERNAME --runasservice --work '_work' --url 'https://YOUR_TFS_SERVER/';
While installing when it prompts for authentication type, enter as Negotiate. Then provide username and password

Unable to create admin user in InfluxDB

I have to create an ADMIN role user of InfluxDB at the time of initializing docker container. My script is:
echo "=> Starting InfluxDB ..."
exec influxd
#wait for the startup of influxdb
RET=1
while [[ RET -ne 0 ]]; do
echo "=> Waiting for confirmation of InfluxDB service startup ..."
sleep 3
curl -k ${API_URL}/ping 2> /dev/null
RET=$?
done
echo ""
RUN su- curl -XPOST 'http://localhost:8086/query' --data-urlencode "q=CREATE USER admin WITH PASSWORD 'password' WITH ALL PRIVILEGES"
Above script does create the user but issue is that the role of the user is not set to ADMIN. I need a user with ADMIN role. What can be the possible issue here ? Any help would be much appreciated
Use env variables (applicable for official InfluxDB docker image https://hub.docker.com/_/influxdb):
INFLUXDB_ADMIN_USER
The name of the admin user to be created. If this is unset, no admin user is created.
INFLUXDB_ADMIN_PASSWORD
The password for the admin user configured with INFLUXDB_ADMIN_USER. If this is unset, a random password is generated and printed to standard out.

How to know if my program is completely started inside my docker with compose

In my CI chain I execute end-to-end tests after a "docker-compose up". Unfortunately my tests often fail because even if the containers are properly started, the programs contained in my containers are not.
Is there an elegant way to verify that my setup is completely started before running my tests ?
You could poll the required services to confirm they are responding before running the tests.
curl has inbuilt retry logic or it's fairly trivial to build retry logic around some other type of service test.
#!/bin/bash
await(){
local url=${1}
local seconds=${2:-30}
curl --max-time 5 --retry 60 --retry-delay 1 \
--retry-max-time ${seconds} "${url}" \
|| exit 1
}
docker-compose up -d
await http://container_ms1:3000
await http://container_ms2:3000
run-ze-tests
The alternate to polling is an event based system.
If all your services push notifications to an external service, scaeda gave the example of a log file or you could use something like Amazon SNS. Your services emit a "started" event. Then you can subscribe to those events and run whatever you need once everything has started.
Docker 1.12 did add the HEALTHCHECK build command. Maybe this is available via Docker Events?
If you have control over the docker engine in your CI setup you could execute docker logs [Container_Name] and read out the last line which could be emitted by your application.
RESULT=$(docker logs [Container_Name] 2>&1 | grep [Search_String])
logs output example:
Agent pid 13
Enter passphrase (empty for no passphrase): Enter same passphrase again: Identity added: id_rsa (id_rsa)
#host SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2.6
#host SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2.6
parse specific line:
RESULT=$(docker logs ssh_jenkins_test 2>&1 | grep Enter)
result:
Enter passphrase (empty for no passphrase): Enter same passphrase again: Identity added: id_rsa (id_rsa)

Nagios Percona Monitoring Plugin

I was reading a blog post on Percona Monitoring Plugins and how you can somehow monitor a Galera cluster using pmp-check-mysql-status plugin. Below is the link to the blog demonstrating that:
https://www.percona.com/blog/2013/10/31/percona-xtradb-cluster-galera-with-percona-monitoring-plugins/
The commands in this tutorial are run on the command line. I wish to try these commands in a Nagios .cfg file e.g, monitor.cfg. How do i write the services for the commands used in this tutorial?
This was my attempt and i cannot figure out what the best parameters to use for check_command on the service. I am suspecting that where the problem is.
So inside my /etc/nagios3/conf.d/monitor.cfg file, i have the following:
define host{
use generic-host
host_name percona-server
alias percona
address 127.0.0.1
}
## Check for a Primary Cluster
define command{
command_name check_mysql_status
command_line /usr/lib/nagios/plugins/pmp-check-
mysql-status -x wsrep_cluster_status -C == -T str -c non-Primary
}
define service{
use generic-service
hostgroup_name mysql-servers
service_description Cluster
check_command pmp-check-mysql-
status!wsrep_cluster_status!==!str!non-Primary
}
When i run the command Nagios and go to monitor it, i get this message in the Nagios dashboard:
status: UNKNOWN; /usr/lib/nagios/plugins/pmp-check-mysql-status: 31:
shift: can't shift that many
You verified that:
/usr/lib/nagios/plugins/pmp-check-mysql-status -x wsrep_cluster_status -C == -T str -c non-Primary
works fine on command line on the target host? I suspect there's a shell escape issue with the ==
Does this work well for you? /usr/lib64/nagios/plugins/pmp-check-mysql-status -x wsrep_flow_control_paused -w 0.1 -c 0.9

Resources