tamirgal.com logo


SharpSSH examples

The following samples are raw examples of how to directly use the JSch API from sharpSSH. The samples were translated from the java examples found on JSch homepage.

Please select a sample:


AES.cs | ChangePassphrase.cs | KeyGen.cs | KnownHosts.cs | PortForwardingL.cs | PortForwardingR.cs | ScpFrom.cs | Scp.cs | ScpTo.cs | Sftp.cs | Shell.cs | SshExeTest.cs | SshExpectTest.cs | SshFileTransferTest.cs | SshShellTest.cs | StreamForwarding.cs | Subsystem.cs | UserAuthPubKey.cs | Util.cs | README.txt |

Scp.cs

1using System;
2using Tamir.SharpSsh.jsch;
3using System.IO;
4using System.Text;
5using System.Collections;
6
7/* 
8 * Scp.cs
9 * 
10 * Copyright (c) 2006 Tamir Gal, http://www.tamirgal.com, All rights reserved.
11 * 
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions are met:
14 *
15 *  	1. Redistributions of source code must retain the above copyright notice,
16 *		this list of conditions and the following disclaimer.
17 *
18 *	    2. Redistributions in binary form must reproduce the above copyright 
19 *		notice, this list of conditions and the following disclaimer in 
20 *		the documentation and/or other materials provided with the distribution.
21 *
22 *	    3. The names of the authors may not be used to endorse or promote products
23 *		derived from this software without specific prior written permission.
24 *
25 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
26 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
27 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR
28 *  *OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
29 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
30 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
31 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
32 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
33 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
34 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35 * 
36 **/
37
38namespace Tamir.SharpSsh
39{
40	/// <summary>
41	/// Class for handling SCP file transfers over SSH connection.
42	/// </summary>
43	public class Scp : SshTransferProtocolBase
44	{
45		private bool m_recursive = false;
46		private bool m_verbos = false;
47		private bool m_cancelled = false;
48
49		public Scp(string host, string user, string password)
50			: base(host, user, password)
51		{
52		}
53
54		public Scp(string host, string user)
55			: base(host, user)
56		{
57		}
58
59		protected override string ChannelType
60		{
61			get { return "exec"; }
62		}
63
64		/// <summary>
65		///This function is empty, so no channel is connected
66		///on session connect 
67		/// </summary>
68		protected override void ConnectChannel()
69		{
70		}
71
72		/// <summary>
73		/// Gets or sets a value indicating the default recursive transfer behaviour
74		/// </summary>
75		public bool Recursive
76		{
77			get{return m_recursive;}
78			set{m_recursive=value;}
79		}
80
81		/// <summary>
82		/// Gets or sets a value indicating whether trace information should be printed
83		/// </summary>
84		public bool Verbos
85		{
86			get{return m_verbos;}
87			set{m_verbos=value;}
88		}
89
90		public override void Cancel()
91		{
92			m_cancelled = true;
93		}
94
95		/// <summary>
96		/// Creates a directory on the remot server
97		/// </summary>
98		/// <param name="dir">The new directory</param>
99		public override void Mkdir(string dir)
100		{
101			SCP_CheckConnectivity();
102
103			Channel channel=null;
104			Stream server = null;
105			m_cancelled=false;
106
107			SCP_ConnectTo(out channel, out server, dir, true);
108			SCP_EnterIntoDir(server, dir);
109			channel.disconnect();
110		}
111
112		public override void Put(string fromFilePath, string toFilePath)
113		{
114			this.To(fromFilePath, toFilePath);
115		}
116
117		public override void Get(string fromFilePath, string toFilePath)
118		{
119			this.From(fromFilePath, toFilePath);
120		}
121
122
123
124		/// <summary>
125		/// Copies a file from local machine to a remote SSH machine.
126		/// </summary>
127		/// <param name="localPath">The local file path.</param>
128		/// <param name="remotePath">The path of the remote file.</param>
129		public void To(string localPath, string remotePath)
130		{
131			this.To(localPath, remotePath, Recursive);
132		}
133
134
135		/// <summary>
136		/// Copies a file from local machine to a remote SSH machine.
137		/// </summary>
138		/// <param name="localPath">The local file path.</param>
139		/// <param name="remotePath">The path of the remote file.</param>
140		public void To(string localPath, string remotePath, bool _recursive)
141		{
142			SCP_CheckConnectivity();
143
144			Channel channel=null;
145			Stream server = null;
146			m_cancelled=false;
147 
148			try
149			{
150				//if we are sending a single file
151				if(File.Exists(localPath))
152				{
153					SCP_ConnectTo(out channel, out server, remotePath, _recursive);
154					SCP_SendFile(server, localPath, remotePath);					
155					channel.disconnect();
156				}
157				//else, if we are sending a local directory
158				else if(Directory.Exists(localPath))
159				{
160					if(!_recursive)
161					{
162						throw new SshTransferException(Path.GetFileName("'"+localPath)+"' is a directory, you should use recursive transfer.");
163					}
164					SCP_ConnectTo(out channel, out server, remotePath, true);
165					ToRecursive(server, localPath, remotePath);
166					channel.disconnect();
167				}
168				else
169				{
170					throw new SshTransferException("File not found: "+localPath);
171				}
172			}
173			catch(Exception e)
174			{
175				if(Verbos)
176					Console.WriteLine("Error: "+e.Message);				
177				//SendEndMessage(remoteFile, localFile, filesize,filesize, "Transfer ended with an error.");
178				try{channel.disconnect();}
179				catch{}
180				throw e;
181			}
182		}
183
184		/// <summary>
185		/// Copies files and directories from local machine to a remote SSH machine using SCP.
186		/// </summary>
187		/// <param name="server">I/O Stream for the remote server</param>
188		/// <param name="src">Source to copy</param>
189		/// <param name="dst">Destination path</param>
190		private void ToRecursive(Stream server, string src, string dst)
191		{
192			if(Directory.Exists(src))
193			{
194				SCP_EnterIntoDir(server, Path.GetFileName(dst));
195				foreach(string file in Directory.GetFiles(src))
196				{
197					SCP_SendFile(server, file, Path.GetFileName( file));
198				}
199				if(m_cancelled)
200				{
201					return;
202				}
203				foreach(string dir in Directory.GetDirectories(src))
204				{
205					ToRecursive(server, dir, Path.GetFileName(dir));
206				}
207			}
208			else if(File.Exists(src))
209			{
210				SCP_SendFile(server, src, Path.GetFileName(src));
211			}
212			else
213			{
214				throw new SshTransferException("File not found: "+src);
215			}
216		}
217
218		/// <summary>
219		/// Copies a file from a remote SSH machine to the local machine using SCP.
220		/// </summary>
221		/// <param name="remoteFile">The remmote file name</param>
222		/// <param name="localPath">The local destination path</param>
223		public void From(string remoteFile, string localPath)
224		{
225			this.From(remoteFile, localPath, Recursive);
226		}
227
228		/// <summary>
229		/// Copies a file from a remote SSH machine to the local machine using SCP.
230		/// </summary>
231		/// <param name="remoteFile">The remmote file name</param>
232		/// <param name="localPath">The local destination path</param>
233		/// <param name="recursive">Value indicating whether a recursive transfer should take place</param>
234		public void From(string remoteFile, string localPath, bool _recursive)
235		{
236			SCP_CheckConnectivity();
237
238			Channel channel=null;
239			Stream server = null;
240			m_cancelled=false;
241			int filesize=0;
242			String filename=null;
243			string cmd = null;
244
245			try
246			{
247				String dir=null;
248				if(Directory.Exists(localPath))
249				{
250					dir= Path.GetFullPath( localPath );
251				}
252
253				SCP_ConnectFrom(out channel, out server, remoteFile, _recursive);				
254
255				byte[] buf=new byte[1024];
256
257				// send '\0'
258				SCP_SendAck(server);
259				int c=SCP_CheckAck(server);
260				
261				//parse scp commands
262				while((c=='D')||(c=='C')||(c=='E'))
263				{
264					if(m_cancelled)
265						break;
266
267					cmd = ""+(char)c;
268					if(c=='E')
269					{
270						c=SCP_CheckAck(server);
271						dir = Path.GetDirectoryName(dir);
272						if(Verbos) Console.WriteLine("E");
273						//send '\0'
274						SCP_SendAck(server);
275						c=(char)SCP_CheckAck(server);
276						continue;
277					}
278					
279					// read '0644 ' or '0755 '
280					server.Read(buf, 0, 5);
281					for(int i=0;i<5;i++)
282						cmd+=(char)buf[i];
283					
284					//reading file size
285					filesize=0;
286					while(true)
287					{
288						server.Read(buf, 0, 1);
289						if(buf[0]==' ')break;
290						filesize=filesize*10+(buf[0]-'0');
291					}					
292
293					//reading file name					
294					for(int i=0;;i++)
295					{
296						server.Read(buf, i, 1);
297						if(buf[i]==(byte)0x0a)
298						{
299							filename=Util.getString(buf, 0, i);							
300							break;
301						}
302					}
303					cmd += " "+filesize+" "+filename;
304					// send '\0'
305					SCP_SendAck(server);
306
307					//Receive file
308					if(c=='C')
309					{
310						if(Verbos) Console.WriteLine("Sending file modes: "+cmd);
311						SCP_ReceiveFile(server, remoteFile, 
312							dir==null?localPath:dir+"/"+filename,
313							filesize);
314
315						if(m_cancelled)
316							break;
317						
318						// send '\0'
319						SCP_SendAck(server);
320					}
321					//Enter directory
322					else if(c=='D')
323					{
324						if(dir==null)
325						{
326							if(File.Exists(localPath)) throw new SshTransferException("'"+localPath+"' is not a directory");
327							dir = localPath;
328							Directory.CreateDirectory(dir);
329						}
330						if(Verbos) Console.WriteLine("Entering directory: "+cmd);
331						dir += "/"+filename;
332						Directory.CreateDirectory(dir);
333					}
334
335					c=SCP_CheckAck(server);
336				}				
337				channel.disconnect();
338			}
339			catch(Exception e)
340			{
341				if(Verbos)
342					Console.WriteLine("Error: "+e.Message);				
343				try
344				{
345					channel.disconnect();
346				}
347				catch{}
348				throw e;
349			}
350		}
351		#region SCP private functions   ...		#endregion SCP private functions
577	}
578}
579

Copyright (c) 2005 TamirGal.Com