Пример #1
0
        /// <summary>
        /// 获取systemctl里面有没有这个服务
        /// </summary>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public static Tuple <string, string, string> GetLinuxService(string serviceName, Action <string> logger = null)
        {
            try
            {
                var folder = string.Empty;
                var exeute = string.Empty;
                var result = CopyHelper.RunCommand($"sudo systemctl status {serviceName}.service", null, logger);
                if (!result)
                {
                    logger?.Invoke($"【Warn】【systemctl】 {serviceName} not exist");
                }
                else
                {
                    //说明存在这个服务的

                    //读出来 service 文件的内容 然后拿到他的 WorkingDirectory
                    var filePath = $"/etc/systemd/system/{serviceName}.service";
                    if (!File.Exists(filePath))
                    {
                        logger?.Invoke($"【Warn】【systemctl】 {filePath} not exist");
                        return(new Tuple <string, string, string>(null, folder, exeute));
                    }

                    var content = File.ReadAllLines(filePath);
                    //WorkingDirectory
                    foreach (var line in content)
                    {
                        if (string.IsNullOrEmpty(line))
                        {
                            continue;
                        }
                        logger?.Invoke($"【systemctl】 {line}");
                        if (line.StartsWith("WorkingDirectory"))
                        {
                            var folderArr = line.Split('=');
                            if (folderArr.Length != 2)
                            {
                                logger?.Invoke($"【Warn】【systemctl】 WorkingDirectory not found");
                                return(new Tuple <string, string, string>(null, folder, exeute));
                            }

                            folder = folderArr[1].Trim();
                        }

                        if (line.StartsWith("ExecStart"))
                        {
                            var folderArr = line.Split('=');
                            if (folderArr.Length != 2)
                            {
                                logger?.Invoke($"【Warn】【systemctl】 ExecStart not found");
                                return(new Tuple <string, string, string>(null, folder, exeute));
                            }

                            exeute = folderArr[1].Trim();
                        }
                    }
                }

                return(new Tuple <string, string, string>(null, folder, exeute));
            }
            catch (Exception e)
            {
                return(new Tuple <string, string, string>(e.Message, null, null));
            }
        }