private void RsyncChanged(object source, FileSystemEventArgs e) { ConsoleLogger.Log($"[watcher] change at {e.FullPath}"); var files = _directoriesModel.Where(_ => _.Source == e.FullPath).ToList(); var launcher = new CommandLauncher(); if (!files.Any()) { ConsoleLogger.Log($"[watcher] applying {e.FullPath} change"); var parent = Path.GetDirectoryName(e.FullPath); var dirs = _directoriesModel.Where(_ => _.Source == parent).ToList(); if (!dirs.Any()) { ConsoleLogger.Log("[watcher] nothing in db"); return; } foreach (var dir in dirs) { if (dir.Type == "directory") { var src = dir.Source.EndsWith("/") ? dir.Source : dir.Source + "/"; var dst = dir.Destination.EndsWith("/") ? dir.Destination : dir.Destination + "/"; ConsoleLogger.Log($"[watcher] rsync, src {src}; dst {dst};"); launcher.Launch("rsync", new Dictionary <string, string> { { "$source", src }, { "$destination", dst } }); } if (dir.Type == "file") { var src = dir.Source.EndsWith("/") ? dir.Source.TrimEnd('/') : dir.Source; var dst = dir.Destination.EndsWith("/") ? dir.Destination.TrimEnd('/') : dir.Destination; ConsoleLogger.Log($"[watcher] rsync, src {src}; dst {dst};"); launcher.Launch("rsync", new Dictionary <string, string> { { "$source", src }, { "$destination", dst } }); } } } foreach (var file in files) { if (file.Type == "directory") { var src = file.Source.EndsWith("/") ? file.Source : file.Source + "/"; var dst = file.Destination.EndsWith("/") ? file.Destination : file.Destination + "/"; ConsoleLogger.Log($"[watcher] rsync, src {src}; dst {dst};"); launcher.Launch("rsync", new Dictionary <string, string> { { "$source", src }, { "$destination", dst } }); } if (file.Type == "file") { var src = file.Source.EndsWith("/") ? file.Source.TrimEnd('/') : file.Source; var dst = file.Destination.EndsWith("/") ? file.Destination.TrimEnd('/') : file.Destination; ConsoleLogger.Log($"[watcher] rsync, src {src}; dst {dst};"); launcher.Launch("rsync", new Dictionary <string, string> { { "$source", src }, { "$destination", dst } }); } } }
public void ApplyHostRemoveModules() { Host = LoadHostModel(); var launcher = new CommandLauncher(); launcher.Launch(Host.RemoveModules.SetCmd, Host.RemoveModules.StoredValues); }
public AssetScanModule() { Get["/scan"] = x => { var settings = new NetscanConfiguration(); var set = settings.Get(); var values = set.Values.Where(_ => !string.IsNullOrEmpty(_.Label)) .Select(_ => new ScanModel { Name = _.Label, Subnet = set.Subnet + _.Number + ".0" }) .ToList(); var model = new PageAssetScanModel { Subnets = values }; return(JsonConvert.SerializeObject(model)); }; Get["/scan/{subnet}"] = x => { string subnet = x.subnet; if (string.IsNullOrEmpty(subnet)) { return(HttpStatusCode.BadRequest); } var launcher = new CommandLauncher(); var result = launcher.Launch("nmap-ip-sp", new Dictionary <string, string> { { "$subnet", subnet + "/24" } }).Skip(1).Reverse().Skip(1).Reverse(); return(Response.AsJson(result.OrderBy(_ => _))); }; }
public void ApplyTimezone() { Host = LoadHostModel(); var launcher = new CommandLauncher(); launcher.Launch(Host.Timezone.SetCmd, Host.Timezone.StoredValues); }
public void ApplyNtpdate() { Host = LoadHostModel(); var launcher = new CommandLauncher(); launcher.Launch(Host.NtpdateServer.SetCmd, Host.NtpdateServer.StoredValues); }
public AntdHost2Module() { Get["/host2"] = x => { const StringSplitOptions ssoree = StringSplitOptions.RemoveEmptyEntries; var hostnamectl = CommandLauncher.Launch("hostnamectl").ToList(); var model = new PageHost2Model { Host = Host2Configuration.Host, IconName = hostnamectl.FirstOrDefault(_ => _.Contains("Icon name:"))?.Split(new[] { ":" }, 2, ssoree)[1], MachineId = hostnamectl.FirstOrDefault(_ => _.Contains("Machine ID:"))?.Split(new[] { ":" }, 2, ssoree)[1], BootId = hostnamectl.FirstOrDefault(_ => _.Contains("Boot ID:"))?.Split(new[] { ":" }, 2, ssoree)[1], Virtualization = hostnamectl.FirstOrDefault(_ => _.Contains("Virtualization:"))?.Split(new[] { ":" }, 2, ssoree)[1], Os = hostnamectl.FirstOrDefault(_ => _.Contains("Operating System:"))?.Split(new[] { ":" }, 2, ssoree)[1], Kernel = hostnamectl.FirstOrDefault(_ => _.Contains("Kernel:"))?.Split(new[] { ":" }, 2, ssoree)[1], Architecture = hostnamectl.FirstOrDefault(_ => _.Contains("Architecture:"))?.Split(new[] { ":" }, 2, ssoree)[1] }; return(JsonConvert.SerializeObject(model)); }; Post["/host2/info"] = x => { string hostName = Request.Form.HostName; string hostChassis = Request.Form.HostChassis; string hostDeployment = Request.Form.HostDeployment; string hostLocation = Request.Form.HostLocation; string hostAliasPrimary = Request.Form.HostAliasPrimary; string internalDomainPrimary = Request.Form.InternalDomainPrimary; string externalDomainPrimary = Request.Form.ExternalDomainPrimary; string internalHostIpPrimary = Request.Form.InternalHostIpPrimary; string externalHostIpPrimary = Request.Form.ExternalHostIpPrimary; string internalNetPrimaryBits = Request.Form.InternalNetPrimaryBits; string externalNetPrimaryBits = Request.Form.ExternalNetPrimaryBits; string resolvNameserver = Request.Form.ResolvNameserver; string resolvDomain = Request.Form.ResolvDomain; string timezone = Request.Form.Timezone; string ntpdateServer = Request.Form.NtpdateServer; string cloud = Request.Form.Cloud; var old = Host2Configuration.Host; var vars = new Host2Model { HostName = hostName ?? old.HostName, HostChassis = hostChassis ?? old.HostChassis, HostDeployment = hostDeployment ?? old.HostDeployment, HostLocation = hostLocation ?? old.HostLocation, HostAliasPrimary = hostAliasPrimary ?? old.HostAliasPrimary, InternalDomainPrimary = internalDomainPrimary ?? old.InternalDomainPrimary, ExternalDomainPrimary = externalDomainPrimary ?? old.ExternalDomainPrimary, InternalHostIpPrimary = internalHostIpPrimary ?? old.InternalHostIpPrimary, ExternalHostIpPrimary = externalHostIpPrimary ?? old.ExternalHostIpPrimary, InternalNetPrimaryBits = internalNetPrimaryBits ?? old.InternalNetPrimaryBits, ExternalNetPrimaryBits = externalNetPrimaryBits ?? old.ExternalNetPrimaryBits, ResolvNameserver = resolvNameserver ?? old.ResolvNameserver, ResolvDomain = resolvDomain ?? old.ResolvDomain, Timezone = timezone ?? old.Timezone, NtpdateServer = ntpdateServer ?? old.NtpdateServer, MachineUid = Machine.MachineIds.Get.MachineUid, Cloud = cloud ?? old.Cloud }; Host2Configuration.Export(vars); new Do().HostChanges(); return(HttpStatusCode.OK); }; }
/// <summary> /// Apply the stored value /// </summary> public void Apply() { if (IsApplied) { return; } CommandLauncher.Launch(SetCmd, StoredValues); }
public void RemoveModules() { var modules = string.Join(" ", HostParametersConfiguration.Conf.Rmmod); CommandLauncher.Launch("rmmod", new Dictionary <string, string> { { "$modules", modules } }); }
public string[] GetNsResolv() { Host = LoadHostModel(); var launcher = new CommandLauncher(); var resolv = launcher.Launch(Host.NsResolv.GetCmd).ToArray(); return(resolv); }
public string[] GetNsHosts() { Host = LoadHostModel(); var launcher = new CommandLauncher(); var hosts = launcher.Launch(Host.NsHosts.GetCmd).ToArray(); return(hosts); }
public string[] GetNsNetworks() { Host = LoadHostModel(); var launcher = new CommandLauncher(); var networks = launcher.Launch(Host.NsNetworks.GetCmd).ToArray(); return(networks); }
public string[] GetNtpd() { Host = LoadHostModel(); var launcher = new CommandLauncher(); var ntpd = launcher.Launch(Host.Ntpd.GetCmd).ToArray(); return(ntpd); }
public string HashPasswd(string input) { var output = CommandLauncher.Launch("mkpasswd", new Dictionary <string, string> { { "$password", input } }).FirstOrDefault(); return(output); }
public string[] GetNsSwitch() { Host = LoadHostModel(); var launcher = new CommandLauncher(); var @switch = launcher.Launch(Host.NsSwitch.GetCmd).ToArray(); return(@switch); }
public bool TestConnection() { var r = CommandLauncher.Launch("ping-c", new Dictionary <string, string> { { "$ip", _serviceModel.RemotePoint.Address } }).Grep("From"); return(!r.All(_ => _.ToLower().Contains("host unreachable"))); }
public AntdTimeModule() { Get["/time/info"] = x => { const StringSplitOptions ssoree = StringSplitOptions.RemoveEmptyEntries; var bash = new Bash(); var launcher = new CommandLauncher(); var hostConfiguration = new HostConfiguration(); var timezones = bash.Execute("timedatectl list-timezones --no-pager").SplitBash(); var timedatectl = launcher.Launch("timedatectl").ToList(); var ntpd = launcher.Launch("cat-etc-ntp").ToArray(); var model = new PageTimeModel { Timezones = timezones, LocalTime = timedatectl.First(_ => _.Contains("Local time:")).Split(new[] { ":" }, 2, ssoree)[1], UnivTime = timedatectl.First(_ => _.Contains("Universal time:")).Split(new[] { ":" }, 2, ssoree)[1], RtcTime = timedatectl.First(_ => _.Contains("RTC time:")).Split(new[] { ":" }, 2, ssoree)[1], Timezone = timedatectl.First(_ => _.Contains("Time zone:")).Split(new[] { ":" }, 2, ssoree)[1], Nettimeon = timedatectl.First(_ => _.Contains("Network time on:")).Split(new[] { ":" }, 2, ssoree)[1], Ntpsync = timedatectl.First(_ => _.Contains("NTP synchronized:")).Split(new[] { ":" }, 2, ssoree)[1], Rtcintz = timedatectl.First(_ => _.Contains("RTC in local TZ:")).Split(new[] { ":" }, 2, ssoree)[1], NtpServer = hostConfiguration.Host.NtpdateServer.StoredValues["$server"], Ntpd = ntpd.JoinToString("<br />"), NtpdEdit = ntpd.JoinToString(Environment.NewLine) }; return(JsonConvert.SerializeObject(model)); }; Post["/host/timezone"] = x => { string timezone = Request.Form.Timezone; var hostconfiguration = new HostConfiguration(); hostconfiguration.SetTimezone(timezone); hostconfiguration.ApplyTimezone(); return(HttpStatusCode.OK); }; Post["/host/synctime"] = x => { var hostconfiguration = new HostConfiguration(); hostconfiguration.SyncClock(); return(HttpStatusCode.OK); }; Post["/host/ntpdate"] = x => { string ntpdate = Request.Form.Ntpdate; var hostconfiguration = new HostConfiguration(); hostconfiguration.SetNtpdate(ntpdate); hostconfiguration.ApplyNtpdate(); return(HttpStatusCode.OK); }; Post["/host/ntpd"] = x => { string ntpd = Request.Form.Ntpd; var hostConfiguration = new HostConfiguration(); hostConfiguration.SetNtpd(ntpd.Contains("\n") ? ntpd.SplitToList("\n").ToArray() : ntpd.SplitToList(Environment.NewLine).ToArray()); hostConfiguration.ApplyNtpd(); return(HttpStatusCode.OK); }; }
/// <summary> /// Apply and store a new set of values /// </summary> /// <param name="values"> /// Where values.Key == parameter name, ex "$host_name" /// Where values.Value == parameter value, ex "myhost01" /// </param> public void Apply(Dictionary <string, string> values) { if (IsApplied) { return; } StoredValues = values; CommandLauncher.Launch(SetCmd, StoredValues); }
public CommandModule() { Get["/cmd/launch/{name}"] = x => { string name = x.name; try { var result = CommandLauncher.Launch(name); return(JsonConvert.SerializeObject(result, Formatting.Indented)); } catch (Exception ex) { return(JsonConvert.SerializeObject(ex, Formatting.Indented)); } }; Get["/cmd/launch/{name}/{values*}"] = x => { string name = x.name; string strValues = x.values; if (!string.IsNullOrEmpty(strValues)) { try { var dict = strValues.SplitToList(";") .Select(kv => kv.SplitToList(":").ToArray()) .ToDictionary(s => s.First(), s => s.Last()); var result = CommandLauncher.Launch(name, dict); return(JsonConvert.SerializeObject(result, Formatting.Indented)); } catch (Exception ex) { return(JsonConvert.SerializeObject(ex, Formatting.Indented)); } } return(HttpStatusCode.InternalServerError); }; Post["/cmd/launch"] = x => { string name = Request.Form.Command; string strValues = Request.Form.Matches; if (!string.IsNullOrEmpty(strValues)) { try { var dict = strValues.SplitToList(";") .Select(kv => kv.SplitToList(":").ToArray()) .ToDictionary(s => s.First(), s => s.Last()); var result = CommandLauncher.Launch(name, dict); return(JsonConvert.SerializeObject(result, Formatting.Indented)); } catch (Exception ex) { return(JsonConvert.SerializeObject(ex, Formatting.Indented)); } } try { var result = CommandLauncher.Launch(name); return(JsonConvert.SerializeObject(result, Formatting.Indented)); } catch (Exception ex) { return(JsonConvert.SerializeObject(ex, Formatting.Indented)); } }; }
public void ApplyHostServices() { Host = LoadHostModel(); var launcher = new CommandLauncher(); foreach (var srvc in Host.Services) { launcher.Launch(srvc.SetCmd, srvc.StoredValues); } }
public static void ApplyHostInfo() { CommandLauncher.Launch(Host.HostName.SetCmd, Host.HostName.StoredValues); CommandLauncher.Launch(Host.HostChassis.SetCmd, Host.HostChassis.StoredValues); CommandLauncher.Launch(Host.HostDeployment.SetCmd, Host.HostDeployment.StoredValues); CommandLauncher.Launch(Host.HostLocation.SetCmd, Host.HostLocation.StoredValues); var name = Host.HostName.StoredValues["$host_name"]; File.WriteAllText("/etc/hostname", name); }
public void ApplyHostModprobes() { Host = LoadHostModel(); var launcher = new CommandLauncher(); foreach (var modprobe in Host.Modprobes) { launcher.Launch(modprobe.SetCmd, modprobe.StoredValues); } }
public AntdServicesModule() { Get["/services"] = x => { var model = new PageServicesModel(); var machineInfo = new MachineInfo(); var services = machineInfo.GetUnits("service"); var mounts = machineInfo.GetUnits("mount"); var targets = machineInfo.GetUnits("target"); var timers = machineInfo.GetUnits("timer"); services.AddRange(mounts); services.AddRange(targets); services.AddRange(timers); model.Units = services; return(JsonConvert.SerializeObject(model)); }; Get["/services/log"] = x => { string unit = Request.Query.unit; var launcher = new CommandLauncher(); var model = launcher.Launch("journactl-service", new Dictionary <string, string> { { "$service", unit } }); return(JsonConvert.SerializeObject(model)); }; Post["/services/start"] = x => { string unit = Request.Form.Unit; Systemctl.Start(unit); return(HttpStatusCode.OK); }; Post["/services/restart"] = x => { string unit = Request.Form.Unit; Systemctl.Restart(unit); return(HttpStatusCode.OK); }; Post["/services/stop"] = x => { string unit = Request.Form.Unit; Systemctl.Stop(unit); return(HttpStatusCode.OK); }; Post["/services/enable"] = x => { string unit = Request.Form.Unit; Systemctl.Enable(unit); return(HttpStatusCode.OK); }; Post["/services/disable"] = x => { string unit = Request.Form.Unit; Systemctl.Disable(unit); return(HttpStatusCode.OK); }; }
public void SyncClock(string ntpServer = "") { var launcher = new CommandLauncher(); ApplyNtpdate(); if (Systemctl.IsActive("ntpd")) { ApplyNtpd(); } launcher.Launch("sync-clock"); }
public static void Start() { if (!IsActive()) { return; } CommandLauncher.Launch("nft-f", new Dictionary <string, string> { { "$file", MainFilePath } }); ConsoleLogger.Log("[firewall] start"); }
public void SaveModprobes() { var modules = HostParametersConfiguration.Conf.Modprobes; foreach (var mod in modules) { ConsoleLogger.Log($"load module: {mod}"); Bash.Execute($"modprobe {mod}"); CommandLauncher.Launch("modprobe", new Dictionary <string, string> { { "$package", mod } }); } }
public static void StartFallback() { ConsoleLogger.Log("[network] setting up a default configuration"); const string bridge = "br0"; if (_networkInterfaces.All(_ => _ != bridge)) { CommandLauncher.Launch("brctl-add", new Dictionary <string, string> { { "$bridge", bridge } }); ConsoleLogger.Log($"[network] {bridge} configured"); } foreach (var phy in InterfacePhysical) { CommandLauncher.Launch("brctl-addif", new Dictionary <string, string> { { "$bridge", bridge }, { "$net_if", phy } }); ConsoleLogger.Log($"[network] {phy} add to {bridge}"); } foreach (var phy in InterfacePhysical) { CommandLauncher.Launch("ip4-enable-if", new Dictionary <string, string> { { "$net_if", phy } }); } CommandLauncher.Launch("ip4-enable-if", new Dictionary <string, string> { { "$net_if", bridge } }); ConsoleLogger.Log("[network] interfaces up"); const string address = "192.168.1.1"; const string range = "24"; CommandLauncher.Launch("ip4-add-addr", new Dictionary <string, string> { { "$address", address }, { "$range", range }, { "$net_if", bridge } }); var tryBridgeAddress = CommandLauncher.Launch("ifconfig-if", new Dictionary <string, string> { { "$net_if", bridge } }).ToList(); if (tryBridgeAddress.FirstOrDefault(_ => _.Contains("inet")) != null) { var bridgeAddress = tryBridgeAddress.Print(2, " "); ConsoleLogger.Log($"[network] {bridge} is now reachable at {bridgeAddress}"); return; } ConsoleLogger.Log($"[network] {bridge} is unreachable"); }
public string ConfigureInterface() { var netIf = GetInterfaceWithCarrier(); if (string.IsNullOrEmpty(netIf)) { return(string.Empty); } CommandLauncher.Launch("ip4-add-addr", new Dictionary <string, string> { { "$address", "192.168.1.1" }, { "$range", "24" }, { "$net_if", netIf } }); return(netIf); }
private static void Action() { var lsmod = Mapper.FromCommand <ModuleModel>("lsmod").ToList().Skip(1).ToList(); if (!lsmod.Any()) { return; } var launcher = new CommandLauncher(); launcher.Launch("rmmod", new Dictionary <string, string> { { "$modules", lsmod.Select(_ => _.Name).JoinToString(" ") } }); var hostConfiguration = new HostConfiguration(); hostConfiguration.ApplyHostModprobes(); }
public override void DoJob() { try { //ConsoleLogger.Log("Scheduled action: Watch Cloud Stored Commands"); var cloudaddress = new AppConfiguration().Get().CloudAddress; if (string.IsNullOrEmpty(cloudaddress)) { return; } if (!cloudaddress.EndsWith("/")) { cloudaddress = cloudaddress + "/"; } if (Parameter.Cloud.Contains("localhost")) { return; } //fetchcommand/{partnum}/{serialnum}/{machineuid}/{appname} var cmds = Api.Get <List <RemoteCommand> >($"{cloudaddress}repo/assetinfo/fetchcommand/{MachineId.PartNumber}/{MachineId.SerialNumber}/{MachineId.MachineUid}/Antd"); if (cmds == null) { return; } if (!cmds.Any()) { return; } foreach (var cmd in cmds.OrderBy(_ => _.Date)) { CommandLauncher.Launch(cmd.Command, cmd.Parameters); var dict = new Dictionary <string, string> { { "AppName", "Antd" }, { "PartNumber", MachineId.PartNumber }, { "SerialNumber", MachineId.SerialNumber }, { "MachineUid", MachineId.MachineUid }, { "Command", cmd.CommandCode } }; Api.Post($"{cloudaddress}repo/assetinfo/confirmcommand", dict); } } catch (Exception) { //ConsoleLogger.Error(ex.Message); } }
//public void SetupResolvD() { // if(!File.Exists("/etc/systemd/resolved.conf") || string.IsNullOrEmpty(File.ReadAllText("/etc/systemd/resolved.conf"))) { // var lines = new List<string> { // "[Resolve]", // "DNS=10.1.19.1 10.99.19.1", // "FallbackDNS=8.8.8.8 8.8.4.4 2001:4860:4860::8888 2001:4860:4860::8844", // "Domains=antd.local", // "LLMNR=yes" // }; // File.WriteAllLines("/etc/systemd/resolved.conf", lines); // } // _launcher.Launch("systemctl-daemonreload"); // _launcher.Launch("systemctl-restart", new Dictionary<string, string> { { "$service", "systemd-resolved" } }); //} #endregion #region [ hostnamectl ] private void SaveHostname() { CommandLauncher.Launch("set-hostname", new Dictionary <string, string> { { "$host_name", _host.HostName } }); CommandLauncher.Launch("set-chassis", new Dictionary <string, string> { { "$host_chassis", _host.HostChassis } }); CommandLauncher.Launch("set-deployment", new Dictionary <string, string> { { "$host_deployment", _host.HostDeployment } }); CommandLauncher.Launch("set-location", new Dictionary <string, string> { { "$host_location", _host.HostLocation } }); File.WriteAllText("/etc/hostname", _host.HostName); CommandLauncher.Launch("set-timezone", new Dictionary <string, string> { { "$host_timezone", _host.Timezone } }); }