Reputation: 623
I am using Visual Studio and C# web application . I am trying to move a file from Windows server to a remote Linux server using SSH.NET SshClient
. I am trying the below code, but the file is not getting copied.
var filespath = FUupload.PostedFile.FileName.Replace("\\", "/");
SshClient sshclient = new SshClient("hostname", "username", "pwd");
sshclient.Connect();
ShellStream stream = sshclient.CreateShellStream("cmsd", 80, 24, 800, 600, 1024);
Label1.Text = sendCommand("sudo su - wwabc1", stream).ToString();
Label2.Text = sendCommand("whoami", stream).ToString();
Label3.Text = sendCommand("cp /" + filespath + " /wwabc1/test/folder_one/test/", stream).ToString();
public StringBuilder sendCommand(string customCMD)
{
StringBuilder answer;
var reader = new StreamReader(stream);
var writer = new StreamWriter(stream);
writer.AutoFlush = true;
WriteStream(customCMD, writer, stream);
answer = ReadStream(reader);
return answer;
}
private void WriteStream(string cmd, StreamWriter writer, ShellStream stream)
{
writer.WriteLine(cmd);
while (stream.Length == 0)
{
Thread.Sleep(500);
}
}
private StringBuilder ReadStream(StreamReader reader)
{
StringBuilder result = new StringBuilder();
string line;
while ((line = reader.ReadLine()) != null)
{
result.AppendLine(line);
}
return result;
}
I am not getting any error, but the file is not moved.
Upvotes: 2
Views: 4479
Reputation: 202138
You cannot transfer a file between a local and a remote machine using shell commands.
Imagine, you are using an SSH terminal client (like PuTTY) instead. Can you use cp
command in PuTTY to upload a file? – you cannot.
You have to use SFTP protocol.
SftpClient sftpclient = new SftpClient("hostname", "username", "pwd");
sftpclient.connect();
string localFilename = FUupload.PostedFile.FileName;
string remoteFilename = "/wwabc1/test/folder_one/test/" + Path.GetFileName(filename);
using (var fileStream = File.OpenRead(localFilename))
{
sftpClient.UploadFile(fileStream, remoteFilename);
}
Upvotes: 1