在 C# 中使用 pscp 通过 post 请求在 Windows 和 Linux 之间传输文件

Using pscp in C# for file transfer between Windows and Linux through a post request

我一直在尝试通过 C# 代码传输文件,但它似乎不起作用。尽管命令提示符中的以下行工作正常。

"C:\Program Files (x86)\PuTTY\pscp.exe" -l user -pw password C:\Users\user1\Desktop\transfer1.txt 000.000.00.000:/home/doc

通信class是

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace Server.Controllers
{     
    public class ComLinux
    {
        public static string TransferFilesToSever(string args)
        {
        Process p = new Process();

        p.StartInfo.FileName = @"C:\Program Files (x86)\PuTTY\pscp.exe";
        p.StartInfo.Arguments = args;
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardInput = true;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.CreateNoWindow = false;
        p.Start();
        string output = p.StandardOutput.ReadToEnd();
        p.WaitForExit(); 
        return "Done";
   }}}

并且 SendFilesController 看起来像

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace Server.Controllers
{
    [Route("api/[controller]")]
    public class SendFilesController : Controller
    {
        [HttpPost]
        public IActionResult Post([FromBody] string cmdTostart)
        {
        var WindowsPath = ConfigurationManager.AppSettings["WindowsPath"].ToString();
        var LinuxPath = ConfigurationManager.AppSettings["LinuxPath"].ToString();
        var LinuxUserPass = ConfigurationManager.AppSettings["LinuxUserPass"].ToString();
        var WindowcommandtoL = LinuxUserPass + " " + WindowsPath + "transfer1.txt" + " " + LinuxPath;
        var resultw = ComLinux.TransferFilesToSever(WindowcommandtoL); 
        return Content("OK");
    }}}

app.config中,我有

<add key="LinuxUserPass" value="-l user -pw password"/>
<add key="WindowsPath" value="C:\Users\user1\Desktop\"/>
<add key="LinuxPath" value="000.00.000://home/doc"/>

发出 post 请求时,HTTP 代码为 200,但文件未移动到 Linux 服务器。我不确定这里出了什么问题。

当我 运行 通过位于 localhost:49595 的 IIS Express 处于调试模式时,代码似乎可以工作。但是一旦我将它发布到网站上,它就不起作用了。 p.Exitcode 为 1,p.ouput 为空。

首先,使用外部应用程序上传SCP是错误的。

改用一些本机 .NET SCP 实现。参见 Library to do SCP for C#


无论如何,一个明显的问题是您的命令不包含 -hostkey 开关。您需要验证 SSH 主机密钥指纹。如果您曾经连接过 PuTTY/PSCP,系统会提示您验证主机密钥。如果这样做,经过验证的主机密钥将缓存在 Windows 注册表中。这就是您的代码在使用本地帐户在本地计算机上执行时有效的原因。

但是如果您 运行 代码在另一台机器上或使用另一个帐户,它将无法工作,因为那里没有验证主机密钥。

您应该将 -hostkey switch 包含在您的主机密钥指纹中。

我无法发送文件的原因是应用程序池身份是默认的,我不得不将其更改为我的用户名。

尽管我决定不使用 pscp 而是使用 ssh.net 库。非常感谢 Martin Prikryl