How to use SFTP with .pem file in C#.net? - c#

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 source code:
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:
sftp -i testsftp-key testsftp#sftp.xxx-xxx.com
put filename
here
testsftp-key :.pem filename(key file),
testsftp :username,
sftp.xxx-xxx.com :host address.
filename :file to be uploaded
File is not getting uploaded when exe is executed by rrot user/cronjob. Executing using non-root user like pi uploads the file.
Permissions are 777 for all.
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.
I took help from here:
How to capture Shell command output in C#?

Related

Running .cmd file by C#

I am using the mentioned code to run a cmd file. It is working properly in my local machine. However when I am running in a remote machine windows security warning is coming. How can i bypass that security warning. Any help?
string[] newFilePath = Directory.GetFiles(workingDir, "*.cmd");
foreach (var n in newFilePath) {
finishedOld = false;
Process p = new Process();
p.StartInfo.FileName = string.Format("\"" + n + "\"");
p.Start();
p.WaitForExit();
p.Dispose();
finishedOld = true;
}

Cannot access the file because it is being used by another process using ffmpeg

I am getting the error:
Cannot access the file because it is being used by another process
I have a C# desktop app.
I am using the Process class to convert images to a video file by using FFMPEG.
This is my code:
using (Process serverBuild = new Process())
{
serverBuild.StartInfo.WorkingDirectory = Environment.CurrentDirectory;
string args = " -f image2 -i " + {path} + "\\img%05d.jpg -s 352x288 -filter:v \"setpts=5.0*PTS\" -y " + {path}\\File.mp4;
serverBuild.StartInfo.Arguments = args;
serverBuild.StartInfo.FileName = "ffmpeg.exe";
serverBuild.StartInfo.UseShellExecute = false;
serverBuild.StartInfo.RedirectStandardOutput = true;
serverBuild.StartInfo.RedirectStandardError = true;
serverBuild.StartInfo.CreateNoWindow = true;
serverBuild.Start();
// string output = serverBuild.StandardOutput.ReadToEnd();
//Log.Instance.Debug(serverBuild.StandardError.ReadToEnd());
serverBuild.WaitForExit();
serverBuild.Close();
}
Directory.Delete(ExportRoute + FFMPEGPacket.LicenseKey + "\\" + FFMPEGPacket.Guid, true);
//which raise the error..
The images are all deleted but the File.Mp4 is not and that is the error. The error says that the newly created MP4 file cannot be deleted.
NB
This is partial code to illustrate the error
You may try the following code to create the file (it worked for me):
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = exe_path;
// replace your arguments here
psi.Arguments = string.Format(#" arguments ")
psi.CreateNoWindow = true;
psi.ErrorDialog = true;
psi.UseShellExecute = false;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.RedirectStandardOutput = true;
psi.RedirectStandardInput = false;
psi.RedirectStandardError = true;
Process exeProcess = Process.Start(psi);
exeProcess.PriorityClass = ProcessPriorityClass.High;
string outString = string.Empty;
exeProcess.OutputDataReceived += (s, e) =>
{
outString += e.Data;
};
exeProcess.BeginOutputReadLine();
string errString = exeProcess.StandardError.ReadToEnd();
Trace.WriteLine(outString);
Trace.TraceError(errString);
exeProcess.WaitForExit();
exeProcess.Close();
exeProcess.Dispose();
FFMPEG might still be rendering the creation of video from images after it closes, so it might be worth if you place a Threading.Thead.Sleep(5000) 5 secs; before delete.
Try that:
File.WriteAllBytes(path, new byte[0]);
File.Delete(path);

Input to processes (batch files)

I'm trying to make some kind of app, in C# Windows Forms Application (not console one, with tab pages, configuration, and console as a list box).
My problem is, that when I am writing some kind of input (to the text box), nothing happens (I'm new to coding).
My code:
Process process = new Process
{
StartInfo =
{
FileName = textBox2.Text,
//Arguments = textBox3.Text,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardInput = true,
CreateNoWindow = false,
}
};
server = process;
process.Start();
...
/* LATER */
...
serverInput = process.StandardInput;
...
serverInput.Write(textBoxInput.Text);
UPDATE - SOLVED: code:
serverInput.WriteLine(...);
Method 1:
This will be enough to run a batch files present in a directory:
string[] arrBatFiles = Directory.GetFiles(textBox2.Text, "*.bat"); //search at directory path
//loop through all batch files
foreach(string sFile in arrBatFiles)
{
Process.Start(sFile);
}
Method 2:
If you want to use ProcessStartInfo members, use following method:
public void ExecuteCommand(string sBatchFile, string command)
{
int ExitCode;
ProcessStartInfo ProcessInfo;
Process process;
string sBatchFilePath = textBox2.Text; //batch file Path
ProcessInfo = new ProcessStartInfo(sBatchFile, command);
ProcessInfo.CreateNoWindow = false;
ProcessInfo.UseShellExecute = false;
ProcessInfo.WorkingDirectory = Path.GetDirectoryName(sBatchFile);
// *** Redirect the output ***
ProcessInfo.RedirectStandardError = true;
ProcessInfo.RedirectStandardOutput = true;
process = Process.Start(ProcessInfo);
process.WaitForExit();
// *** Read the streams ***
string sInput = process.StardardInput.ReadToEnd();
string sOutput = process.StandardOutput.ReadToEnd();
string sError = process.StandardError.ReadToEnd();
ExitCode = process.ExitCode;
}
UPDATE:
How to call when you have directory of batch files.
string[] arrBatFiles = Directory.GetFiles(textBox2.Text, "*.bat"); //search at directory path
//loop through all batch files
foreach(string sFile in arrBatFiles)
{
ExecuteCommand(sFile, string.Empty); //string.Empty refer optional command args
}

Running exe from ASPX page and returning output

Below is my code to execute exe from the ASPX page,
string path = #"C:\Reshma\DATA\bbc1.pdf";
System.Diagnostics.Process si = new System.Diagnostics.Process();
si.StartInfo.WorkingDirectory = "c:\\";
si.StartInfo.UseShellExecute = false;
si.StartInfo.FileName = #"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe";
si.StartInfo.Arguments = "www.bbc.com"+" "+path;
si.StartInfo.CreateNoWindow = true;
si.StartInfo.RedirectStandardInput = true;
si.StartInfo.RedirectStandardOutput = true;
si.StartInfo.RedirectStandardError = true;
si.Start();
si.WaitForExit();
string output = si.StandardOutput.ReadToEnd();
si.Close();
Response.Write(output);
My problem is program doesnot exit and it doesnot renders output. I am trying to convert the webpage into pdf by passing 2 arguments. bbc1.pdf originates in the respective path but without any content.Any help will be greatly appreciated.

Starting Weka from command line through C#

I am trying to open Weka from cmd line, using C#. This is the code that I'm using. It's giving me an error for Weka.Start() line, and the error is : Win32 exception was unhandled. System cannot find the file specified. Please help me out. Thanks
ProcessStartInfo WekaStartInfo = new ProcessStartInfo(#"C:\Program Files\Weka- 3-6\java -Xmx1536m -jar weka.jar");
WekaStartInfo.UseShellExecute = false;
WekaStartInfo.RedirectStandardOutput = true;
WekaStartInfo.RedirectStandardError = true;
WekaStartInfo.CreateNoWindow = false;
Process Weka = new Process();
Weka.StartInfo = WekaStartInfo;
Weka.Start();
string output = Weka.StandardOutput.ReadToEnd();
Weka.WaitForExit();
There are two options to start WEKA from a
C# application.
In the WEKA install directory there is a
batch file called RunWeka.bat. To start WEKA
using this batch file use the following
code:
ProcessStartInfo wekaStartInfo =
new ProcessStartInfo(#"c:\Program Files\Weka-3-6\runweka.bat", "default");
wekaStartInfo.WorkingDirectory = #"c:\Program Files\Weka-3-6";
wekaStartInfo.UseShellExecute = false;
wekaStartInfo.RedirectStandardOutput = true;
wekaStartInfo.RedirectStandardError = true;
wekaStartInfo.CreateNoWindow = false;
using(Process weka = new Process())
{
weka.StartInfo = wekaStartInfo;
weka.Start();
}
To start WEKA without using the batch file
use the following code:
ProcessStartInfo wekaStartInfo =
new ProcessStartInfo(#"javaw", #"-classpath . RunWeka -i .\RunWeka.ini -w .\weka.jar -c default");
wekaStartInfo.WorkingDirectory = #"c:\Program Files\Weka-3-6";
wekaStartInfo.UseShellExecute = false;
wekaStartInfo.RedirectStandardOutput = true;
wekaStartInfo.RedirectStandardError = true;
wekaStartInfo.CreateNoWindow = false;
using(Process weka = new Process())
{
weka.StartInfo = wekaStartInfo;
weka.Start();
}
In both cases you have to set the working directory.
You've probably specified incorrect or inexistent location for your process based on the error description. Check that the path specified in ProcessStartInfo is correct.
Maybe, there are unnecessary spaces in the declaration here:
ProcessStartInfo WekaStartInfo = new ProcessStartInfo(#"C:\Program Files\Weka-3-6\java -Xmx1536m -jar weka.jar");
In the constructor of ProcessStartInfo you must either enter just the application name, or specify the arguments separate;
ProcessStartInfo WekaStartInfo = new ProcessStartInfo(
#"C:\Program Files\Weka-3-6\java.exe",
#"-Xmx1536m -jar weka.jar");

Categories

Resources