Esempio n. 1
0
        static void Main(string[] args)
        {
            //Example1

            var cmd = new CommandPrompt("dir");

            cmd.Execute();


            //Example2

            /*
             * var cmd = new cs_CommandPrompt();
             * cmd.SetCommand("echo helloworld");
             * cmd.Execute();
             */

            //Example3

            /*
             * var cmd = new cs_CommandPrompt();
             * cmd.Execute("echo hoge");
             */


            System.Console.WriteLine(cmd.ExitCode);
            System.Console.WriteLine(cmd.StdOut);
        }
Esempio n. 2
0
        public static bool ReserveUrlForNonAdministratorUsersAndAccounts(int port, string scheme = "http", string host = "+")
        {
            string command;
            string result;

            command = $"netsh http show urlacl url={scheme}://{host}:{port}/";
            result  = CommandPrompt.Execute(command);
            if (result.Contains("Reserved URL"))
            {
                Logger.Log("Url Reservation", $"Url {scheme}://{host}:{port}/ already has a reservation.");
                return(true);
            }

            command = $"netsh http add urlacl {scheme}://{host}:{port}/ user=$env:UserName";
            try {
                result = PowerShell.Execute(command, administrator: true);
            } catch (UnauthorizedAccessException ex) {
                Logger.Log("Exception", ex.Message);
                Logger.Log("Napaka", "Nimate administratorskih pravic.", toLog: false);
                return(false);
            }

            bool success = result.Contains("URL reservation successfully added");

            if (success)
            {
                Logger.Log("Url Reservation", $"Url {scheme}://{host}:{port}/ reserved.");
            }

            return(success);
        }
Esempio n. 3
0
        public static bool KillByName(string name, List <int> exclude = null)
        {
            string command;
            string result;

            if (exclude == null)
            {
                exclude = new List <int>();
            }

            command = $"wmic process where(Name = \"{name}\") get ProcessId";
            result  = CommandPrompt.Execute(command);

            List <int> pids = result
                              .Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
                              .Skip(1)
                              .Select(x => TypeConverter.StringToInteger(x.Trim()))
                              .Where(x => !exclude.Contains(x))
                              .ToList();

            command = $"taskkill /f";
            foreach (int pid in pids)
            {
                command += $" /pid {pid}";
            }
            result = CommandPrompt.Execute(command);

            return(Regex.Matches(result, "SUCCESS").Count == pids.Count);
        }
        private static bool PublishCoreProject(string solutionPath, string projectPath, string projectDeployPath)
        {
            string command = $"dotnet publish \"{projectPath}\" " +
                             $"--configuration Release " +
                             $"--framework netcoreapp2.0 " +
                             $"--output \"{projectDeployPath}\" " +
                             $"--verbosity normal";
            string result = CommandPrompt.Execute(command);

            return(result.Contains("Build succeeded"));
        }
Esempio n. 5
0
        public static int FindProcessPIDByListeningTCPPort(int port)
        {
            string command = $"netstat -ano -p TCP | find /I \"listening\" | find /I \"{port}\"";
            string result  = CommandPrompt.Execute(command);
            var    tokens  = result.Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            if (tokens.Length > 0)
            {
                return(TypeConverter.StringToInteger(tokens.Last()));
            }

            return(0);
        }
Esempio n. 6
0
        public static string GetRegistryValue(string key, string value)
        {
            string response = null;

            string command = $"reg query \"{key}\" /v \"{value}\"";
            string result  = CommandPrompt.Execute(command);

            if (!result.Contains("ERROR: The system was unable to find the specified registry key or value."))
            {
                response = ExtractDataByValue(result, value);
            }

            return(response);
        }
Esempio n. 7
0
        public static string GetRegistryValueByPattern(string key, string pattern, string value)
        {
            string response = null;

            string command = $"reg query \"{key}\" /s /f \"{pattern}\"";
            string result  = CommandPrompt.Execute(command);

            if (!result.Contains("End of search: 0 match(es) found."))
            {
                response = ExtractDataByValue(result, value);
            }

            return(response);
        }
Esempio n. 8
0
        private void CreateProjectCommands()
        {
            LinkedList <string> commands = new LinkedList <string>();

            commands.AddLast("cd C:/");
            commands.AddLast("cd " + createdDirectory + ";");
            commands.AddLast("git init;");
            commands.AddLast("git add README.md;");
            commands.AddLast("git commit -m \"initial commit\";");
            commands.AddLast("git push -u origin master");

            foreach (var command in commands)
            {
                string output = CommandPrompt.Execute(command);
                TbOutput.Text += output + Environment.NewLine;
            }
        }
Esempio n. 9
0
        public static bool OpenFirewallPort(string name, int port, string dir = "in", string action = "allow", string protocol = "TCP", string profile = "private")
        {
            string command;
            string result;

            command = $"netsh advfirewall firewall show rule name=\"{name}\"";
            result  = CommandPrompt.Execute(command);
            if (!result.Contains("No rules match the specified criteria."))
            {
                if (Regex.IsMatch(result, $"LocalPort:.*{port}{Environment.NewLine}"))
                {
                    Logger.Log("Firewall", $"Port {port} already opened.");
                    return(true);
                }
                else
                {
                    command = $"netsh advfirewall firewall delete rule name=\"{name}\"";
                    try {
                        result = CommandPrompt.Execute(command, administrator: true);
                    } catch (UnauthorizedAccessException ex) {
                        Logger.Log("Exception", ex.Message);
                        Logger.Log("Napaka", "Nimate administratorskih pravic.", toLog: false);
                        return(false);
                    }
                }
            }

            command = $"netsh advfirewall firewall add rule name=\"{name}\" dir=in action={action} protocol={protocol} profile={profile} localport={port}";
            try {
                result = CommandPrompt.Execute(command, administrator: true);
            } catch (UnauthorizedAccessException ex) {
                Logger.Log("Exception", ex.Message);
                Logger.Log("Napaka", "Nimate administratorskih pravic.", toLog: false);
                return(false);
            }

            bool success = result.Contains("Ok.");

            if (success)
            {
                Logger.Log("Firewall", $"Opened port {port}.");
            }

            return(success);
        }
Esempio n. 10
0
        public static bool KillbyPID(int pid, bool recurse = false)
        {
            string command = $"taskkill /f /pid {pid}";

            List <int> children = new List <int>();

            if (recurse)
            {
                children = GetChildren(pid, recurse);
                foreach (int childPid in children)
                {
                    command += $" /pid {childPid}";
                }
            }

            string result = CommandPrompt.Execute(command);

            return(Regex.Matches(result, "SUCCESS").Count == children.Count + 1);
        }
Esempio n. 11
0
        private static string GetMSBuildPath()
        {
            var    vsWherePath = Path.Combine(Build.SolutionPath, @"common\deployment\tools\vswhere.exe");
            string result      = CommandPrompt.Execute(vsWherePath);

            var match = Regex.Match(result, $"installationPath:.*{Environment.NewLine}");

            if (match.Success)
            {
                var visualStudioInstallPath = match.Value.Trim().Split(new[] { ": " }, StringSplitOptions.None)[1];
                return(Path.Combine(visualStudioInstallPath, @"MSBuild\15.0\Bin\MSBuild.exe"));
            }
            else
            {
                Console.WriteLine("Could not determine 'MSBuild.exe' path.");
                Console.ReadLine();
                Environment.Exit(-1);
            }

            return(null);
        }
Esempio n. 12
0
        public static List <int> GetChildren(int pid, bool recurse = false)
        {
            string command = $"wmic process where(ParentProcessId = {pid}) get ProcessId";
            string result  = CommandPrompt.Execute(command);

            List <int> children = result
                                  .Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
                                  .Skip(1)
                                  .Select(x => TypeConverter.StringToInteger(x.Trim()))
                                  .ToList();

            if (recurse)
            {
                for (int i = 0; i < children.Count; i++)
                {
                    children.AddRange(GetChildren(children[i], recurse));
                }
            }

            return(children);
        }
Esempio n. 13
0
        public static bool PublishFrameworkProject(string projectName, string destinationPath = DEFAULT_DESTINATION_PATH)
        {
            string msBuildPath = GetMSBuildPath();

            Console.Write($"Publishing {projectName} project");

            string solutionPath      = Build.SolutionPath;
            string projectPath       = Path.Combine(solutionPath, projectName);
            string projectDeployPath = Path.Combine(solutionPath, destinationPath, projectName);

            if (Directory.Exists(projectDeployPath))
            {
                Directory.Delete(projectDeployPath, recursive: true);
            }

            string command = $"\"{msBuildPath}\" " +
                             $"/target:Publish " +
                             $"/p:Configuration=Release " +
                             $"/p:OutDir={Path.Combine(projectDeployPath, @"bin\Release")} " +
                             $"\"{projectPath}\"";
            string result = CommandPrompt.Execute(command);

            var success = result.Contains("Build succeeded");

            if (success)
            {
                CreateCleanLog(projectDeployPath);
                Console.WriteLine("SUCCESS");
            }
            else
            {
                Console.WriteLine("...ERROR\n\nPress any key to exit.");
                Console.ReadLine();
                Environment.Exit(-1);
            }

            return(success);
        }
        public static void RegisterService(string filename, string path, bool unregister = true)
        {
            string command;

            if (unregister)
            {
                command = $@"reg query HKEY_LOCAL_MACHINE\SOFTWARE\Classes\TypeLib /s /f {filename}";
                string result = CommandPrompt.Execute(command);

                if (!result.Contains("End of search: 0 match(es) found."))
                {
                    string data = ExtractDataByValue(result, "(Default)");
                    if (data != null)
                    {
                        command = $"regsvr32 /s /u \"{data}\"";
                        CommandPrompt.ExecuteInBackground(command, administrator: true, waitForExit: true);
                    }
                }
            }

            command = $"regsvr32 /s \"{Path.Combine(path, filename)}\"";
            CommandPrompt.ExecuteInBackground(command, administrator: true, waitForExit: true);
        }
Esempio n. 15
0
        public static bool PublishCoreProject(string projectName, string destinationPath = DEFAULT_DESTINATION_PATH)
        {
            Console.Write($"Publishing {projectName} project");

            string solutionPath      = Build.SolutionPath;
            string projectPath       = Path.Combine(solutionPath, projectName);
            string projectDeployPath = Path.Combine(solutionPath, destinationPath, projectName);

            if (Directory.Exists(projectDeployPath))
            {
                Directory.Delete(projectDeployPath, recursive: true);
            }

            string command = $"dotnet publish \"{projectPath}\" " +
                             $"--configuration Release " +
                             $"--framework netcoreapp2.1 " +
                             $"--output \"{projectDeployPath}\" " +
                             $"--verbosity normal";
            string result = CommandPrompt.Execute(command);

            var success = result.Contains("Build succeeded");

            if (success)
            {
                CopyAndDeleteSettings(projectPath, projectDeployPath);
                CreateCleanLog(projectDeployPath);
                Console.WriteLine("SUCCESS");
            }
            else
            {
                Console.WriteLine("...ERROR\n\nPress any key to exit.");
                Console.ReadLine();
                Environment.Exit(-1);
            }

            return(success);
        }
Esempio n. 16
0
        public static bool AddAllowedProgram(string name, string program, bool force = false, string profile = "standard")
        {
            string command;
            string result;

            command = $"netsh advfirewall firewall show rule name=\"{name}\"";
            result  = CommandPrompt.Execute(command);
            if (!result.Contains("No rules match the specified criteria."))
            {
                if (force ||
                    !(
                        Regex.IsMatch(result, $"Enabled:.*Yes{Environment.NewLine}") &&
                        Regex.IsMatch(result, $"Protocol:.*UDP{Environment.NewLine}") &&
                        Regex.IsMatch(result, $"Protocol:.*TCP{Environment.NewLine}")
                        )
                    )
                {
                    command = $"netsh advfirewall firewall delete rule name=\"{name}\"";
                    try {
                        result = CommandPrompt.Execute(command, administrator: true);
                    } catch (UnauthorizedAccessException ex) {
                        Logger.Log("Exception", ex.Message);
                        Logger.Log("Napaka", "Nimate administratorskih pravic.", toLog: false);
                        return(false);
                    }
                }
                else
                {
                    Logger.Log("Firewall", $"Program '{name}' already allowed.");
                    return(true);
                }
            }

            bool success = false;

            if (profile != "any")
            {
                command = $"netsh firewall add allowedprogram name=\"{name}\" program=\"{program}\" mode=enable profile={profile}";
                try {
                    result  = CommandPrompt.Execute(command, administrator: true);
                    success = result.Contains("Ok.");
                } catch (UnauthorizedAccessException ex) {
                    Logger.Log("Exception", ex.Message);
                    Logger.Log("Napaka", "Nimate administratorskih pravic.", toLog: false);
                    return(false);
                }
            }
            else
            {
                command = $"netsh firewall add allowedprogram name=\"{name}\" program=\"{program}\" mode=enable profile=standard";
                try {
                    result  = CommandPrompt.Execute(command, administrator: true);
                    success = result.Contains("Ok.");
                } catch (UnauthorizedAccessException ex) {
                    Logger.Log("Exception", ex.Message);
                    Logger.Log("Napaka", "Nimate administratorskih pravic.", toLog: false);
                    return(false);
                }

                command = $"netsh advfirewall firewall set rule name=\"{name}\" profile=private new profile=any";
                try {
                    result   = CommandPrompt.Execute(command, administrator: true);
                    success &= result.Contains("Ok.");
                } catch (UnauthorizedAccessException ex) {
                    Logger.Log("Exception", ex.Message);
                    Logger.Log("Napaka", "Nimate administratorskih pravic.", toLog: false);
                    return(false);
                }
            }

            if (success)
            {
                Logger.Log("Firewall", $"Program '{name}' allowed.");
            }

            return(success);
        }