I'd like to run a command over ssh from a windows box running using c#

前端 未结 6 1812
天命终不由人
天命终不由人 2021-01-02 08:31

Note that this has to be on a windows box as I am using c# to access information about windows

(I need information from both a windows box and a linux box, plus I th

6条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-02 08:49

    It is quite easy to call plink without the shell popping up.

    The trick to not show a window is to set ProcessStartInfo.CreateNoWindow = true.
    Add some error handling to this and you're done.

    --- PlinkWrapper.cs ---

    using System.Collections.Generic;
    using System.Diagnostics;
    
    namespace Stackoverflow_Test
    {
        public class PlinkWrapper
        {
            private string host { get; set; }
            /// 
            /// Initializes the 
            /// Assumes the key for the user is already loaded in PageAnt.
            /// 
            /// The host, on format user@host
            public PlinkWrapper(string host)
            {
                this.host = host;
            }
    
            /// 
            /// Runs a command and returns the output lines in a List<string>.
            /// 
            /// The command to execute
            /// 
            public List RunCommand(string command)
            {
                List result = new List();
    
                ProcessStartInfo startInfo = new ProcessStartInfo("plink.exe");
                startInfo.UseShellExecute = false;
                startInfo.RedirectStandardOutput = true;
                startInfo.CreateNoWindow = true;
                startInfo.Arguments = host + " " + command;
                using (Process p = new Process())
                {
                    p.StartInfo = startInfo;
                    p.Start();
                    while (p.StandardOutput.Peek() >= 0)
                    {
                        result.Add(p.StandardOutput.ReadLine());
                    }
                    p.WaitForExit();
                }
    
                return result;
            }
        }
    }
    

    --- END PlinkWrapper.cs ---

    Call it like

    PlinkWrapper plink = new PlinkWrapper("albin@mazarin");
    foreach (var str in plink.RunCommand("pwd"))
        Console.WriteLine("> " + str);
    

    and the output will be like

    > /home/albin
    

    The nice thing with plink is that it is well proven and integrates well with pageant.

提交回复
热议问题