分享

dotnetcore执行shell脚本

 小世界的野孩子 2020-05-01

    我们可以使有dotnetcore跨平台的特性,优雅的实现在dotnetcore执行shell (bash).  代码如下:

using System;using System.Collections.Generic;using System.Text;namespace hshoc{    using System.Diagnostics;    public static class ShellHelper
    {        public static string Bash(this string cmd)
        {            var escapedArgs = cmd.Replace("\"", "\\\"");            var process = new Process()
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "/bin/bash",
                    Arguments = $"-c \"{escapedArgs}\"",
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true,
                }
            };
            process.Start();            string result = process.StandardOutput.ReadToEnd();
            process.WaitForExit();            return result;
        }
    }
}

为什么使用dotnetcore, 其性能比java更好,使用C#的扩展方法, 具体调用上面的代码是

var output = "ps aux".Bash();

是不是比较方便。大家可以延伸自动的应用。我们编写更复杂的SHELL脚本在其中,充分利用c#的特性,快速开发,易于调试。
这也是其中DevOps过程中很小一个点儿。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多