Windows server restart service



The post Monitoring Windows services covered how to remotely check a service status (running, stopped) using WMI, a powerful framework for fetching info from Windows based systems.

All of us managing monitoring systems know how important is providing proactive capabilities to the system in order to fix simple problems as a first step once an incidence is detected. Maybe the best example might be an stopped Windows service: It might be desirable that the monitoring system tried to restart it and, once a given number of unsuccessful tries were made, it performed a notification to the administrators in order to manage the problem in a more human-like way.

Sadly WMI is not so useful when trying to being interactive with the remote system. If not using sql-like syntax, it’s is possible calling a local script when a given condition is true (for instance when a service is stopped) but the Linux wmi client (wmic) only support sql-like queries. Moreover, even if sql queries supported running commands under certain circumstances, a remote script might exist on the Windows server side in order to be run (whose existence migth be a problem when dealing with strict remote server administrators).

Let’s dance

SAMBA is the Linux implementation of the Windows SMB protocol that allows, among others, supporting Remote Procedure Call transport (RPC over SMB)… and obviously RPC allow us remotely calling Windows procedures, what seems a good solution for our purpose.

samba-client is a package available for different platforms (it is called smbclient in Debian-like plataforms) that groups different utilities for interacting from Linux hosts with remote SMB compatible systems (as Windows servers). One of these utilities is net, that is meant to work just like the net utility available for Windows and DOS.

On a Windows system, we can restart an stopped service calling net in this way:

net start my_windows_service

Using the samba net utility, we can do the same action from a remote Linux system in this way:

net rpc service start my_windows_service \

-I 192.168.0.64 \

-U myDomain/jdoe%jdoe_password

The only difference is that, while in Windows you can use both long (quoting it) or short service name, in Linux you can use just the short service name.


The previous command started a service called my_windows_service on a remote Windows server with address 192.168.0.64 using the privileges of the user jdoe (authenticated with password jdoe_password) belonging to the Active Directory domain myDomain. It is possible doing it using a local user if the domain name (and the slash) is omitted:

net rpc service start my_windows_service \

-I 192.168.0.64 \

-U jdoe%jdoe_password

Finally, using net is possible checking if a given service is running, something useful for validating that a restarted service operation succeeds:

net rpc service status my_windows_service \

-I 192.168.0.64 \

-U myDomain/jdoe%jdoe_password

In practice

Let’s assume we are managing a Nagios Core based system that monitors the status of some services running on remote Windows servers. The way to do it was covered in the post Monitoring Windows services.

Now we want to give our monitoring system proactive capabilities in this way: Once a monitored windows service is detected as stopped, our monitoring system must restart it for a given number of tries and, if not achieved, stop doing it and notifying the incidence to the defined contacts (or contactgroup members).

That can be achieved by defining an event handler bound to the service check. Since an event handler executes a command every time a service or host is in a soft state and the first time it goes to a hard (OK or non-OK) state, we will create a command that restarts the Windows service if the Nagios service check is in a non-OK, soft state. Since we can define how many checks can be run before going to a hard state via the service property max_check_attempts, we can set how many service restart tries can be performed before going to a hard state and then running a notification. Let’s see it step by step:

1.- Create an script for restarting a windows service if a nagios service is in a soft, non-ok state. Name it ‘restart_win-service’ and save it in the Nagios libexec directory (with the right permissions for being executed from Nagios):

#!/bin/sh

#

# restart_win-service

# Restarts a remote windows service if nagios service is 

# in a non ok, soft state

# Arguments:  sevice_status service_status_type user_id 

#             server_address service_name  

#

if [ «$1» != ‘OK’ -a «$2» == ‘SOFT’ ]; then

# We are in a soft, non OK status: 

# Restart the service

net rpc service start $5 -I $4 -U $3 > /dev/null 2> /dev/null

fi

2.- Define a Nagios command representing the previous script:

define command{

command_name restart_win_service

command_line $USER1$/restart_win-service $SERVICESTATE$ $SERVICESTATETYPE$ $ARG1$ $HOSTADDRESS$ $ARG2$

}

3.- Configure the service for using the command restart_win_service as event handler and running it for three times before notifying the problem

define service {

enable_event_handler 1

event_handler restart_win_service!myDomain/jdoe%jdoe_password!my_windows_service

max_check_attempts 3

}

Is it possible to enable/disable services using similar syntax? I don’t know much about Linux commands but this is definitely helpful.

protix
·
775 weeks and 6 days ago

It says failed to start service, but it does start the service

This is handy when the service in question is already enabled on the windows machine.
Any idea of how to Enable a Disabled Service so you *can* start it?

net rpc service list -I <ADDRESS> -U <USERNAME%PASSWORD>
Get a list of running services

I know this is REALLY old, but man, after myriad attempts involving wmic and winexe, this solved my problem completely (and rather simply/elegantly.) Specifically useful for me to disable a service on a Windows app server while updating/refreshing a test/dev database on a Linux box. Thank you so much. (Note: on RHEL, the net command is part of samba-common-tools in yum.)

Interesting PG SLOT promotions, don’t miss out on what we have prepared for you. Modern ?????????online, attractive to play, with huge rewards within the game. playable on mobile

Pgslot vs slotxo , what is the difference between these two game camps? What are some interesting games? Let’s see. Collision from 2 online slot game camps. two famous camps Pounding on our websitePG-SLOT.GAME

Ij start canon is the website where you can find and download Canon printer drivers. Installing the correct drivers ensures that your printer functions properly with your computer or device. By visiting ij.start.canon and following the instructions provided, you can easily install the necessary drivers for your Canon printer.
ij.start.canon is the website provided by Canon for users to set up, install, and manage their Canon printers and multifunction devices. It serves as a centralized platform to access various resources, tools, and services related to Canon printers.

alaxa09
·
46 weeks and 1 day ago

ij.start.canon is the website provided by Canon for users to set up, configure, and manage their Canon printers and multifunction devices. It’s a dedicated website where users can find various resources and tools tailored to their Canon printer model.
ij.start.canon is the website provided by Canon to assist users with the setup and management of their Canon printers and multifunction devices. It serves as a central hub for accessing various resources, tools, and services related to Canon printers.

alaxa09
·
46 weeks and 1 day ago

First, create a free account on Credit karma website or via their app in order to view your credit score.
Using Credit karma to check your credit score is an easy process. Credit Karma provides this service so that you can take control of your finances and move in the direction of improvement. It’s a simple, cost-free way to be informed about your credit status.

alaxa09
·
46 weeks and 1 day ago

Credit Karma is a website that offers free credit reports, credit monitoring, and tailored financial advice to assist customers in managing their money.Visit Credit karma webpage.
A easy approach to check your credit score for free is to use Credit karma. You may obtain your credit score from TransUnion and Equifax, as well as credit monitoring and customized financial advice, by creating an account with Credit Karma. It’s an easy-to-use yet practical tool for monitoring your credit health and comprehending the variables that influence your creditworthiness.

alaxa09
·
46 weeks and 1 day ago

Free access to your credit ratings from Equifax and TransUnion, which are updated on a regular basis, is offered by Credit Karma. This enables you to monitor your credit status without incurring any fees. Visit Credit karma website and select «Sign Up.» Enter your name, email address, birthdate, Social Security number, and other personal data.
A free online resource that provides credit reports, scores, and tailored financial advice is called Credit karma . It assists customers in keeping tabs on their credit situation and making wise financial choices.

alaxa09
·
46 weeks and 1 day ago

Credit reports, credit scores, and other financial tools and services are all freely accessible through Credit karma , a personal finance organization. It gives people information on the state of their credit and suggestions for enhancing their financial security. These are some of Credit Karma’s salient characteristics.
With the aim of managing and enhancing their financial well-being, Credit karma offers its members free access to financial tools, credit monitoring, credit ratings, and instructional materials.

alaxa09
·
46 weeks and 1 day ago

To access Account Hub, simply go to taxslayerpro login/my account and enter your username and password. From there, you can manage your business, apply for bank products, update your company’s information, and much more.
An all-inclusive tax preparation program is TaxSlayer Pro. There are several advantages to logging into your taxslayerpro login/my account , particularly if you are a tax professional or a person handling tax-related duties.

alaxa09
·
46 weeks and 1 day ago

TaxSlayer is a business that provides tax preparation services and software to corporations, tax professionals, and individuals. A secure login gateway, taxslayerpro login/my account , is provided by TaxSlayer Pro.
Our platform is made to make tax preparation easier for you and to help you save time and energy. Put your trust in the taxslayerpro account for all of your filing requirements. You can have confidence knowing that your private data is secure. Create a more efficient tax preparation procedure by using taxslayerpro login/my account right now.
TaxSlayer is a firm that provides tax preparation software. Their solutions are tailored for tax professionals, who can visit their website to access their taxslayerpro login/my account . This allows tax professionals to efficiently prepare and file tax returns for their clients.

alaxa09
·
46 weeks and 1 day ago

With a reputation for dependability and safety, American airlines book ticket offers dependable flight travel to locations all over the world. with a dedication to client satisfaction and a history of excellence. You can rely on American Airlines to get you there in comfort and on schedule whether you’re traveling for work or pleasure.
The term American airlines book ticket describes a platform or service that makes it easier to book tickets, particularly with American Airlines. This could be displayed as a welcome message on an airline’s website, mobile application, or marketing collateral intended to assist passengers in making airline reservations. Its objective is to welcome visitors and inform them that they have come to the right place to start the American Airlines booking process.

alaxa09
·
46 weeks and 1 day ago

To conveniently book your flight, visit American airlines book ticket on your phone. Book your trip, choose a flight, enter passenger details, safely finish the payment process, and get a booking confirmation on your mobile right away.
With a reputation for dependability and safety, American airlines book ticket offers flights to locations all over the world. We aim to make every flight experience remarkable, building on our tradition of excellence and dedication to client pleasure. You can depend on American Airlines to deliver you there in comfort and on schedule whether you’re traveling for business or pleasure.

alaxa09
·
46 weeks and 1 day ago

You can quickly search for and reserve flights online using Priceline flights . Enter your trip information, evaluate airfares offered by different airlines, choose a flight, input passenger data, complete payment, and get an email confirming your reservation.
Priceline flights flight booking platform is easy to use and offers low costs, making it a popular choice for travelers. You can easily locate and contrast different flight alternatives, apply preferences filters, and take advantage of sales and promos.

alaxa09
·
46 weeks and 1 day ago

expedia flights are programs that allow Dell hardware—such as laptops and printers—to interact with the operating system of your computer and guarantee proper operation.»
«Updating expedia flights is crucial for optimal performance, fixing bugs, and ensuring compatibility with the latest operating systems, enhancing the overall functionality of your Dell devices.»

alaxa09
·
46 weeks and 1 day ago

Updating your Dell drivers improves your device’s security, compatibility, and performance. It fixes problems, lessens system crashes, and enhances connectivity. Regular updates ensure that your hardware is running the most recent software. Update your Dell device to obtain the best possible performance.
You may get Dell drivers from our website. For Dell PCs, laptops, printers, and other devices, we have drivers. It’s easy to find and download the right drivers for your particular device with our website. With our most recent drivers, you can wave goodbye to compatibility problems and hello to better performance. Come see us right now to get the most out of your Dell gadget!»

alaxa09
·
46 weeks and 1 day ago

ticketmaster is a well-known international marketplace that makes it simple to purchase tickets for live entertainment events like concerts, sporting events, and more.
The process of locating and organizing tickets bought through ticketmaster is made easier by our platform. You can quickly find and retrieve your event tickets from any location at any time. With Ticketmaster, bid adieu to anxiety surrounding tickets and hello to flawless event experiences.

alaxa09
·
46 weeks and 1 day ago

ticketmaster manages ticket sales, delivery, and customer service, offering a comprehensive service to both event organizers and attendees. They work in tandem with organizers and venues to optimize the ticketing process, guaranteeing seamless transactions and access control at events across the globe.

alaxa09
·
46 weeks and 1 day ago

Была у меня как то проблема, везде используется linux но вот одна программа
работала только на Windows а именно Litemanager NoIP сервер, держать ради нее отдельную Windows машину не хотелось, да и с учетом того что от программы нужно было только чтобы она «проксировала трафик» и позволяла подключится удаленно было решено перенести это на маленькую ubuntu машину где нибудь в облаке

Подготовка

в данном примере я использую Ubuntu 16.04

Устанавливаем Wine

sudo dpkg --add-architecture i386
wget -nc https://dl.winehq.org/wine-builds/winehq.key
sudo apt-key add winehq.key
sudo apt update
sudo apt-add-repository 'deb https://dl.winehq.org/wine-builds/ubuntu/ xenial main'
sudo apt-get install wine

Устанавливаем необходимое ПО:

sudo apt-get install fluxbox vnc4server xterm

Добавляем пользователя

добавляем пользователя vnc_server

sudo adduser vnc_server

переключаемся напользователя vnc_server

sudo su - vnc_server

Устанавливаем пароль

vncpasswd

Настраиваем VNC


vncserver -geometry 800x600 -depth 24
vncserver -kill :1

Настраиваем VNC для инеграции с fluxbox

echo "fluxbox &" >> ~/.vnc/xstartup

Выходим из vnc_server

exit


Добавляем сервис

sudo nano /etc/systemd/system/vnc_server.service

Копируем в этот файл:

[Unit]
Description=VNC Server
After=network.target

[Service]
Type=oneshot

ExecStart=/bin/sh -c "/usr/bin/vnc_server.sh start" &>/dev/null &
ExecStop=/bin/sh -c "/usr/bin/vnc_server.sh stop"

RemainAfterExit=yes

[Install]
WantedBy=multi-user.target

Сохраняем, перезапускаем systemctl

sudo systemctl daemon-reload

Создаем скрипт запуска vncserver имени пользователя vnc_server

sudo nano /usr/bin/vnc_server.sh

#!/bin/sh
export PATH="/usr/local/sbin:/sbin:/bin:/usr/sbin:/usr/bin"

start() {
    echo -n "Starting VNC: "
    su -c "vncserver :1 -geometry 800x600 -depth 24" vnc_server
    RETVAL=$?
    return $RETVAL
}

stop() {
    echo -n "Stopping VNC: "
    su -c "vncserver -kill :1 >/dev/null 2>&1" vnc_server
    RETVAL=$?
    return $RETVAL
}

case "$1" in
    start)
    start
    RETVAL=$?
    ;;
    stop)
    stop
    RETVAL=$?
    ;;
    restart)
    stop
    sleep 1
    start
    RETVAL=$?
    ;;
    condrestart)
    stop
    sleep 1
    start
    ;;
    status)
    status $service
    RETVAL=0
    ;;
    *)
    echo "Usage: $service {start|stop|restart|condrestart|status}"
    RETVAL=1
    ;;
esac

exit $RETVAL

Включаем серис при запуске:

sudo systemctl enable vnc_server

Делаем файл запускаемый:

sudo chmod 775 /usr/bin/vnc_server.sh

Перезагружаемся:

sudo reboot

Копируем программу на сервер

sudo mkdir  ~/lm

с машины пользователя

scp -r ~/lm пользовательssh@адрессервера:~/lm

Переносим в папку vnc_server


sudo mkdir /home/vnc_server/lm & sudo mv ~/lm/* /home/vnc_server/lm 
sudo chown vnc_server /home/vnc_server/lm/*

Подключаемся по VNC:

Используя люой vnc клиент подключаемся к серверу
правой кнопкой мыши запускаем Applications>Terminal Emulators>Xterm
и в водим

wine ~/lm/LMNoIpServer.exe

программа запущена.

Автозапуск программы при старте системы:

sudo nano /home/vnc_server/.fluxbox/startup

и перед exec fluxbox добавляем

wine ~/lm/LMNoIpServer.exe

хочу так же добавить что LMNoIpServer была выбрана в качестве примера


Monday, April 2nd, 2012

I had a request on how to restart the three LSF services from a script. The person worked on the farm team and did not relish the idea of using remote desktop or VNC.

I thought about a Powershell script or using a batch script to run the PsService from sysinternals. It looked simple as the command is as follows:

psservice \\<computer> -u <domain\username> -p password stop service <service name>

psservice \\<computer> -u <domain\username> -p password start service <service name>

I contacted the user and asked a couple more questions and learned she wanted to run the script from Linux. Of course this required a change in my approach as I like to keep things as simple as possible especially when a user will write their own script. I decided to abandon windows scripts and find away to see if Linux could handle this via the windows management interface.

Looking around the Net, I found a way I didn’t even consider. Simply install the Samba-Common. This offers the Net utility(or as close to it as possible) for the Linux host. The particular command in question is Net RPC service command:

To list out the services on a Windows computer:

net rpc service list -I <IP Address> -U “<domain\username>%<password>”

If you wish to use the command line; simply remove “%<password>” and you will be prompted for a password.

To start or stop a service; you would enter:

net rpc service {start|stop} <Service Name> -I <IP Address> -U “<domain\username>%<password>”

Again, if you wish to use the command line, simply remove “%<password>” and you will be prompted for a password.

The account used will have to have local admin privileges so if you decide to script it, secure the file to yourself since the password will be plain text.

Much as I would like to impress you with my great knowledge; there was a sense of urgency to the request so I went to the Net and I did get help from the following sites so credit must be given where credit is due.

LifeHacker

Commandlinefu

LyleBackenrorth

Posted in Linux, LSF, Windows

|

Tagged Linux, LSF, Windows Service

|

6 Expect script examples

September 01, 2014 20:48:32HaveFunInLinux Reading 7982

This document is:http://www.thegeekstuff.com/2010/10/expect-examples/

The Expect scripting language is used to automatically submit an input to the interactive program. It is easy to learn more than other scripting languages. System administrators and developers using an Expect script can easily automate redundant tasks. It works the working principle is waiting for a particular string and sends or responds to the corresponding string.

The following three excect commands are used for any process of automated interaction.

  • Send — Send string to process
  • EXPECT — Wait for a specific string from the process
  • Spawn — start command

Be sure to install the Expect package on your system because it will not be installed by default. Once installed, you will see the Expect interpreter «/ usr / bin / expect». In general, the Expect script file has an extension of .exp.

1. Expect «Hello World» example

The following EXPECT script waits for the specific string «Hello».When it finds it (after the user is entered), the «World» string will be sent as a response.

#!/usr/bin/expect
expect "hello"
send "world"

2. Waiting string timeout

By default, the waiting timeout is 10 seconds.If you don’t enter anything for the expect command, it will time out in 20 seconds.You can also change the timeout, as shown below.

#!/usr/bin/expect
set timeout 10
expect "hello"
send "world"

3. Automate user processes using the Expect

In EXPECTWith the help, you can automate the user’s process and get the desired output.For example, you can write test scripts to simplify project test cases using Expect.

The following example performs additional programs automation.

#!/usr/bin/expect

set timeout 20

spawn "./addition.pl"

expect "Enter the number1 :" { send "12\r" }
expect "Enter the number2 :" { send "23\r" }

interact

Execute the above script, the output is as follows.

$ ./user_proc.exp
spawn ./addition.pl
Enter the number1 : 12
Enter the number2 : 23
Result : 35

If the code you write doesn’t have an interact command, in this case, the script exits immediately after the string «23 \ r» is sent. InteractCommand execution control, processing the job of the Addtion process, and generates the expected result.

4. Match and mismatched content in the $ excect_out variable

When the string matches successfully, Expect returns, but it will store the matching string in $ expect_out (0, string).The previously received string plus matching string is stored in $ expect_out (buffer).The following example shows the value of the two variables.

#!/usr/bin/expect

set timeout 20

spawn "./hello.pl"

expect "hello"
send "no match : <$expect_out(buffer)> \n"
send "match :  <$expect_out(0,string)>\n"

interact

Hello.pl programs are only printed, as shown in the following figure.

#!/usr/bin/perl

print "Perl program\n";
print "hello world\n";

Executed as shown below.

$ ./match.exp
spawn ./hello.pl
Perl program
hello world
no match :  <Perl program

hello>
match :  <hello>

5. Automation Su Login to other user accounts

EXPECT allows you to pass your password from the program to the Linux login account instead of entering a password at the terminal. In the following program, the SU automatically logs in to the required account.

#!/usr/bin/expect

set timeout 20

set user [lindex $argv 0]

set password [lindex $argv 1]

spawn su $user

expect "Password:"

send "$password\r";

interact

The above Expect program is executed as shown below.

bala@localhost $ ./su.exp guest guest
spawn su guest
Password:
guest@localhost $

After running the above script, log in to the GUEST user account from the Bala User Account.

6. SSH login to another computer

The Expect program items given below can automatically log in to another machine from one computer SSH.

#!/usr/bin/expect

set timeout 20

set ip [lindex $argv 0]

set user [lindex $argv 1]

set password [lindex $argv 2]

spawn ssh "$user\@$ip"

expect "Password:"

send "$password\r";

interact

Execute the above Expect program as shown below.

guest@host1 $ ./ssh.exp 192.168.1.2 root password
spawn ssh [email protected]
Password:
Last login: Sat Oct  9 04:11:35 2010 from host1.geetkstuff.com
root@host2 #

4. The simple command of my side is

The script is:

#!/usr/bin/expect

set timeout 20

set ip [lindex $argv 0]

set user [lindex $argv 1]

set password [lindex $argv 2]

spawn ssh "$user\@$ip" "net start gscloud"

expect "password:"

send "$password\r";

interact

The command executed is:

./deploy/startwin 10.24.196.213 administrator Test1127?!


Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Ikev2 windows 7 маршруты
  • После ввода пароля долго загружается windows 10
  • Как установить jupiter notebook на windows 11
  • Open source calendar for windows
  • Почему нет звука в наушниках на компьютере windows 11