How to run commands on SSH server in C#?

前端 未结 2 968
南方客
南方客 2020-12-01 12:55

I need to execute this action using a C# code:

  1. open putty.exe in the background (this is like a cmd window)
  2. login to a remote host using its IP addres
2条回答
  •  失恋的感觉
    2020-12-01 13:42

    You could try https://sshnet.codeplex.com/. With this you wouldn't need putty or a window at all. You can get the responses too. It would look sth. like this.

    SshClient sshclient = new SshClient("172.0.0.1", userName, password);    
    sshclient.Connect();
    SshCommand sc= sshclient .CreateCommand("Your Commands here");
    sc.Execute();
    string answer = sc.Result;
    

    Edit: Another approach would be to use a shellstream.

    Create a ShellStream once like:

    ShellStream stream = sshclient.CreateShellStream("customCommand", 80, 24, 800, 600, 1024);
    

    Then you can use a command like this:

      public StringBuilder sendCommand(string customCMD)
        {
            StringBuilder answer;
    
            var reader = new StreamReader(stream);
            var writer = new StreamWriter(stream);
            writer.AutoFlush = true; 
            WriteStream(customCMD, writer, stream);
            answer = ReadStream(reader);
            return answer;
        }
    
    private void WriteStream(string cmd, StreamWriter writer, ShellStream stream)
        {
            writer.WriteLine(cmd);
            while (stream.Length == 0)
            {
                Thread.Sleep(500);
            }
        }
    
    private StringBuilder ReadStream(StreamReader reader)
        {
            StringBuilder result = new StringBuilder();
    
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                result.AppendLine(line);
            }
            return result;
        }
    

提交回复
热议问题