public object ExecuteCommand(string guid, string command, string stringFormat)
        {
            var serializer = new JavaScriptSerializer();
            var output     = new StringBuilder();

            if (!IsLoggedInUserAuthorized ||
                !SessionElevationManager.IsSessionTokenElevated(ApplicationNames.Console))
            {
                return(serializer.Serialize(
                           new
                {
                    status = StatusElevationRequired,
                    result =
                        "You need to be authenticated, elevated and have sufficient privileges to use the PowerShell console. Please (re)login to Sitecore.",
                    prompt = "PS >",
                    background = OutputLine.ProcessHtmlColor(ConsoleColor.DarkBlue)
                }));
            }

            PowerShellLog.Info($"Arbitrary script execution in Console session '{guid}' by user: '******'");

            var session = GetScriptSession(guid);

            session.Interactive = true;
            session.SetItemContextFromLocation();
            try
            {
                var handle     = ID.NewID.ToString();
                var jobOptions = new JobOptions(GetJobId(guid, handle), "PowerShell", "shell", this, nameof(RunJob),
                                                new object[] { session, command })
                {
                    AfterLife      = new TimeSpan(0, 0, 20),
                    ContextUser    = Sitecore.Context.User,
                    EnableSecurity = true,
                    ClientLanguage = Sitecore.Context.ContentLanguage
                };
                JobManager.Start(jobOptions);
                Thread.Sleep(WebServiceSettings.CommandWaitMillis);
                return(PollCommandOutput(guid, handle, stringFormat));
            }
            catch (Exception ex)
            {
                return
                    (serializer.Serialize(
                         new Result
                {
                    status = StatusError,
                    result =
                        output +
                        ScriptSession.GetExceptionString(ex, ScriptSession.ExceptionStringFormat.Console) +
                        "\r\n" +
                        "\r\n[[;#f00;#000]Uh oh, looks like the command you ran is invalid or something else went wrong. Is it something we should know about?]\r\n" +
                        "[[;#f00;#000]Please submit a support ticket here https://git.io/spe with error details, screenshots, and anything else that might help.]\r\n\r\n" +
                        "[[;#f00;#000]We also have a user guide here http://doc.sitecorepowershell.com/.]\r\n\r\n",
                    prompt = $"PS {session.CurrentLocation}>",
                    background = OutputLine.ProcessHtmlColor(session.PrivateData.BackgroundColor),
                    color = OutputLine.ProcessHtmlColor(session.PrivateData.ForegroundColor)
                }));
            }
        }
示例#2
0
        protected override void OnLoad(EventArgs e)
        {
            if (!SecurityHelper.CanRunApplication("PowerShell/PowerShell Console") ||
                ServiceAuthorizationManager.TerminateUnauthorizedRequest(WebServiceSettings.ServiceClient,
                                                                         Context.User?.Name))
            {
                PowerShellLog.Error($"User {Context.User?.Name} attempt to access PowerShell Console - denied.");
                return;
            }
            base.OnLoad(e);

            UpdateWarning();

            Settings = ApplicationSettings.GetInstance(ApplicationNames.Context, false);
            HttpContext.Current.Response.AddHeader("X-UA-Compatible", "IE=edge");
            var settings = ApplicationSettings.GetInstance(ApplicationNames.Console, false);

            if (!Context.ClientPage.IsEvent)
            {
                Options.Text = @"<script type='text/javascript'>" +
                               @"$ise(function() { cognifide.powershell.setOptions({ initialPoll: " +
                               WebServiceSettings.InitialPollMillis + @", maxPoll: " +
                               WebServiceSettings.MaxmimumPollMillis + @", fontSize: " +
                               settings.FontSize + $", fontFamily: '{settings.FontFamilyStyle}' }});}});</script>" +
                               @"<style>#terminal {" +
                               $"color: {OutputLine.ProcessHtmlColor(settings.ForegroundColor)};" +
                               $"background-color: {OutputLine.ProcessHtmlColor(settings.BackgroundColor)};" +
                               $"font-family: inherit;" + "}</style>";
            }
            SheerResponse.SetDialogValue("ok");
        }
示例#3
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            var          sid      = WebUtil.GetQueryString("sid");
            var          settings = ApplicationSettings.GetInstance(ApplicationNames.Context, false);
            ConsoleColor fc;
            ConsoleColor bc;

            if (!Enum.TryParse(WebUtil.GetQueryString("fc"), true, out fc))
            {
                fc = settings.ForegroundColor;
            }
            if (!Enum.TryParse(WebUtil.GetQueryString("bc"), true, out bc))
            {
                bc = settings.BackgroundColor;
            }
            var foregroundColor = OutputLine.ProcessHtmlColor(fc);
            var backgroundColor = OutputLine.ProcessHtmlColor(bc);

            Result.Style.Add("color", foregroundColor);
            Result.Style.Add("background-color", backgroundColor);
            Result.Style.Add("font-family", settings.FontFamilyStyle);
            Result.Style.Add("font-size", $"{settings.FontSize}px");
            Result.InnerHtml = HttpContext.Current.Session[sid] as string ?? string.Empty;
            All.Style.Add("color", foregroundColor);
            All.Style.Add("background-color", backgroundColor);
            Promo.Style.Add("background-color", backgroundColor);
            HttpContext.Current.Session.Remove(sid);
        }
示例#4
0
        protected override void OnLoad(EventArgs e)
        {
            Assert.CanRunApplication("PowerShell/PowerShell Console");
            base.OnLoad(e);
            Settings = ApplicationSettings.GetInstance(ApplicationNames.Context, false);
            HttpContext.Current.Response.AddHeader("X-UA-Compatible", "IE=edge");
            var settings = ApplicationSettings.GetInstance(ApplicationNames.AjaxConsole, false);

            if (!Context.ClientPage.IsEvent)
            {
                var db       = Factory.GetDatabase(ApplicationSettings.ScriptLibraryDb);
                var fonts    = db.GetItem(ApplicationSettings.FontNamesPath);
                var font     = string.IsNullOrEmpty(settings.FontFamily) ? "monospace" : settings.FontFamily;
                var fontItem = fonts.Children[font];
                font = fontItem != null
                    ? fontItem["Phrase"]
                    : "Monaco, Menlo, \"Ubuntu Mono\", Consolas, source-code-pro, monospace";

                Options.Text = @"<script type='text/javascript'>" +
                               @"$ise(function() { cognifide.powershell.setOptions({ initialPoll: " +
                               WebServiceSettings.InitialPollMillis + @", maxPoll: " +
                               WebServiceSettings.MaxmimumPollMillis + @", fontSize: " +
                               settings.FontSize + $", fontFamily: '{font}' }});}});</script>" +
                               @"<style>#terminal {" +
                               $"color: {OutputLine.ProcessHtmlColor(settings.ForegroundColor)};" +
                               $"background-color: {OutputLine.ProcessHtmlColor(settings.BackgroundColor)};" +
                               $"font-family: inherit;" + "}</style>";
            }
            SheerResponse.SetDialogValue("ok");
        }
示例#5
0
        protected virtual void UpdateSettings(ClientPipelineArgs args)
        {
            var settings        = ApplicationSettings.GetInstance(ApplicationNames.ISE);
            var backgroundColor = OutputLine.ProcessHtmlColor(settings.BackgroundColor);
            var bottomPadding   = CurrentVersion.IsAtLeast(SitecoreVersion.V80) ? 0 : 10;

            SheerResponse.Eval(
                $"spe.changeSettings('{settings.FontFamilyStyle}', {settings.FontSize}, '{backgroundColor}', {bottomPadding}, {settings.LiveAutocompletion.ToString().ToLower()});");
        }
示例#6
0
        public object ExecuteCommand(string guid, string command, string stringFormat)
        {
            if (!WebServiceSettings.ServiceEnabledClient)
            {
                return(string.Empty);
            }
            var serializer = new JavaScriptSerializer();
            var output     = new StringBuilder();

            if (!HttpContext.Current.Request.IsAuthenticated &&
                !command.StartsWith("login-user", StringComparison.OrdinalIgnoreCase))
            {
                return(serializer.Serialize(
                           new
                {
                    result =
                        "You need to be authenticated to use the PowerShell console. Please login to Sitecore first.",
                    prompt = "PS >",
                    background = OutputLine.ProcessHtmlColor(ConsoleColor.DarkBlue)
                }));
            }

            var session = GetScriptSession(guid);

            session.Interactive = true;
            try
            {
                var handle     = ID.NewID.ToString();
                var jobOptions = new JobOptions(GetJobId(guid, handle), "PowerShell", "shell", this, "RunJob",
                                                new object[] { session, command })
                {
                    AfterLife      = new TimeSpan(0, 0, 20),
                    ContextUser    = Sitecore.Context.User,
                    EnableSecurity = true,
                    ClientLanguage = Sitecore.Context.ContentLanguage
                };
                JobManager.Start(jobOptions);
                Thread.Sleep(WebServiceSettings.CommandWaitMillis);
                return(PollCommandOutput(guid, handle, stringFormat));
            }
            catch (Exception ex)
            {
                return
                    (serializer.Serialize(
                         new Result
                {
                    status = StatusError,
                    result = output + ScriptSession.GetExceptionString(ex, ScriptSession.ExceptionStringFormat.Console) + "\r\n" +
                             "\r\n[[;#f00;#000]Uh oh, looks like the command you ran is invalid or something else went wrong. Is it something we should know about?]\r\n" +
                             "[[;#f00;#000]Please submit a support ticket here https://git.io/spe with error details, screenshots, and anything else that might help.]\r\n\r\n" +
                             "[[;#f00;#000]We also have a user guide here http://sitecorepowershell.gitbooks.io/sitecore-powershell-extensions/.]\r\n\r\n",
                    prompt = $"PS {session.CurrentLocation}>",
                    background = OutputLine.ProcessHtmlColor(session.PrivateData.BackgroundColor),
                    color = OutputLine.ProcessHtmlColor(session.PrivateData.ForegroundColor)
                }));
            }
        }
示例#7
0
        protected virtual void UpdateSettings(ClientPipelineArgs args)
        {
            var settings        = ApplicationSettings.GetInstance(ApplicationNames.IseConsole);
            var db              = Factory.GetDatabase(ApplicationSettings.ScriptLibraryDb);
            var fonts           = db.GetItem(ApplicationSettings.FontNamesPath);
            var font            = string.IsNullOrEmpty(settings.FontFamily) ? "monospace" : settings.FontFamily;
            var fontItem        = fonts.Children[font];
            var backgroundColor = OutputLine.ProcessHtmlColor(settings.BackgroundColor);

            font = fontItem != null
                ? fontItem["Phrase"]
                : "Monaco, Menlo, \"Ubuntu Mono\", Consolas, source-code-pro, monospace";
            var bottomPadding = CurrentVersion.IsAtLeast(SitecoreVersion.V80) ? 0 : 10;

            SheerResponse.Eval(
                $"cognifide.powershell.changeSettings('{font}', {settings.FontSize}, '{backgroundColor}', {bottomPadding}, {settings.LiveAutocompletion.ToString().ToLower()});");
        }
        protected override void OnLoad(EventArgs e)
        {
            Assert.CanRunApplication("PowerShell/PowerShell Console");
            Assert.IsTrue(ServiceAuthorizationManager.IsUserAuthorized(WebServiceSettings.ServiceClient, Context.User.Name, false), "Application access denied.");
            base.OnLoad(e);
            Settings = ApplicationSettings.GetInstance(ApplicationNames.Context, false);
            HttpContext.Current.Response.AddHeader("X-UA-Compatible", "IE=edge");
            var settings = ApplicationSettings.GetInstance(ApplicationNames.AjaxConsole, false);

            if (!Context.ClientPage.IsEvent)
            {
                Options.Text = @"<script type='text/javascript'>" +
                               @"$ise(function() { cognifide.powershell.setOptions({ initialPoll: " +
                               WebServiceSettings.InitialPollMillis + @", maxPoll: " +
                               WebServiceSettings.MaxmimumPollMillis + @", fontSize: " +
                               settings.FontSize + $", fontFamily: '{settings.FontFamilyStyle}' }});}});</script>" +
                               @"<style>#terminal {" +
                               $"color: {OutputLine.ProcessHtmlColor(settings.ForegroundColor)};" +
                               $"background-color: {OutputLine.ProcessHtmlColor(settings.BackgroundColor)};" +
                               $"font-family: inherit;" + "}</style>";
            }
            SheerResponse.SetDialogValue("ok");
        }
        public object PollCommandOutput(string guid, string handle, string stringFormat)
        {
            if (!IsLoggedInUserAuthorized)
            {
                return(string.Empty);
            }

            HttpContext.Current.Response.ContentType = "application/json";
            var serializer = new JavaScriptSerializer();
            var session    = GetScriptSession(guid);
            var result     = new Result();
            var scriptJob  = JobManager.GetJob(GetJobId(guid, handle));

            if (scriptJob == null)
            {
                result.status = StatusError;
                result.result =
                    "Can't find your command result. This might mean that your job has timed out or your script caused the application to restart.";
                result.prompt = $"PS {session.CurrentLocation}>";

                if (!session.Output.HasUpdates())
                {
                    session.Output.Clear();
                    return(serializer.Serialize(result));
                }
            }
            else
            {
                result.handle = handle;
            }

            if (scriptJob != null && scriptJob.Status.Failed)
            {
                result.status = StatusError;
                var message =
                    string.Join(Environment.NewLine, scriptJob.Status.Messages.Cast <string>().ToArray())
                    .Replace("[", "&#91;")
                    .Replace("]", "&#93;");
                result.result = "[[;#f00;#000]" +
                                (message.IsNullOrEmpty() ? "Command failed" : HttpUtility.HtmlEncode(message)) + "]";
                result.prompt = $"PS {session.CurrentLocation}>";
                session.Output.Clear();
                return(serializer.Serialize(result));
            }

            var complete = scriptJob == null || scriptJob.IsDone;

            var output = new StringBuilder();

            session.Output.GetConsoleUpdate(output, 131072);
            var partial = session.Output.HasUpdates();

            result.result = output.ToString().TrimEnd('\r', '\n');
            result.prompt = $"PS {session.CurrentLocation}>";

            result.status     = complete ? (partial ? StatusPartial : StatusComplete) : StatusWorking;
            result.background = OutputLine.ProcessHtmlColor(session.PrivateData.BackgroundColor);
            result.color      = OutputLine.ProcessHtmlColor(session.PrivateData.ForegroundColor);

            if (partial && complete)
            {
                session.Output.Clear();
            }
            var serializedResult = serializer.Serialize(result);

            return(serializedResult);
        }