示例#1
0
        public static string ExecuteCommand(string command)
        {
            _streamError   = null;
            _processOutput = null;

            var escapedArgs = command.Replace("\"", "\\\"");

            ProcessStartInfo procStartInfo = OsDetector.IsWindows() ?
                                             new ProcessStartInfo("cmd", "/c " + escapedArgs) :
                                             new ProcessStartInfo("/bin/bash", $"-c \"{escapedArgs}\"");

            // Check if errors should be redirected to a file.
            _errorsWritten = false;

            Process process;

            process           = new Process();
            process.StartInfo = procStartInfo;

            // Set UseShellExecute to false for redirection.
            process.StartInfo.UseShellExecute = false;

            // Redirect the standard output of the net command.
            // This stream is read asynchronously using an event handler.
            process.StartInfo.RedirectStandardOutput = true;
            process.OutputDataReceived += new DataReceivedEventHandler(NetOutputDataHandler);
            _processOutput              = new StringBuilder();

            // Do not redirect the error output.
            process.StartInfo.RedirectStandardError = false;

            // Start the process.
            process.Start();
            process.BeginOutputReadLine();

            if (_errorRedirect)
            {
                process.BeginErrorReadLine();
            }

            process.WaitForExit();

            if (_streamError != null)
            {
                _streamError.Close();
            }
            else
            {
                // Set _errorsWritten to false if the stream is not
                // open.   Either there are no errors, or the error
                // file could not be opened.
                _errorsWritten = false;
            }

            if (_processOutput.Length > 0)
            {
                // If the process wrote more than just
                // white space, write the output to the console.
                Console.WriteLine("\nOutput: \n{0}\n", _processOutput);
            }

            process.Close();
            return(_processOutput.ToString());
        }
示例#2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="profile"></param>
        /// <param name="region"></param>
        /// <param name="serialnumber"></param>
        /// <param name="tokencode"></param>
        public string Run(string profile, string region, string serialnumber, string tokencode)
        {
            //unset environment variabes
            try
            {
                System.Environment.SetEnvironmentVariable("AWS_ACCESS_KEY_ID", null);
                System.Environment.SetEnvironmentVariable("AWS_SECRET_ACCESS_KEY", null);
                System.Environment.SetEnvironmentVariable("AWS_SESSION_TOKEN", null);
                System.Environment.SetEnvironmentVariable("AWS_PROFILE", null);

                /*
                 * if (OsDetector.IsWindows())
                 * {
                 *  ExecuteCommand($"set AWS_ACCESS_KEY_ID=");
                 *  ExecuteCommand($"set AWS_SECRET_ACCESS_KEY=");
                 *  ExecuteCommand($"set AWS_SESSION_TOKEN=");
                 *  ExecuteCommand($"set AWS_PROFILE=");
                 *
                 *  //if case there is an issue to remove the environment varialbe with the code above
                 *  ExecuteCommand("REG delete HKCU\\Environment /F /V AWS_ACCESS_KEY_ID");
                 *  ExecuteCommand("REG delete HKCU\\Environment /F /V AWS_SECRET_ACCESS_KEY");
                 *  ExecuteCommand("REG delete HKCU\\Environment /F /V AWS_SESSION_TOKEN");
                 *  ExecuteCommand("REG delete HKCU\\Environment /F /V AWS_PROFILE");
                 *
                 * }
                 * else
                 * {
                 *  ExecuteCommand($"export AWS_ACCESS_KEY_ID=\"\"");
                 *  ExecuteCommand($"export AWS_SECRET_ACCESS_KEY=\"\"");
                 *  ExecuteCommand($"export AWS_SESSION_TOKEN=\"\"");
                 *  ExecuteCommand($"export AWS_PROFILE=\"\"");
                 * }
                 */
            }
            catch (Exception)
            {
                Console.WriteLine("Failed while deleting environment variables, but that is OK");
            }

            Console.WriteLine($"Log : aws sts get-session-token --profile {profile} --serial-number {serialnumber} --token-code {tokencode}");
            //string result = ExecuteCommand($"aws sts get-session-token --profile {profile} --serial-number {serialnumber} --token-code {tokencode}");

            string result = ProcessExecuter.ExecuteCommand($"aws sts get-session-token --profile {profile} --serial-number {serialnumber} --token-code {tokencode}");

            AwsStsGetTokenReturn credentials = JsonConvert.DeserializeObject <AwsStsGetTokenReturn>(result);

            Console.WriteLine("Log : Setting environment variables: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN, AWS_PROFILE");

            System.Environment.SetEnvironmentVariable("AWS_ACCESS_KEY_ID", credentials.Credentials.AccessKeyId, EnvironmentVariableTarget.User);
            System.Environment.SetEnvironmentVariable("AWS_SECRET_ACCESS_KEY", credentials.Credentials.SecretAccessKey, EnvironmentVariableTarget.User);
            System.Environment.SetEnvironmentVariable("AWS_SESSION_TOKEN", credentials.Credentials.SessionToken, EnvironmentVariableTarget.User);
            System.Environment.SetEnvironmentVariable("AWS_PROFILE", profile, EnvironmentVariableTarget.User);

            //set environment variabes

            if (OsDetector.IsWindows())
            {
                //set environment variables for AWS CLI
                ProcessExecuter.ExecuteCommand($"setx AWS_ACCESS_KEY_ID {credentials.Credentials.AccessKeyId}");
                ProcessExecuter.ExecuteCommand($"setx AWS_SECRET_ACCESS_KEY {credentials.Credentials.SecretAccessKey}");
                ProcessExecuter.ExecuteCommand($"setx AWS_SESSION_TOKEN {credentials.Credentials.SessionToken}");

                //set environment variable for terraform
                //if (profile != "default")
                ProcessExecuter.ExecuteCommand($"setx AWS_PROFILE {profile}");
            }
            else if (!OsDetector.IsWindows())
            {
                System.Environment.SetEnvironmentVariable("AWS_ACCESS_KEY_ID", credentials.Credentials.AccessKeyId);
                System.Environment.SetEnvironmentVariable("AWS_SECRET_ACCESS_KEY", credentials.Credentials.SecretAccessKey);
                System.Environment.SetEnvironmentVariable("AWS_SESSION_TOKEN", credentials.Credentials.SessionToken);
                System.Environment.SetEnvironmentVariable("AWS_PROFILE", profile);

                ////set environment variables for AWS CLI
                //ProcessExecuter.ExecuteCommand($"export AWS_ACCESS_KEY_ID={credentials.Credentials.AccessKeyId}");
                //ProcessExecuter.ExecuteCommand($"export AWS_SECRET_ACCESS_KEY={credentials.Credentials.SecretAccessKey}");
                //ProcessExecuter.ExecuteCommand($"export AWS_SESSION_TOKEN={credentials.Credentials.SessionToken}");

                ////set environment variable for terraform
                //ProcessExecuter.ExecuteCommand($"export AWS_PROFILE=\"{profile}\"");


                string fileContent = $"export AWS_ACCESS_KEY_ID=\"{credentials.Credentials.AccessKeyId}\"" +
                                     $" && export AWS_SECRET_ACCESS_KEY=\"{credentials.Credentials.SecretAccessKey}\"" +
                                     $" && export AWS_SESSION_TOKEN=\"{credentials.Credentials.SessionToken}\"" +
                                     $" && export AWS_PROFILE=\"{profile}\"";

                Console.WriteLine("Dotnetcore has an issue to update environment variables. If they are not set, run the following commands manually:");
                Console.WriteLine($"-----------------------------------------");
                Console.WriteLine(fileContent);
                Console.WriteLine($"-----------------------------------------");

                // Write the string array to a new file named "WriteLines.txt".
                using (StreamWriter outputFile = new StreamWriter("aws.env"))
                {
                    outputFile.Write(fileContent);
                }

                Console.WriteLine($"Call: '$ source aws.env' to load environment variables.. ");
            }


            return(result);
        }