C# 使用SSH.NET连接服务器,执行命令,并在程序运行较长时间后返回

目录

整体目标

安装SSH.NET库

上传下载方法

连接方法

常见问题

参考:


整体目标

        实现本地电脑向Liunx服务器发送命令行指令,实现python程序的运行,并将运行后的结果发送回本地电脑。

安装SSH.NET库

直接依赖项里NuGet查照安装即可

sshnet/SSH.NET: SSH.NET is a Secure Shell (SSH) library for .NET, optimized for parallelism. (github.com)https://github.com/sshnet/SSH.NET

上传下载方法

代码摘自https://zhuanlan.zhihu.com/p/449829353,略有改动
public  string RunDown(string serverPath, string localPath)
        {
            try
            {
                using (var sftp = new SftpClient(this.Host, 22, this.User, this.Psw))
                {
                    sftp.Connect();
                    
                    using (var fileStream = File.OpenWrite(localPath))
                    {
                        sftp.DownloadFile(serverPath, fileStream);
                    }
                    sftp.Disconnect();
                    sftp.Dispose();
                    return "success";//返回空字符串
                }
            }
            catch (Exception ex)
            {
                return $"下载失败,原因:{ex.Message}";
            }
        }


 public  string RunUp(string upFileName, string serverPath)
        {
            try
            {
                using (var sftp = new SftpClient(this.Host, 22, this.User, this.Psw))
                {
                    sftp.Connect();
                    using (var fileStream = File.OpenRead(upFileName))
                    {
                        sftp.UploadFile(fileStream, serverPath, true, null);//true表示可以覆写
                    }
                    sftp.Disconnect();
                    sftp.Dispose();
                    return "success";
                }
            }//try
            catch (Exception ex)
            {
                return $"上传失败,原因是:{ex.Message}";
            }//catch
        }

连接方法

private void RunCommand()
{
    using (var client = new SshClient(host,22,user,psw))
    {
        client.Connect();

        var cmd = client.CreateCommand("command1; command2");
        //这里命令注意目录,每一次执行都是从根部从头开始。
        //例如执行/home/xxxx/目录下的python文件.
        //client.CreateCommand("cd /home/xxxx");
        //client.CreateCommand("python3 -u hsad.py");会报错
        //client.CreateCommand("cd /home/xxxx;python3 -u hsad.py");这样用;连起来才是正确的

        var rasyncht = cmd.BeginExecute();

        using (var reader = new StreamReader(cmd.OutputStream, Encoding.UTF8, true, 1024, true))
        {
            while (!rasynch.IsCompleted || !reader.EndOfStream)
            {
                string line = reader.ReadLine();
                if (line != null)
                {
                    Console.WriteLine(line)
                }
            }
        }

        cmd.EndExecute(rasynch);
        client.Disconnect();
    }
}

常见问题

  • 尽量使用CreateCommand或者RunCommand两个函数去执行。
  • 当运行的程序运行时间较长时需要等待程序的运行,下面的代码用于判断程序是否运行结束。
 while (!result.IsCompleted || !reader.EndOfStream)
  • 因为CreateCommand方法不使用终端仿真,而python程序在没有中断的情况下执行缓冲输出,因此在需要获得程序输出的情况下应当使用-u后缀。
python3 -u test.py 
  • 程序运行错误时注意检查程序里面的相对地址,当你使用绝对地址的命令运行程序时,程序内的地址需要相应的改为绝对地址。或者将命令分为先cd到程序目录再执行两步。

参考

How to continuously write output from Python Program running on a remote host (Raspberry Pi) executed with C# SSH.NET on local console? - Stack Overflowhttps://stackoverflow.com/questions/57609499/how-to-continuously-write-output-from-python-program-running-on-a-remote-host-rc# - Execute long time command in SSH.NET and display the results continuously in TextBox - Stack Overflowhttps://stackoverflow.com/questions/47386713/execute-long-time-command-in-ssh-net-and-display-the-results-continuously-in-tex

[C#.net资料]SSH远程操作Linux实时通信,上传下载 - 知乎 (zhihu.com)https://zhuanlan.zhihu.com/p/449829353

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值