Beispiel #1
0
        /// <summary>
        /// Gets all quarantined emails.
        /// </summary>
        /// <returns></returns>
        public ICollection <QuarantineEmail> GetAllQuarantinedMails()
        {
            ICollection <QuarantineEmail> functionResults = new List <QuarantineEmail>();

            using (PowerShellExecutor pse = new PowerShellExecutor())
            {
                PSDataCollection <PSObject> results = pse.ExecuteAsynchronously(Scripts.GetQuarantinedMails);
                foreach (PSObject item in results)
                {
                    if (item.BaseObject.ToString().StartsWith("Result:"))
                    {
                        string value = item.BaseObject.ToString();
                        value = value.Replace("Result:", "");
                        string[]        values = value.Split(';');
                        QuarantineEmail email  = new QuarantineEmail
                        {
                            Id     = values.FirstOrDefault(),
                            Sender = values.LastOrDefault()
                        };
                        functionResults.Add(email);
                    }
                }
            }

            return(functionResults);
        }
        protected override void DoExecute()
        {
            try
            {
                var powerShellRemoteExecutor = new PowerShellExecutor(
                    new PowerShellConfiguration
                {
                    IsRemote          = _isRemote,
                    RemoteMachineName = _machineName,
                    OnOutput          = LogOutput,
                    OnError           = LogError,
                });

                string script = string.Format(ScriptTemplate, _lazyScriptPath.Value, _scriptName);

                powerShellRemoteExecutor.Execute(script);

                PostDiagnosticMessage(string.Format("PowerShell script executed successfully, script: {0}", _lazyScriptPath), DiagnosticMessageType.Info);
            }
            catch (Exception exc)
            {
                PostDiagnosticMessage(string.Format("PowerShell script execution failed, script: {0}", _lazyScriptPath), DiagnosticMessageType.Error);

                throw new DeploymentTaskException(string.Format("Error while executing PowerShell script: {0}", _lazyScriptPath), exc);
            }
        }
Beispiel #3
0
        public void Execute(ServerConfig server, IReportStatus status, ConDepSettings settings, CancellationToken token)
        {
            var assemblyLocalDir  = Path.GetDirectoryName(GetType().Assembly.Location);
            var assemblyRemoteDir = Path.Combine(server.GetServerInfo().TempFolderDos, "Assemblies");

            var publisher = new FilePublisher();

            publisher.PublishDirectory(assemblyLocalDir, assemblyRemoteDir, server, settings);

            var remoteAssemblyFileName = Path.Combine(Path.Combine(server.GetServerInfo().TempFolderPowerShell, "Assemblies"), Path.GetFileName(GetType().Assembly.Location));
            var remoteJsonAssembly     = Path.Combine(Path.Combine(server.GetServerInfo().TempFolderPowerShell, "Assemblies"), "Newtonsoft.Json.dll");
            var typeName       = GetType().FullName;
            var loggerTypeName = typeof(RemotePowerShellLogger).FullName;

            var parameters        = GetPowerShellParameters(ConstructorArguments, GetType()).ToList();
            var scriptParams      = string.Join(",", parameters.Select(x => "$" + x.Name));
            var argumentList      = string.Join(",", GetType().GetConstructor(ConstructorArguments.Select(x => x.GetType()).ToArray()).GetParameters().Select(x => "$" + x.Name));
            var deserializeScript = GetDeserializationScript(GetType().GetConstructor(ConstructorArguments.Select(x => x.GetType()).ToArray()));

            var psExecutor = new PowerShellExecutor(server);
            var script     = string.Format(@"
Param({3})
add-type -path {0}
add-type -path {5}
{4}
$operation = new-object -typename {1} -ArgumentList {6}
$logger = new-object -typename {2} -ArgumentList (Get-Host).UI
$operation.Execute($logger)
", remoteAssemblyFileName, typeName, loggerTypeName, scriptParams, deserializeScript, remoteJsonAssembly, argumentList);

            psExecutor.Execute(script, parameters);
        }
 public RemoteServerValidator(IEnumerable <ServerConfig> servers, ServerInfoHarvester serverInfoHarvester,
                              PowerShellExecutor psExecutor)
 {
     _servers             = servers;
     _serverInfoHarvester = serverInfoHarvester;
     _psExecutor          = psExecutor;
 }
 private bool Encrypt()
 {
     if (IsAutoMode)
     {
         if (ComputerName.IsNullOrEmpty())
         {
             var protector = new PasswordProtector();
             EncryptedValue = protector.Protect(OriginalValue, PasswordProtectionScope.LocalMachine);
             return(true);
         }
         else
         {
             //var factory = new ImpersonatorFactory()
             //{
             //    IsEnabled = true,
             //    Username = "******",
             //    Password = "******",
             //    Domain = "LILI"
             //};
             //using (factory.Create())
             {
                 var powershell = new PowerShellExecutor(ComputerName);
                 if (powershell.Execute())
                 {
                     EncryptedValue = powershell.Result;
                     return(true);
                 }
             }
         }
         return(false);
     }
     return(true);
 }
        public bool Deploy()
        {
            using (PowerShellExecutor pse = new PowerShellExecutor())
            {
                pse.ExecuteAsynchronously(Scripts.DeploySolution);
            }

            return(true);
        }
        public bool Retract()
        {
            using (PowerShellExecutor pse = new PowerShellExecutor())
            {
                pse.ExecuteAsynchronously(Scripts.RetractSolution);
            }

            return(true);
        }
Beispiel #8
0
        public bool ReleaseMail(string[] mails)
        {
            using (PowerShellExecutor pse = new PowerShellExecutor())
            {
                pse.ExecuteAsynchronously(Scripts.ReleaseQuarantinedMails, new KeyValuePair <string, string>("QuarantineEmails", "NONE"));
            }

            return(true);
        }
        public ConDepNodePublisher(string srcPath, string destPath, ConDepNodeUrl url, PowerShellExecutor psExecutor)
        {
            _srcPath    = srcPath;
            _destPath   = destPath;
            _url        = url;
            _psExecutor = psExecutor;

            //_psExecutor.LoadConDepNodeModule = true;
            //_psExecutor.LoadConDepModule = false;
        }
        public override void Execute(ServerConfig server, IReportStatus status, ConDepSettings settings, CancellationToken token)
        {
            var createFolderScript = string.Format(@"
if(!(Test-Path ""{0}""))
{{
    New-Item -ItemType directory -Path ""{0}""
}}
", _path);

            var psExecutor = new PowerShellExecutor(server);

            psExecutor.Execute(createFolderScript);
        }
Beispiel #11
0
 private bool ConditionFulfilled(ServerConfig server)
 {
     if (string.IsNullOrEmpty(_conditionScript))
     {
         return(_condition(server.GetServerInfo()) == _expectedConditionResult);
     }
     else
     {
         var psExecutor = new PowerShellExecutor(server);
         var result     = psExecutor.Execute(_conditionScript);
         return(result.First().ToString() == "True");
     }
 }
Beispiel #12
0
        public void Execute(ServerConfig server, IReportStatus status, ConDepSettings settings, CancellationToken token)
        {
            token.ThrowIfCancellationRequested();

            Logger.WithLogSection(string.Format("Stopping ConDepNode on server {0}", server.Name), () =>
            {
                var executor = new PowerShellExecutor(server)
                {
                    LoadConDepModule = false, LoadConDepNodeModule = true
                };
                executor.Execute("Stop-ConDepNode", logOutput: false);
            });
        }
Beispiel #13
0
        public void TestThat_Something()
        {
            ConDep.Dsl.Logging.Logger.Initialize(CreateMemoryLogger());

            var executor = new PowerShellExecutor();
            var result   = executor.ExecuteLocal(new ServerConfig(), "$psVersionTable.PSVersion.Major", load => load.LoadConDepModule = false);

            //var versionResult = GetExecutionResult();

            ////---------------------------
            var version = result.First();

            //dynamic version = ((Collection<PSObject>)versionResult).First();
            Assert.That(version >= 3);
        }
Beispiel #14
0
        protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
        {
            var scriptPath = ScriptPath.Get(context);

            if (Path.GetExtension(scriptPath) != ".ps1")
            {
                throw new ArgumentException($"'{Path.GetExtension(scriptPath)}' is not a valid PowerShell file type.");
            }

            var parameters = Parameters.Select(x => new KeyValuePair <string, object>(x.Key, x.Value.Get(context))).ToList();
            var psExec     = new PowerShellExecutor();

            context.UserState = psExec;
            return(psExec.ExecuteScript(scriptPath, parameters, callback, state));
        }
        protected override void DoExecute()
        {
            var powerShellRemoteExecutor = new PowerShellExecutor(
                new PowerShellConfiguration
            {
                IsRemote          = true,
                RemoteMachineName = _machineName,
                OnOutput          = OnOutput,
                OnError           = OnError,
            });

            string script = string.Format(RemoveDirScriptTemplate, _directoryPathToRemove.Value);

            powerShellRemoteExecutor.Execute(script);
        }
        private dynamic GetNodeState(ServerConfig server)
        {
            var nodeCheckExecutor = new PowerShellExecutor();
            var nodeCheckResult   =
                nodeCheckExecutor.Execute(server,
                                          string.Format("Get-ConDepNodeState \"{0}\" \"{1}\"", _destPath, FileHashGenerator.GetFileHash(_srcPath)),
                                          mod =>
            {
                mod.LoadConDepModule     = false;
                mod.LoadConDepNodeModule = true;
            },
                                          logOutput: true);

            return(nodeCheckResult.Single(psObject => psObject.ConDepResult != null).ConDepResult);
        }
        private void ExecuteCommand(string cmd, ServerConfig server)
        {
            var psExec = new PowerShellExecutor();

            if (_values != null)
            {
                if (_values.UseCredSSP)
                {
                    psExec.UseCredSSP = true;
                }
            }
            psExec.Execute(server, cmd, mod =>
            {
                mod.LoadConDepDotNetLibrary = _values == null || _values.RequireRemoteLib;
            });
        }
        public override Result Execute(IOfferRemoteOperations remote, ServerConfig server, ConDepSettings settings, CancellationToken token)
        {
            token.ThrowIfCancellationRequested();

            Logger.WithLogSection(string.Format("Stopping ConDepNode on server {0}", server.Name), () =>
            {
                var executor = new PowerShellExecutor();
                executor.Execute(server, "Stop-ConDepNode", mod =>
                {
                    mod.LoadConDepModule     = false;
                    mod.LoadConDepNodeModule = true;
                }, logOutput: false);
            });

            return(Result.SuccessUnChanged());
        }
Beispiel #19
0
        /// <summary>
        /// Gets the status of the programm.
        /// </summary>
        /// <returns></returns>
        public bool GetStatus()
        {
            using (PowerShellExecutor pse = new PowerShellExecutor())
            {
                PSDataCollection <PSObject> results = pse.ExecuteAsynchronously(Scripts.GetSolutionStatus);
                foreach (PSObject item in results)
                {
                    if (item.BaseObject.ToString().StartsWith("Result:"))
                    {
                        string value = item.BaseObject.ToString();
                        value        = value.Replace("Result:", "");
                        Control.Text = value;
                    }
                }
            }

            return(true);
        }
Beispiel #20
0
        public void Harvest(ServerConfig server)
        {
            var psExecutor = new PowerShellExecutor(server)
            {
                LoadConDepModule = false
            };
            var result = psExecutor.Execute(@"$regKeys = @(
        ""HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Client"", 
        ""HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full"", 
        ""HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5"",
        ""HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.0"",
        ""HKLM:\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727"",
        ""HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v1.1.4322""
        )

$result = @()

foreach($regKeyPath in $regKeys) {
    if(test-path $regKeyPath) {

        $regKey = Get-Item $regKeyPath
        $installed = $regKey.GetValue(""Install"")
        if($installed) {
            $dotNetVersion = @{}
            $dotNetVersion.Installed = $installed
            $dotNetVersion.Version = $regKey.GetValue(""Version"")
            $dotNetVersion.ServicePack = $regKey.GetValue(""SP"")
            $dotNetVersion.Release = $regKey.GetValue(""Release"")
            $dotNetVersion.TargetVersion = $regKey.GetValue(""TargetVersion"")
            $dotNetVersion.Client = $regKey.Name.ToLower().EndsWith(""client"")
            $dotNetVersion.Full = $regKey.Name.ToLower().EndsWith(""full"")

            $result += ,@($dotNetVersion)
        }
    }
}

return $result", logOutput: false);

            foreach (var element in result)
            {
                server.GetServerInfo().DotNetFrameworks.Add(element);
            }
        }
        protected override void DoExecute()
        {
            var powerShellRemoteExecutor = new PowerShellExecutor(
                new PowerShellConfiguration
            {
                IsRemote          = true,
                RemoteMachineName = _machineName,
                OnOutput          = OnOutput,
                OnError           = OnError,
            });

            PSObject psObject = powerShellRemoteExecutor.Execute(CreateTempDirScript);

            if (psObject == null || psObject.BaseObject == null || psObject.BaseObject is string == false)
            {
                throw new DeploymentTaskException(string.Format("Failed creating remote temp dir on machine: [{0}]", _machineName));
            }

            RemoteTempDirPath = psObject.BaseObject as string;
        }
Beispiel #22
0
        public void Harvest(ServerConfig server)
        {
            var psExecutor = new PowerShellExecutor(server)
            {
                LoadConDepModule = false
            };
            var diskInfo = @"$disks = Get-WmiObject win32_logicaldisk
$result = @()
foreach($disk in $disks) {
    $diskInfo = @{}
    $diskInfo.DeviceId = $disk.DeviceID
    $diskInfo.Size = $disk.Size
    $diskInfo.FreeSpace = $disk.FreeSpace
    $diskInfo.Name = $disk.Name
    $diskInfo.FileSystem = $disk.FileSystem
    $diskInfo.VolumeName = $disk.VolumeName

    $result += ,@($diskInfo)
}

return $result";

            var diskInfoResult = psExecutor.Execute(diskInfo, logOutput: false);

            if (diskInfoResult != null)
            {
                foreach (var disk in diskInfoResult)
                {
                    var d = new DiskInfo
                    {
                        DeviceId      = disk.DeviceId,
                        SizeInKb      = disk.Size == null ? 0 : Convert.ToInt64(disk.Size / 1024),
                        FreeSpaceInKb = disk.FreeSpace == null ? 0 : Convert.ToInt64(disk.FreeSpace / 1024),
                        Name          = disk.Name,
                        FileSystem    = disk.FileSystem,
                        VolumeName    = disk.VolumeName
                    };
                    server.GetServerInfo().Disks.Add(d);
                }
            }
        }
Beispiel #23
0
        private void InstallChocolatey(ServerConfig server, ConDepSettings settings)
        {
            Logger.WithLogSection("Installing Chocolatey", () =>
            {
                var psExecutor = new PowerShellExecutor(server);
                psExecutor.Execute(@"
try {
    if(!(Test-Path $env:ProgramData\chocolatey)) {
        iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))
    }
    else {
        Write-Host 'Chocolatey allready installed.'
    }
}
catch {
    Write-Warning 'Failed to install Chocolatey! This could break operations depending on Chocolatey.'
    Write-Warning ""Error message: $($_.Exception.Message)""
}
");
            });
        }
        private Result ExecuteCommand(string cmd, ServerConfig server)
        {
            var result = Result.SuccessUnChanged();

            var psExec = new PowerShellExecutor();

            if (_values != null)
            {
                if (_values.UseCredSSP)
                {
                    psExec.UseCredSSP = true;
                }
            }
            var execResult = psExec.Execute(server, cmd, mod =>
            {
                mod.LoadConDepDotNetLibrary = _values == null || _values.RequireRemoteLib;
            });

            result.Data.PsResult = execResult;
            return(result);
        }
Beispiel #25
0
        public void TestDotNetFrameworkHarvester()
        {
            if (_runningOnAppVeyor)
            {
                Assert.Ignore();
            }
            else
            {
                ConDep.Dsl.Logging.Logger.Initialize(CreateMemoryLogger());

                var executor  = new PowerShellExecutor();
                var harvester = new ConDep.Dsl.Harvesters.DotNetFrameworkHarvester(executor);

                harvester.Harvest(new ServerConfig()
                {
                    Name = "localhost", PowerShell = new PowerShellConfig(), DeploymentUser = new DeploymentUserConfig()
                    {
                        UserName = "******", Password = "******"
                    }
                });
            }
        }
        public override void Execute(ServerConfig server, IReportStatus status, ConDepSettings settings, CancellationToken token)
        {
            var canPingServer      = CanPingServer(server);
            var startNodeOperation = new StartConDepNodeOperation();

            Logger.Verbose(string.Format("Can {0}use ping for validation", canPingServer ? "" : "NOT "));

            Logger.WithLogSection("Restarting", () =>
            {
                Logger.Info(string.Format("Executing restart command on server {0}", server.Name));
                var powershellExecutor = new PowerShellExecutor();
                powershellExecutor.Execute(server, string.Format("cmd /c \"shutdown /r /t {0}\"", _delayInSeconds));

                if (canPingServer)
                {
                    Logger.Verbose("Waiting for ping to fail");
                    Logger.Info("Waiting for server to stop responding");
                    WaitForPing(WaitForStatus.Failure, server);
                    Logger.Info("Server stopped responding");
                    Logger.Verbose("Waiting for ping to Succeed");
                    Logger.Info("Waiting for server to respond again");
                    WaitForPing(WaitForStatus.Success, server);
                    Logger.Info("Server started to respond");
                }
                else
                {
                    Logger.Verbose("Waiting for WinRM to fail");
                    Logger.Info("Waiting for server to stop responding");
                    WaitForWinRm(WaitForStatus.Failure, server);
                    Logger.Info("Server stopped responding");
                }
                Logger.Verbose("Waiting for WinRM to succeed");
                Logger.Info("Waiting for server to respond to PowerShell commands");
                WaitForWinRm(WaitForStatus.Success, server);
                Logger.Info("Serve successfully responds to PowerShell commands");
                Logger.Info("Computer successfully restarted");
                Logger.WithLogSection("Starting ConDepNode", () => startNodeOperation.Execute(server, status, settings, token));
            });
        }
Beispiel #27
0
        public override void Execute(ServerConfig server, IReportStatus status, ConDepSettings settings, CancellationToken token)
        {
            var psExecutor = new PowerShellExecutor();

            psExecutor.Execute(server, string.Format("[Environment]::SetEnvironmentVariable(\"{0}\", \"{1}\", \"{2}\")", _name, _value, _target));
        }
Beispiel #28
0
 public PreRemoteOps(PowerShellExecutor psExecutor)
 {
     _psExecutor = psExecutor;
 }
Beispiel #29
0
 public OperatingSystemHarvester(PowerShellExecutor executor)
 {
     _executor = executor;
 }
Beispiel #30
0
 public OperatingSystemHarvester()
 {
     _executor = new PowerShellExecutor();
 }
Beispiel #31
0
        static int Main(string[] args)
        {
            var logger = new Logger();

            try
            {
                var parser = new FluentCommandLineParser();

                var deployDbConnection = string.Empty;
                parser.Setup<string>('d', "deployDbConnection").Callback(s => deployDbConnection = s).Required();

                var environment = string.Empty;
                parser.Setup<string>('e', "environment").Callback(s => environment = s).Required();

                var scriptFolder = string.Empty;
                parser.Setup<string>('f', "folder").Callback(s => scriptFolder = s).Required();

                var filenameMask = string.Empty;
                parser.Setup<string>('m', "mask").Callback(s => filenameMask = s).Required();

                var sqlConn = string.Empty;
                parser.Setup<string>('s', "sqlConn").Callback(s => sqlConn = s).SetDefault(String.Empty);

                var psFile = string.Empty;
                parser.Setup<string>('p', "psFile").Callback(s => psFile = s).SetDefault(String.Empty);

                var cmdFile = string.Empty;
                parser.Setup<string>('c', "cmdFile").Callback(s => cmdFile = s).SetDefault(String.Empty);

                var result = parser.Parse(args);
                if (result.HasErrors)
                {
                    logger.LogError(result.ErrorText);
                    return 2;
                }

                IExecutor executor;
                if (string.IsNullOrWhiteSpace(sqlConn) == false)
                {
                    executor = new SqlExecutor(sqlConn, logger);
                }
                else if (string.IsNullOrWhiteSpace(psFile) == false)
                {
                    executor = new PowerShellExecutor();
                }
                else if (string.IsNullOrWhiteSpace(cmdFile) == false)
                {
                    executor = new CommandExecutor();
                }
                else
                {
                    throw new ApplicationException("Script type cannot be determined.  Specify sqlConn, psFile or cmdFile");
                }

                var locator = new FileLocator();
                var history = new ScriptHistory(deployDbConnection);
                var processor = new ScriptProcessor(environment, scriptFolder, filenameMask, locator, history, executor);

                processor.ProcessScripts();
            }
            catch (Exception ex)
            {
                logger.LogError(ex.ToString());
                return 1;
            }

            return 0;
        }