netcore中执行linux命令

可以通过System.Diagnostics.Process类来实现。具体的代码如下:

    public class RunCommand
    {
        public RunCommand(string fileName, string arguments, string workingDirectory = "")
        {
            FileName = fileName;
            Arguments = arguments;
            WorkingDirectory = workingDirectory;
        }
        public string FileName { get; set; }
        public string Arguments { get; set; }
        public string WorkingDirectory { get; set; }

        public string Execute(int milliseconds = 10000)
        {
            var rValue = "";
            using (System.Diagnostics.Process p = new System.Diagnostics.Process())
            {
                p.StartInfo.FileName = FileName;
                p.StartInfo.Arguments = Arguments;
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.WorkingDirectory = WorkingDirectory;
                p.Start();
                p.WaitForExit(milliseconds);
                rValue = p.StandardOutput.ReadToEnd();
            }
            return rValue;
        }
    }
View Code

 

调用代码如下:

1.给设备加权限。

                var arg = "chmod 777 001";
                new RunCommand("sudo", arg, "/dev/bus/usb/001").Execute();

2.列出所有usb设备信息。

            var result = new RunCommand("lsusb", "").Execute();
            Console.WriteLine(result);
posted @ 2020-07-30 17:40  HandsomeBoy  阅读(3244)  评论(1编辑  收藏  举报