I have below code for run a putty with authentication from C#
private void button1_Click(object sender, EventArgs e)
{
ProcessStartInfo cmd = new ProcessStartInfo();
cmd.FileName = "putty.exe";
cmd.UseShellExecute = false;
cmd.RedirectStandardInput = true;
cmd.RedirectStandardOutput = true;
cmd.Arguments = "-ssh " + username + host+ " -pw " + upassword;
using (Process process = Process.Start(cmd))
{
process.WaitForExit();
}
}
The above code is launching putty and authenticating the user and password.
I want to execute some commands after launching the putty. I used below code
private void button1_Click(object sender, EventArgs e)
{
ProcessStartInfo cmd = new ProcessStartInfo();
cmd.FileName = "putty.exe";
cmd.UseShellExecute = false;
cmd.RedirectStandardInput = true;
cmd.RedirectStandardOutput = true;
cmd.Arguments = "-ssh " + username + host+ " -pw " + upassword+ "-m "+path;;
using (Process process = Process.Start(cmd))
{
process.WaitForExit();
}
}
The path variable contains the location of the file and file contain below text in it
ssh webhostname
While executing the above code, putty is launched but during authentication putty terminated with message "Unauthorized access to this machine is prohibited"
Is there anyway we can run the commands in putty from a file?
Related
When users click on a button, I want it to run the logon script(launching from server), but each computer in different servers, so I get the server name. But the netlogon.StartInfo.Arguments = slnres + #"/c \netlogon\logon.cmd"; line is not working as it should be. It should run the logon.cmd on the PC(mapping network drivers, printers, etc), and then the CMD should close.
private void MapNetwork_Click(object sender, EventArgs e)
{
Process sln = new Process();
sln.StartInfo.UseShellExecute = false;
sln.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
sln.StartInfo.FileName = "cmd.exe";
sln.StartInfo.Arguments = "/c echo %logonserver%";
sln.StartInfo.RedirectStandardOutput = true;
sln.Start();
string slnres = sln.StandardOutput.ReadToEnd();
label1.Text = slnres;
Process netlogon = new Process();
netlogon.StartInfo.UseShellExecute = false;
netlogon.StartInfo.FileName = "cmd.exe";
netlogon.StartInfo.Arguments = slnres + #"/c \netlogon\logon.cmd";
netlogon.Start();
}
A couple things:
You don't need to run a command prompt to get an environment variable. You can use Environment.GetEnvironmentVariable.
Your Arguments property for your call to logon.cmd is being constructed into this:
\\myserver/c \netlogon\logon.cmd
When I think you want this:
/c \\myserver\netlogon\logon.cmd
So make sure you put slnres at the right place in your string. Your code should look like this:
private void MapNetwork_Click(object sender, EventArgs e)
{
string slnres = Environment.GetEnvironmentVariable("logonserver");
label1.Text = slnres;
Process netlogon = new Process();
netlogon.StartInfo.UseShellExecute = false;
netlogon.StartInfo.FileName = "cmd.exe";
netlogon.StartInfo.Arguments = "/c " + slnres + #"\netlogon\logon.cmd";
netlogon.Start();
}
i am a little confused about your question and i am not rly sure if i understand you correctly. some time ago i made a program where i had to run few powershell commands, so i made a class for it. redirected to your button it would look like that:
(and remember you need the fqdn to your file location => Reading File From Network Location)
using System.Diagnostics;
//class lvl scope vars
string output;
string ErrorOutput;
private void MapNetwork_Click(object sender, EventArgs e)
{
//define process arguments
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = #"cmd.exe";
startInfo.Arguments = #"FQDN path to your file on the server; exit";
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
//start process
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
//outpunt handling
if (string.IsNullOrEmpty(ErrorOutput))
{
return output;
}
else
{
return ErrorOutput;
}
}
first of all i would check if your application is able to open the file one the shared network location. (server available? access rights to server? serer mapped?)
after that you can check if he is able to start the file locally. (does it need admin rights to run the *.cmd, *.bat file)
now you can check if your application runs it correctly.
I'm trying to connect to a linux machine via pLink and PuTTY to transfer some .txt file. Right now I'm just trying to make the connection work. I have a small window with 2 textboxes (username,linux1) and a password box (pwbox1), and a button that when you click, it should connect you to the linux machine!
Here's my code:
private void button1_Click(object sender, RoutedEventArgs e)
{
string user = username.Text;
string passw = pwbox1.Password;
string linuxHst = linux1.Text;
ProcessStartInfo psi = new ProcessStartInfo(#"C:\Program Files (x86)\PuTTY\plink.exe", user + "#" + linuxHst + " -pw " + passw);
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
psi.WindowStyle = ProcessWindowStyle.Normal;
psi.UseShellExecute = false;
psi.CreateNoWindow = false;
Process process = Process.Start(psi);
process.WaitForExit(5000);
}
The problem is that when I try this with the console application it works, without the textboxes! but I need it to work with WPF.
Can anyone please tell me what I'm doing wrong? am I missing something?
I am writing a backup program using xcopy and because there are a lot of large files it takes a while so I want to show the progress. When I try to use StreamReader to get the standard output, it has this error message when I debug. "Cannot mix synchronous and asynchronous operation on process stream."
public void backup_worker_DoWork(object sender, DoWorkEventArgs e)
{
int loop = 1;
backup_worker.WorkerReportsProgress = true;
Process xcopy = new Process();
ProcessStartInfo startinfo = new ProcessStartInfo();
startinfo.CreateNoWindow = true;
startinfo.UseShellExecute = false;
startinfo.RedirectStandardError = true;
startinfo.RedirectStandardOutput = true;
startinfo.FileName = Environment.CurrentDirectory + "\\xcopy.exe";
startinfo.Arguments = '"' + source + '"' + " " + '"' + target + '"' + " " + "/s /e /y";
xcopy.StartInfo.RedirectStandardOutput = true;
xcopy.StartInfo = startinfo;
xcopy.Start();
xcopy.BeginErrorReadLine();
xcopy.BeginOutputReadLine();
StreamReader sr = xcopy.StandardOutput;
while (loop > 0)
{
progress = sr.ReadLine();
output_list.Items.Add(progress);
}
xcopy.OutputDataReceived += new DataReceivedEventHandler(backup_worker_OutputDataRecieved);
xcopy.ErrorDataReceived += new DataReceivedEventHandler(backup_worker_ErrorDataReceived);
xcopy.WaitForExit();
backup_worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backup_worker_RunWorkerCompleted);
}
void backup_worker_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
}
void backup_worker_OutputDataRecieved(object sender, DataReceivedEventArgs e)
{
}
void backup_worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Completed");
}
Please help.
Thanks in advance
The problem is that you're using both synchronous and asynchronous output:
// Using async version here...
xcopy.BeginOutputReadLine();
StreamReader sr = xcopy.StandardOutput;
while (loop > 0)
{
// Trying to use synchronous reading here
progress = sr.ReadLine();
You need to design your algorithm to use one option or the other, but not both.
The below note from MSDN should make it very clear, what the problem is
You cannot mix asynchronous and synchronous read operations on a redirected stream. Once the redirected stream of a Process is opened in either asynchronous or synchronous mode, all further read operations on that stream must be in the same mode. For example, do not follow BeginErrorReadLine with a call to ReadLine on the StandardError stream, or vice versa. However, you can read two different streams in different modes. For example, you can call BeginErrorReadLine and then call ReadLine for the StandardOutput stream.
Your code should be more on the lines as below
public void backup_worker_DoWork(object sender, DoWorkEventArgs e) {
int loop = 1;
// This should ideally not be in the DoWork, but where you setup or create the worker
backup_worker.WorkerReportsProgress = true;
backup_worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backup_worker_RunWorkerCompleted);
backup_worker.WorkerSupportsCancellation = true;
// setup your scopy process
ProcessStartInfo startinfo = new ProcessStartInfo();
startinfo.CreateNoWindow = true;
startinfo.UseShellExecute = false;
startinfo.RedirectStandardError = true;
startinfo.RedirectStandardOutput = true;
startinfo.FileName = Environment.CurrentDirectory + "\\xcopy.exe";
startinfo.Arguments = "/s /e /y " + '"' + source + '"' + " " + '"' + target + '"' + " ";
Process xcopy = new Process();
xcopy.StartInfo = startinfo;
xcopy.ErrorDataReceived += new DataReceivedEventHandler(backup_worker_ErrorDataReceived);
// start the xcopy and read the output
xcopy.Start();
xcopy.BeginErrorReadLine();
string copiedFileName;
while ((copiedFileName = xcopy.StandardOutput.ReadLine()) != null) {
output_list.Items.Add(copiedFileName);
}
// we should be done when here, but doesen't hurt to wait
xcopy.WaitForExit();
}
void backup_worker_ErrorDataReceived(object sender, DataReceivedEventArgs e) {
MessageBox.Show("We have a problem. Figure what needs to be done here!");
}
void backup_worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled == true) {
MessageBox.Show("Canceled!");
} else if (e.Error != null) {
MessageBox.Show("Error: " + e.Error.Message);
} else {
MessageBox.Show("Completed!");
}
}
If you want to do the synchronous way,
instead of
xcopy.BeginOutputReadLine()
use
string s = xcopy.StandardOutput.ReadToEnd()
be warned, that if you do that for both the output and the error, and one of them is too long, you can hit a deadlock.
I'm trying to use the following C# code to compile Java using javac:
Process p = new Process();
p.StartInfo.FileName = "javac";
Directory.CreateDirectory(Application.StartupPath + #"/TempJava");
p.StartInfo.Arguments = "-d "Application.StartupPath + #"/TempJava" + files;
p.Start();
"files" represents a string variable containing the name(s) of the *.java files.
All in all, I want to create a new folder, and then take the Java files (from where ever they may be located) and compile it into a class file(s) in TempJava.
For some reason, the code doesn't work, no errors, no warnings, but when I run it and check TempJava, there's no files in it.
Just because your child process ends with a possible error, it doesn't mean your parent process must be aware of it.
Inspect the process' exit code and standard output stream, and especially the standard error stream. Your answer lies in there...
here i have 2 buttons run and compile here is some code to help.
private void comp_Click(object sender, EventArgs e)
{
string text = "javac " + label1.Text + file + "#pause" + "#stop";
text = text.Replace("#", System.Environment.NewLine);
File.WriteAllText(label1.Text + "Compile.bat", text);
Process proc = null;
try
{
proc = new Process();
proc.StartInfo.FileName = label1.Text + "Compile.bat";
proc.StartInfo.CreateNoWindow = false;
proc.Start();
proc.WaitForExit();
}
catch
{
}
}
private void runp_Click(object sender, EventArgs e)
{
string news = file.Remove(file.Length - 5);
string text = "java " + news + "#pause";
text = text.Replace("#", System.Environment.NewLine);
File.WriteAllText(label1.Text + "Run.bat", text);
Process proc = null;
try
{
proc = new Process();
proc.StartInfo.FileName = label1.Text + "Run.bat";
proc.StartInfo.WorkingDirectory = label1.Text.Remove(label1.Text.Length - 1);
proc.StartInfo.CreateNoWindow = true;
proc.Start();
proc.WaitForExit();
}
catch
{
}
}
all i really do is create a batch and run it using c#.
Hi I've used the below code in C# to take the backup of a database in PostgreSQL.This code runs when the backup button is clicked
private void lnkSCBackup_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.Filter = "Postgre backups (*.backup)|*.backup";
save.ShowDialog();
if (save.FileName != "")
{
string saveFileName = "\"" + save.FileName + "\"";
string host = S ystem.Configuration.ConfigurationSettings.AppSettings["HOST"].ToString().Trim();
string port = System.Configuration.ConfigurationSettings.AppSettings["PORT"].ToString().Trim();
string userName = System.Configuration.ConfigurationSettings.AppSettings["USERNAME"].ToString().Trim();
string password = System.Configuration.ConfigurationSettings.AppSettings["PASSWORD"].ToString().Trim();
string dataBase = System.Configuration.ConfigurationSettings.AppSettings["DATABASE"].ToString().Trim();
try
{
string Creten = "pg_dump -h " + host + " -U " + userName + " -p " + port + " -F c -b -v " + dataBase + " > " + saveFileName;
try
{
// create the ProcessStartInfo using "cmd" as the program to be run,
// and "/c " as the parameters.
// Incidentally, /c tells cmd that we want it to execute the command that follows,
// and then exit.
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.ProcessStartInfo("cmd", "/c " + Creten);
// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
proc.WaitForExit();
// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();
//Gets the total processing time for this particular process
string totalProcessingTime = proc.TotalProcessorTime.Ticks.ToString();
//progress bar working
progressBar1.Visible = true;
progressBar1.BringToFront();
progressBar1.Minimum = 0;
progressBar1.Maximum = int.Parse(totalProcessingTime);
progressBar1.Step = 500;
progressBar1.Value = 0;
this.lblBackup.Visible = true;
this.lblBackup.Text = "Backing Up Database";//To show the user it is backing up
this.lblBackup.Font = new Font("Microsoft Sans Serif", 9, System.Drawing.FontStyle.Regular);
this.Refresh();
while (progressBar1.Value < progressBar1.Maximum)
{
progressBar1.Value += 10;//= 10000;
}
progressBar1.Visible = false;
this.lblBackup.Visible = false;
int exitCode = proc.ExitCode;
if (exitCode.Equals(0))
{
MessageBox.Show(" Backup Success ");
}
else
{
MessageBox.Show(" Backup not Success ");
}
}
catch (Exception objException)
{
// Log the exception
}
}
Now my problem is this part of code works fine in my system and the backup is taken properly.
But does not work in another system it finally comes and gets stuck in statement
string result = proc.StandardOutput.ReadToEnd();
Does anyone have an idea why this could happen??The same code not working in different PC'S??? Could this be a PostgreSQL issue
Thanks in advance!!!!
It's not all strange that "The same code not working in different PC'S", as different machines can have different environments. For one thing, your are invoking the system command
pg_dump -h " + host + " -U " + userName + " -p " + port + " -F c -b -v " + dataBase
Have you checked that it works in the second machine? (i.e. pg_dump is in your path AND you can connect to your pg DB with those parameters)?