首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SSH.NET从ShellStream检索输出

SSH.NET从ShellStream检索输出
EN

Stack Overflow用户
提问于 2019-09-23 15:44:51
回答 1查看 6.8K关注 0票数 2

我是SSH.NET的新手,我正在用它做一个我目前正在做的项目。

我必须使用SSH.NET运行sudo命令,这就是为什么我要使用ShellStream来运行命令并为sudo命令提供身份验证。现在,我正在尝试运行sudo命令,该命令在服务器上的一个目录中找到一个文件,该目录是我的ssh到的。该命令如下:

代码语言:javascript
复制
sudo -S find -name 29172

这个命令应该输出一个路径,该路径指示文件的位置,如下所示:

./output/directory/29172

我现在遇到的问题是,当我通过shell流执行此操作时,我不知道如何获得输出。即使当我尝试阅读ShellStream时,我也会看到这样的结果:

代码语言:javascript
复制
var client = new SshClient(IP, username, password);

var stream = client.CreateShellStream("input", 0, 0, 0, 0, 1000000);

stream.WriteLine("sudo -S find . -name 29172");

stream.WriteLine("\"" +password+"\"");

var output = stream.ReadToEnd();

输出通常是描述我何时使用SSH.NET登录到服务器,然后是我提供给系统的命令:

代码语言:javascript
复制
"Last login: Mon Sep 23 15:23:35 2019 from 100.00.00.00\r\r\nserver@ubuntu-dev4:~$ sudo -S find . -name 29172\r\n[sudo] password for server: \r\n"

我并不是在寻找这个输出,而是在寻找命令的实际输出,比如来自"./output/directory/29172"的ShellStream。有人知道怎么做吗?谢谢你的阅读,我希望不久能收到你的来信。

EN

回答 1

Stack Overflow用户

发布于 2019-09-25 14:40:59

我的解决方案相当冗长,但它做了一些其他必要的事情,以便在ssh上可靠地运行命令:

requests

  • captures
  • 自动响应身份验证

错误代码并引发故障

为了在SSH上实现sudo自动化,我们可以使用Expect --这就像同名的linux工具,并允许您进行交互响应。它一直等到有一些与模式匹配的输出,例如密码提示。

如果您有一系列sudo操作,您可能会被不可预测的时间所捕获,直到sudo需要重新身份验证,所以sudo可能需要也可能不需要身份验证,因此我们不能确定。

自动化时的一个大问题是知道命令是否失败。唯一知道的方法是获取shell上的最后一个错误。我扔的是非零。

要匹配shell提示符的regex可能需要为您的配置定制。各种事情都可能被注入提示符。

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Renci.SshNet;
using Renci.SshNet.Common;

namespace Example
{
    public class Log
    {
        public static void Verbose(string message) =>
            Console.WriteLine(message);

        public static void Error(string message) =>
            Console.WriteLine(message);
    }

    public static class StringExt
    {
        public static string StringBeforeLastRegEx(this string str, Regex regex)
        {
            var matches = regex.Matches(str);

            return matches.Count > 0
                ? str.Substring(0, matches.Last().Index)
                : str;

        }

        public static bool EndsWithRegEx(this string str, Regex regex)
        {
            var matches = regex.Matches(str);

            return
                matches.Count > 0 &&
                str.Length == (matches.Last().Index + matches.Last().Length);
        }

        public static string StringAfter(this string str, string substring)
        {
            var index = str.IndexOf(substring, StringComparison.Ordinal);

            return index >= 0
                ? str.Substring(index + substring.Length)
                : "";
        }

        public static string[] GetLines(this string str) =>
            Regex.Split(str, "\r\n|\r|\n");
    }

    public static class UtilExt
    {
        public static void ForEach<T>(this IEnumerable<T> sequence, Action<T> func) 
        {
            foreach (var item in sequence)
            {
                func(item);
            }
        }
    }

    public class Ssh
    {
        SshClient sshClient;
        ShellStream shell;
        string pwd = "";
        string lastCommand = "";

        static Regex prompt = new Regex("[a-zA-Z0-9_.-]*\\@[a-zA-Z0-9_.-]*\\:\\~[#$] ", RegexOptions.Compiled);
        static Regex pwdPrompt = new Regex("password for .*\\:", RegexOptions.Compiled);
        static Regex promptOrPwd = new Regex(Ssh.prompt + "|" + Ssh.pwdPrompt);

        public void Connect(string url, int port, string user, string pwd)
        {
            Log.Verbose($"Connect Ssh: {user}@{pwd}:{port}");

            var connectionInfo =
                new ConnectionInfo(
                    url,
                    port,
                    user,
                    new PasswordAuthenticationMethod(user, pwd));

            this.pwd = pwd;
            this.sshClient = new SshClient(connectionInfo);
            this.sshClient.Connect();

            var terminalMode = new Dictionary<TerminalModes, uint>();
            terminalMode.Add(TerminalModes.ECHO, 53);

            this.shell = this.sshClient.CreateShellStream("", 0, 0, 0, 0, 4096, terminalMode);

            try
            {
                this.Expect(Ssh.prompt);
            }
            catch (Exception ex)
            {
                Log.Error("Exception - " + ex.Message);
                throw;
            }
        }

        public void Disconnect()
        {
            Log.Verbose($"Ssh Disconnect");

            this.sshClient?.Disconnect();
            this.sshClient = null;
        }

        void Write(string commandLine)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Log.Verbose("> " + commandLine);
            Console.ResetColor(); 

            this.lastCommand = commandLine;

            this.shell.WriteLine(commandLine);
        }

        string Expect(Regex expect, double timeoutSeconds = 60.0)
        {
            var result = this.shell.Expect(expect, TimeSpan.FromSeconds(timeoutSeconds));

            if (result == null)
            {
                throw new Exception($"Timeout {timeoutSeconds}s executing {this.lastCommand}");
            }

            result = result.Contains(this.lastCommand) ? result.StringAfter(this.lastCommand) : result;
            result = result.StringBeforeLastRegEx(Ssh.prompt);
            result = result.Trim();

            result.GetLines().ForEach(x => Log.Verbose(x));

            return result;
        }

        public string Execute(string commandLine, double timeoutSeconds = 30.0)
        {
            Exception exception = null;
            var result = "";
            var errorMessage = "failed";
            var errorCode = "exception";

            try
            {
                this.Write(commandLine);
                result = this.Expect(Ssh.promptOrPwd);

                if (result.EndsWithRegEx(pwdPrompt))
                {
                    this.Write(this.pwd);
                    this.Expect(Ssh.prompt);
                }

                this.Write("echo $?");
                errorCode = this.Expect(Ssh.prompt);

                if (errorCode == "0")
                {
                    return result;    
                }
                else if (result.Length > 0)
                {
                    errorMessage = result;
                }
            }
            catch (Exception ex)
            {
                exception = ex;
                errorMessage = ex.Message;
            }

            throw new Exception($"Ssh error: {errorMessage}, code: {errorCode}, command: {commandLine}", exception);
        }
    }
}

然后像这样使用它:

代码语言:javascript
复制
var client = new Ssh(IP, 22, username, password);

var output = client.Execute("sudo -S find . -name 29172");
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58065938

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档