Skip to content

Instantly share code, notes, and snippets.

@azenla
Last active June 1, 2022 18:22
Show Gist options
  • Save azenla/39dc75468c631c7a82f8 to your computer and use it in GitHub Desktop.
Save azenla/39dc75468c631c7a82f8 to your computer and use it in GitHub Desktop.
systemctl API in Dart
import "dart:io";
class SystemCTL {
static const String CIRCLE = "\u25CF";
final bool useSudo;
SystemCTL({this.useSudo: false});
Future<bool> start(String service) async {
return (await run(["start", service])).exitCode == 0;
}
Future<bool> stop(String service) async {
return (await run(["stop", service])).exitCode == 0;
}
Future<bool> restart(String service) async {
return (await run(["restart", service])).exitCode == 0;
}
Future<bool> reload(String service) async {
return (await run(["reload", service])).exitCode == 0;
}
Future<bool> isActive(String service) async => (await run(["is-active", service])).exitCode == 0;
Future<bool> enable(String service) async {
return (await run(["enable", service])).exitCode == 0;
}
Future<String> cat(String service) async {
var result = await run(["cat", service]);
if (result.exitCode != 0) {
throw new Exception("No Service Found.");
}
return result.stdout;
}
Future<bool> disable(String service) async {
return (await run(["disable", service])).exitCode == 0;
}
Future<bool> isEnabled(String service) async => (await run(["is-enabled", service])).exitCode == 0;
Future<String> getStatus(String service) async {
return (await run(["is-active", service])).stdout.trim();
}
Future<Map<String, String>> getStatuses() async {
var result = await run(["list-units", "--no-pager", "--plain", "--all"]);
var out = result.stdout.trim();
return _parseUnitFilesList(out);
}
Future<bool> reloadDaemon() async {
return (await run(["daemon-reload"])).exitCode == 0;
}
Future<ProcessResult> run(List<String> args) {
return useSudo ? Process.run("sudo", ["systemctl"]..addAll(args)) : Process.run("systemctl", args);
}
Map<String, String> _parseUnitFilesList(String out) {
var lines = out.split("\n")..removeAt(0);
lines = lines.takeWhile((it) => !it.contains("Reflects whether the unit definition was properly loaded.")).map((it) {
return it.replaceAll("${CIRCLE}", "").trim();
}).toList();
lines.removeWhere((it) => it.trim().isEmpty || it.trim() == " ");
var map = {};
for (var line in lines) {
var parts = line.split(" ");
parts.removeWhere((it) => it.trim().isEmpty || it.trim() == " ");
var name = parts[0];
var status = parts[2];
map[name] = status;
}
return map;
}
}
@Stem-LG
Copy link

Stem-LG commented Jun 1, 2022

just what i needed for my project thx, but maybe you can add a comment with an example with the api capabilities and examples of how to use them ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment