c# - .NET Core - 从 Azure Ubuntu VM 下载或读取 Json 文件内容

标签 c# azure ubuntu .net-core virtual-machine

我的 Ubuntu VM 上有一个 node.js 脚本,它在完成执行后会生成一个 Json 文件。到目前为止,我可以使用以下代码从 .NET Core 控制台应用程序(使用 Visual Studio 2019)执行此脚本:

string subscriptionId = "mySubscriptionId";
string clientId = "myclientId";
string tenantId = "myTenantId";
string clientSecret = "myClientSecret";

var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenantId, AzureEnvironment.AzureGlobalCloud);
var azure = Azure.Configure().Authenticate(credentials).WithSubscription(subscriptionId);
var vm = await azure.VirtualMachines.GetByResourceGroupAsync("MyAzureRg", "MyUbuntuVm");

string cmd1 = "#!/bin/bash";
string cmd2 = "cd /home/Username/myapp/";
string cmd3 = "xvfb-run nodejs myNodeScript.js";

List<string> commands = new List<string>{cmd1,cmd2,cmd3};

Console.WriteLine("Executing shell script");

await vm.RunShellScriptAsync(commands, null);

Console.WriteLine("Script executed!");

然后我使用 PuTTY 和 SSH 连接到 Ubuntu VM,并且可以确认 Json 已在路径/home/Username/myapp/中正确创建。但是,我的问题是如何将其中的内容取回(读取或下载)到 .NET Core 应用程序?

最佳答案

在这种情况下获取 json 文件值的最简单方法应该是使用 RunShellScriptAsync()再次,请尝试以下代码:

List<string> commands = new List<string> { "cat <your json file path>" };

var result = vm.RunShellScriptAsync(commands, null).GetAwaiter().GetResult();

var message = result.Value[0].Message;

Console.WriteLine(result.Value[0].DisplayStatus);

var stdout = message.Substring(message.IndexOf("[stdout]") + 9).Replace("[stderr]","").Trim();

Console.WriteLine(stdout);

我这边的结果:

enter image description here

希望能帮助到你 。

关于c# - .NET Core - 从 Azure Ubuntu VM 下载或读取 Json 文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57982132/

相关文章:

azure - 如何检查我的 azure 网站实例计数是否被利用?

azure - 如何获取有关新添加的主题或队列的通知?

ubuntu - Caffe 错误 Ubuntu 16.04 with GPU/usr/bin/ld :/usr/lib/gcc/x86_64-linux-gnu/4. 9/libglog.a

c# - Windows 窗体 : closing, 但未关闭

azure - 读取 Windows VM RAM 内存日志分析查询

c# - 发送信封后从嵌入式签名切换到远程签名

linux - 从 C++ 应用程序代码调用 Linux 系统调用?

linux - 带有错误栏和线点的 GNUplot 混合图

c# - Entity Framework 4 - 事件连接数

c# - 使用 Prism 和 MEF 多次初始化静态变量