How to execute linux service from java code

Viewed 840

I have a service in linux called appSevice, when I start/stop with these cmd, it works :

sudo systemctl start appSevice.service;
sudo systemctl stop  appSevice.service;

but the problem when I tried to execute these from JAVA code, I tried form exemple :

Runtime.getRuntime().exec("sudo systemctl stop appService.service");

but it didnt work, I can that the service is always running, any suggestions please to resolve this problem ?

service :

[Service]
Type=simple
ExecStart=/opt/soft/v1/launchAppService.ksh start
User=Jms-User
Restart=on-abort
2 Answers

Steps to help you execute a system command via java program:

  1. create user and give him rights to execute systemctl command, see this thread allowing user to run systemctl/systemd services without password

  2. execute your java program using this user

  3. your java code should be: Runtime.getRuntime().exec(new String[]{"systemctl", "stop", "appService.service"});

the first argument is the command to execute, others are the arguments

There is one way also. Create new user with LimitedRoot capabilities and use VISUDO to allow the user to run systemctl/systemd services without entering a password.

Example:

%LimitedRootUser ALL=NOPASSWD: /bin/systemctl restart appService.service
Related