首页 > 解决方案 > 从 C# 将相关命令执行到 SSH

问题描述

我试图从 C# 在 SSH 上执行连续命令我有三个命令 subcommand1、subcommand2 和 subcommand3。尽管成功连接到目标服务器,但我无法通过 C# 从下面获得结果,这在我在 putty 上运行命令时有效。我的主要目标是将文件从 oracle 服务器 140.X.XX.3 下载到 IP 上的本地 lynux 服务器,如下面的 MYIPADDRESS 所示。我做错了什么?

'using System;
using Renci.SshNet;
using Renci.SshNet.Common;
using System.Diagnostics;   
namespace SFTP_SHH
{
    class Program
    {
        static void Main(string[] args)
        {
            //Connection information
            string user = "username";
            string pass = "password";
            string host = "MYIPADDRESS ";
            string gainAcces = "sftp -o IdentityFile=/export/home/oracle/.ssh/rsps_rsa user@140.XX.XX.X;";
            //Set up the SSH connection    
          SshClient sshclient = new SshClient(host, user, pass);
                sshclient.Connect();
            string subcommand1 = gainAcces;
            string subcommand2 = "cd download";
            string subcommand3 = "get 2020-07-22_RESPONSYS_CRM_OUTGOING_CALLS2.csv.zip";
            SshCommand sc1 = sshclient.CreateCommand(subcommand1 && subcommand2 && subcommand3);
            sc1.Execute();                        
        }
      }
    }
'

标签: c#ssh

解决方案


您可以使用;将命令分成三个,

SshCommand sc1 = sshclient.CreateCommand(subcommand1 + ";" + subcommand2  + ";" + subcommand3);

您正在做的是&&在三个字符串之间使用 (AND) 运算符...这与您的想法不太一样。您可以将 && 运算符用作三个命令的一部分,方法是将其添加为字符串...而不是 c# 运算符(可能不适用于所有 linux 系统),

SshCommand sc1 = sshclient.CreateCommand(subcommand1 + "&&" + subcommand2  + "&&" + subcommand3);

推荐阅读