使用C#在远程SSH服务器上启动脚本

时间:2019-06-19 09:02:32

标签: c# ssh

我有一个使用C#在Visual Studio上设计的GUI。我是C#的初学者,但是擅长C ++编程,但是由于任务要求,我正在C#中进行设计。在此GUI中,我有一个连接到远程ssh服务器的按钮,作为试用,当用户按下button1时,我有以下命令要运行。

client.Connect();
                var output    = client.RunCommand("echo happy test");
                var dltOutput = client.RunCommand("rm /home/helloWorld.txt");
                var launchFirst = client.RunCommand("bash /root/first.sh");
                client.Disconnect();
                Console.WriteLine(output.Result);

用于删除我的主文件夹中的“ helloWorld.txt”的命令运行正常,但无法运行该命令以运行外壳程序脚本“ first.sh”。我想在下面附上完整的代码供您参考。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Renci.SshNet;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        //Connection information
        string user = "root";
        string pass = "hello123ado";
        string host = "192.168.38.50";
        int port = 22;

        public Form1()
        {
            InitializeComponent();
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            Console.WriteLine("Say Button1_Clicked");

            using (var client = new SshClient(host,user,pass))
            {
                client.Connect();
                var output    = client.RunCommand("echo happy test");
                var dltOutput = client.RunCommand("rm /home/helloWorld.txt");

                var launchFirst = client.RunCommand("bash /root/first.sh");
                client.Disconnect();
                Console.WriteLine(output.Result);
            }


        }

        private void Button2_Click(object sender, EventArgs e)
        {
            Console.WriteLine("Say Button2_Clicked");

        }

        private void Button3_Click(object sender, EventArgs e)
        {
            Console.WriteLine("Say Button3_Clicked");
        }
    }
}

0 个答案:

没有答案