简体   繁体   English

如何在 C#.net 中使用带有.pem 文件的 SFTP?

[英]How to use SFTP with .pem file in C#.net?

Problem: I am using C# .net platform to SFTP a file to remote host with a key file/.pem file and no password.问题:我正在使用 C# .net 平台使用密钥文件/.pem 文件和无密码将文件 SFTP 到远程主机。

C#.net source code: C#.net 源代码:

ProcessStartInfo p = new ProcessStartInfo
{
    FileName = "sh",
    Arguments = "upload.sh " + file
};
p.RedirectStandardOutput = true;
p.UseShellExecute = false;
p.CreateNoWindow = true;
Process proc1 = new Process();
proc1.StartInfo = p;
proc1.Start();
string result = proc1.StandardOutput.ReadToEnd();
log.InfoFormat(result);

upload.sh:上传.sh:

sftp -i testsftp-key testsftp@sftp.xxx-xxx.com
put  filename

here这里

  1. testsftp-key:.pem filename(key file), testsftp-key:.pem 文件名(密钥文件),
  2. testsftp:username,测试ftp:用户名,
  3. sftp.xxx-xxx.com:host address. sftp.xxx-xxx.com:主机地址。
  4. filename:file to be uploaded文件名:要上传的文件

File is not getting uploaded when exe is executed by rrot user/cronjob. rrot 用户/cronjob 执行 exe 时文件未上传。 Executing using non-root user like pi uploads the file.使用像 pi 这样的非 root 用户执行会上传文件。 Permissions are 777 for all.所有人的权限都是 777。

Error :错误

permission denied

How to solve this permission issue?如何解决这个权限问题?

I found an answer to this:我找到了一个答案:

ProcessStartInfo p = new ProcessStartInfo
{
    FileName = "sh",
    Arguments = "/home/pi/../upload.sh " + file
};
p.RedirectStandardOutput = true;
p.RedirectStandardError = true;
p.UseShellExecute = false;
p.CreateNoWindow = false;
Process proc1 = new Process();
proc1.StartInfo = p;
proc1.Start();
string result = "";
using (System.IO.StreamReader output = proc1.StandardOutput) 
{
    result = output.ReadToEnd();
}
string error = "";
using (System.IO.StreamReader output = proc1.StandardError)
{
    error = output.ReadToEnd();
}
log.InfoFormat("SFTP result: {0}", result);
log.InfoFormat("{0}", error);

I am capturing the redirected stdout and stderr using streamreader.我正在使用流读取器捕获重定向的标准输出和标准错误。 Now i can see the script upload.sh being run successfully and uploading the file to the remote server as well.现在我可以看到脚本upload.sh 正在成功运行并将文件上传到远程服务器。 I took help from here: How to capture Shell command output in C#?我从这里得到帮助: 如何在 C# 中捕获 Shell 命令 output?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM