【问题标题】:Can I invoke the Linux Terminal with .net我可以用 .net 调用 Linux 终端吗
【发布时间】:2022-08-09 23:06:34
【问题描述】:
现在的情况
我有一些服务器可以进行自动硬盘管理(初始化磁盘、挂载磁盘、修复磁盘......)这些服务器在 Ubuntu Server 最新的长期版本上运行。
最初我是从 bash 脚本开始的,但很快我发现我对 bash 脚本的了解有些有限,而且我对文本处理能力感到沮丧。
因此,我使用了我所知道的(.net)并建立了 ssh 连接。通过该 SSH 连接,我可以运行诸如 \"lsblk -O -b --j\" 之类的命令并处理它们的输出以格式化驱动器、编辑 fstab 文件或基本上我想做的任何事情以管理服务器。
目标
我的目标是摆脱本地计算机上的 ssh 连接,并创建一个可以在目标服务器本身上实现为服务的软件。
我想我可以打开到本地主机的 ssh 连接。这是一些适当的解决方法还是有另一种方法可以将我的程序连接到外壳?
在 Windows 中,可以使用与此类似的东西来针对 cmd 调用命令:
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.ProcessStartInfo(\"cmd\", \"/c \" + command);
// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();
// Display the command output.
Console.WriteLine(result);
}
catch (Exception objException)
{
// Log the exception
}
标签:
.net
shell
ubuntu
command-line-interface
【解决方案1】:
事实证明,它与 Windows 比较相似。
我写了一个相对简单的类,它可以用来对 shell 触发命令。
Github 仓库在这里:https://github.com/forReason/UnixCommandInvokeHelper_Solution
public class Command
{
public Command(string commandString, string workingDirectory = "./")
{
CommandText = commandString;
WorkingDirectory = workingDirectory;
}
public string CommandText { get; set; }
public string WorkingDirectory { get; set; }
public string Errors { get; private set; }
public string Output { get; private set; }
public DateTime StartTime { get; private set; }
public DateTime EndTime { get; private set; }
public async void Execute()
{
StartTime = DateTime.Now;
Errors = "";
Output = "";
var process = new Process();
try
{
string escapedArgs = CommandText.Replace("\"", "\\\"");
var processStartInfo = new ProcessStartInfo()
{
WindowStyle = ProcessWindowStyle.Hidden,
FileName = $"/bin/bash",
WorkingDirectory = this.WorkingDirectory,
Arguments = $"-c \"{escapedArgs}\"",
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false
};
process.StartInfo = processStartInfo;
process.Start();
Errors = process.StandardError.ReadToEnd();
Output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
}
catch (Exception ex)
{
Errors = ex.Message;
}
process.Close();
EndTime = DateTime.Now;
}
}