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();
            psExecutor.Execute(server, createFolderScript);
        }
 private bool ConditionFulfilled(ServerConfig server)
 {
     if (string.IsNullOrEmpty(_conditionScript))
     {
         return _condition(server.GetServerInfo()) == _expectedConditionResult;
     }
     else
     {
         var psExecutor = new PowerShellExecutor();
         var result = psExecutor.Execute(server, _conditionScript);
         return result.First().ToString() == "True";
     }
 }
Exemplo n.º 3
0
        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();
        }
        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));
            });
        }
Exemplo n.º 5
0
        private bool NeedToDeployScript(ServerConfig server, string localFile)
        {
            const string script         = @"Param($fileWithHash, $dir)
$dir = $ExecutionContext.InvokeCommand.ExpandString($dir)

$conDepReturnValues = New-Object PSObject -Property @{         
    ConDepResult    = New-Object PSObject -Property @{
		Files = $null
    }                 
}                  

function Get-ConDepFileHash($path) {
    if(Test-Path $path) {
        $md5 = [System.Security.Cryptography.MD5]::Create()
        $hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($path)))
        return $hash.Replace(""-"", """")
    }
    else {
        return """"
    }
}

$returnValues = @()

$hash = Get-ConDepFileHash (Join-Path -path $dir -childpath $($fileWithHash.Item1))
$returnValues += @{
	FileName = $fileWithHash.Item1
	IsEqual = ($hash -eq $fileWithHash.Item2)
}

$conDepReturnValues.ConDepResult.Files = $returnValues
return $conDepReturnValues
";
            var          scriptExecutor = new PowerShellExecutor(server)
            {
                LoadConDepModule = false
            };

            var scriptParameters = new List <CommandParameter>
            {
                new CommandParameter("fileWithHash", new Tuple <string, string>(Path.GetFileName(localFile), FileHashGenerator.GetFileHash(localFile))),
                new CommandParameter("dir", server.GetServerInfo().ConDepNodeScriptsFolder)
            };

            var scriptResult = scriptExecutor.Execute(script, logOutput: false, parameters: scriptParameters);

            foreach (var psObject in scriptResult)
            {
                if (psObject.ConDepResult == null || psObject.ConDepResult.Files == null)
                {
                    continue;
                }

                var remoteFilesArray = ((PSObject)psObject.ConDepResult.Files).BaseObject as ArrayList;
                var remoteFiles      = remoteFilesArray.Cast <dynamic>().Select(remoteFile => remoteFile);

                return(remoteFiles.Any(remoteFile => !remoteFile.IsEqual && remoteFile.FileName == Path.GetFileName(localFile)));
            }

            return(false);
        }
 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));
 }
Exemplo n.º 7
0
        private void EnableServerCredSSP()
        {
            var executor = new PowerShellExecutor();
            var result = executor.Execute(_server, @"get-item -path wsman:\localhost\Service\Auth\CredSSP", mod => mod.LoadConDepModule = false, logOutput: false).ToList();

            if (result.Count != 1) throw new ConDepCredSSPException();

            bool credSspEnabled;
            if (!Boolean.TryParse(result.First().Value, out credSspEnabled))
            {
                throw new ConDepCredSSPException("Unable to retreive CredSSP value from server.");
            }

            if (!credSspEnabled)
            {
                Logger.Verbose("CredSSP for server not enabled. Temporarly enabling now for this execution.");
                executor.Execute(_server, @"set-item -path wsman:\localhost\Service\Auth\CredSSP -value ""true"" -force", mod => mod.LoadConDepModule = false, logOutput: false);
                _cleanupFunctions.Add(() => executor.Execute(_server, @"set-item -path wsman:\localhost\Service\Auth\CredSSP -value ""false"" -force", mod => mod.LoadConDepModule = false, logOutput: false));
            }
        }
        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;
     });
 }
Exemplo n.º 10
0
        private void ConfigureSsl(ServerConfig server)
        {
            var resource = PfxInstallerResource.PfxInstallerScript;
            var script   = ConDepResourceFiles.GetResourceText(GetType().Assembly, resource);

            var dstPathDos = Path.Combine(server.GetServerInfo().TempFolderDos, "node.con-dep.net.pfx");
            var dstPathPs  = Path.Combine(server.GetServerInfo().TempFolderPowerShell, "node.con-dep.net.pfx");

            var certBytes = ConDepResourceFiles.GetResourceBytes(GetType().Assembly,
                                                                 new ConDepResource
            {
                Resource  = "node.con-dep.net.pfx",
                Namespace = typeof(ConDepResourceFiles).Namespace
            });

            var executor = new PowerShellExecutor(server)
            {
                LoadConDepModule = false
            };

            var scriptResult = executor.Execute(string.Format(@"
$conDepReturnValues = New-Object PSObject -Property @{{         
    ConDepResult    = $false 
}}     

$cert = Get-ChildItem Cert:\LocalMachine\My\{0} -ErrorAction SilentlyContinue
$conDepReturnValues.ConDepResult = !($cert -eq $null)
return $conDepReturnValues
", CERT_THUMBPRINT), logOutput: false);

            var certExist = false;

            foreach (var psObject in scriptResult)
            {
                if (psObject.ConDepResult == null)
                {
                    continue;
                }

                if (psObject.ConDepResult)
                {
                    certExist = true;
                }
            }

            if (!certExist)
            {
                Logger.Info("No SSL cert for ConDepNode found. Publishing now.");
                PublishFile(certBytes, dstPathPs, server);

                executor.Execute(script, new List <CommandParameter>
                {
                    new CommandParameter("filePath", dstPathDos),
                    new CommandParameter("password", CERT_PASS),
                });
                var cmd = string.Format(@"
$certThumbprint = ""{1}""
$appId = ""{2}""
netsh http add sslcert ipport=0.0.0.0:{0} certhash=$certThumbprint appid=$appId", _url.Port, CERT_THUMBPRINT, APP_ID);
                executor.Execute(cmd, logOutput: false);
                Logger.Info("SSL cert for ConDepNode published.");
            }
        }