KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > ch > ethz > ssh2 > SCPClient


1
2 package ch.ethz.ssh2;
3
4 import java.io.BufferedInputStream JavaDoc;
5 import java.io.BufferedOutputStream JavaDoc;
6 import java.io.File JavaDoc;
7 import java.io.FileInputStream JavaDoc;
8 import java.io.FileOutputStream JavaDoc;
9 import java.io.IOException JavaDoc;
10 import java.io.InputStream JavaDoc;
11 import java.io.OutputStream JavaDoc;
12
13 /**
14  * A very basic <code>SCPClient</code> that can be used to copy files from/to
15  * the SSH-2 server. On the server side, the "scp" program must be in the PATH.
16  * <p>
17  * This scp client is thread safe - you can download (and upload) different sets
18  * of files concurrently without any troubles. The <code>SCPClient</code> is
19  * actually mapping every request to a distinct {@link Session}.
20  *
21  * @author Christian Plattner, plattner@inf.ethz.ch
22  * @version $Id: SCPClient.java,v 1.11 2006/08/02 11:57:12 cplattne Exp $
23  */

24
25 public class SCPClient
26 {
27     Connection conn;
28
29     class LenNamePair
30     {
31         long length;
32         String JavaDoc filename;
33     }
34
35     public SCPClient(Connection conn)
36     {
37         if (conn == null)
38             throw new IllegalArgumentException JavaDoc("Cannot accept null argument!");
39         this.conn = conn;
40     }
41
42     private void readResponse(InputStream JavaDoc is) throws IOException JavaDoc
43     {
44         int c = is.read();
45
46         if (c == 0)
47             return;
48
49         if (c == -1)
50             throw new IOException JavaDoc("Remote scp terminated unexpectedly.");
51
52         if ((c != 1) && (c != 2))
53             throw new IOException JavaDoc("Remote scp sent illegal error code.");
54
55         if (c == 2)
56             throw new IOException JavaDoc("Remote scp terminated with error.");
57
58         String JavaDoc err = receiveLine(is);
59         throw new IOException JavaDoc("Remote scp terminated with error (" + err + ").");
60     }
61
62     private String JavaDoc receiveLine(InputStream JavaDoc is) throws IOException JavaDoc
63     {
64         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(30);
65
66         while (true)
67         {
68             /* This is a random limit - if your path names are longer, then adjust it */
69
70             if (sb.length() > 8192)
71                 throw new IOException JavaDoc("Remote scp sent a too long line");
72
73             int c = is.read();
74
75             if (c < 0)
76                 throw new IOException JavaDoc("Remote scp terminated unexpectedly.");
77
78             if (c == '\n')
79                 break;
80
81             sb.append((char) c);
82
83         }
84         return sb.toString();
85     }
86
87     private LenNamePair parseCLine(String JavaDoc line) throws IOException JavaDoc
88     {
89         /* Minimum line: "xxxx y z" ---> 8 chars */
90
91         long len;
92
93         if (line.length() < 8)
94             throw new IOException JavaDoc("Malformed C line sent by remote SCP binary, line too short.");
95
96         if ((line.charAt(4) != ' ') || (line.charAt(5) == ' '))
97             throw new IOException JavaDoc("Malformed C line sent by remote SCP binary.");
98
99         int length_name_sep = line.indexOf(' ', 5);
100
101         if (length_name_sep == -1)
102             throw new IOException JavaDoc("Malformed C line sent by remote SCP binary.");
103
104         String JavaDoc length_substring = line.substring(5, length_name_sep);
105         String JavaDoc name_substring = line.substring(length_name_sep + 1);
106
107         if ((length_substring.length() <= 0) || (name_substring.length() <= 0))
108             throw new IOException JavaDoc("Malformed C line sent by remote SCP binary.");
109
110         if ((6 + length_substring.length() + name_substring.length()) != line.length())
111             throw new IOException JavaDoc("Malformed C line sent by remote SCP binary.");
112
113         try
114         {
115             len = Long.parseLong(length_substring);
116         }
117         catch (NumberFormatException JavaDoc e)
118         {
119             throw new IOException JavaDoc("Malformed C line sent by remote SCP binary, cannot parse file length.");
120         }
121
122         if (len < 0)
123             throw new IOException JavaDoc("Malformed C line sent by remote SCP binary, illegal file length.");
124
125         LenNamePair lnp = new LenNamePair();
126         lnp.length = len;
127         lnp.filename = name_substring;
128
129         return lnp;
130     }
131
132     private void sendBytes(Session sess, byte[] data, String JavaDoc fileName, String JavaDoc mode) throws IOException JavaDoc
133     {
134         OutputStream JavaDoc os = sess.getStdin();
135         InputStream JavaDoc is = new BufferedInputStream JavaDoc(sess.getStdout(), 512);
136
137         readResponse(is);
138
139         String JavaDoc cline = "C" + mode + " " + data.length + " " + fileName + "\n";
140
141         os.write(cline.getBytes());
142         os.flush();
143
144         readResponse(is);
145
146         os.write(data, 0, data.length);
147         os.write(0);
148         os.flush();
149
150         readResponse(is);
151
152         os.write("E\n".getBytes());
153         os.flush();
154     }
155
156     private void sendFiles(Session sess, String JavaDoc[] files, String JavaDoc[] remoteFiles, String JavaDoc mode) throws IOException JavaDoc
157     {
158         byte[] buffer = new byte[8192];
159
160         OutputStream JavaDoc os = new BufferedOutputStream JavaDoc(sess.getStdin(), 40000);
161         InputStream JavaDoc is = new BufferedInputStream JavaDoc(sess.getStdout(), 512);
162
163         readResponse(is);
164
165         for (int i = 0; i < files.length; i++)
166         {
167             File JavaDoc f = new File JavaDoc(files[i]);
168             long remain = f.length();
169
170             String JavaDoc remoteName;
171
172             if ((remoteFiles != null) && (remoteFiles.length > i) && (remoteFiles[i] != null))
173                 remoteName = remoteFiles[i];
174             else
175                 remoteName = f.getName();
176
177             String JavaDoc cline = "C" + mode + " " + remain + " " + remoteName + "\n";
178
179             os.write(cline.getBytes());
180             os.flush();
181
182             readResponse(is);
183
184             FileInputStream JavaDoc fis = null;
185
186             try
187             {
188                 fis = new FileInputStream JavaDoc(f);
189
190                 while (remain > 0)
191                 {
192                     int trans;
193                     if (remain > buffer.length)
194                         trans = buffer.length;
195                     else
196                         trans = (int) remain;
197
198                     if (fis.read(buffer, 0, trans) != trans)
199                         throw new IOException JavaDoc("Cannot read enough from local file " + files[i]);
200
201                     os.write(buffer, 0, trans);
202
203                     remain -= trans;
204                 }
205             }
206             finally
207             {
208                 if (fis != null)
209                     fis.close();
210             }
211
212             os.write(0);
213             os.flush();
214
215             readResponse(is);
216         }
217
218         os.write("E\n".getBytes());
219         os.flush();
220     }
221
222     private void receiveFiles(Session sess, OutputStream JavaDoc[] targets) throws IOException JavaDoc
223     {
224         byte[] buffer = new byte[8192];
225
226         OutputStream JavaDoc os = new BufferedOutputStream JavaDoc(sess.getStdin(), 512);
227         InputStream JavaDoc is = new BufferedInputStream JavaDoc(sess.getStdout(), 40000);
228
229         os.write(0x0);
230         os.flush();
231
232         for (int i = 0; i < targets.length; i++)
233         {
234             LenNamePair lnp = null;
235
236             while (true)
237             {
238                 int c = is.read();
239                 if (c < 0)
240                     throw new IOException JavaDoc("Remote scp terminated unexpectedly.");
241
242                 String JavaDoc line = receiveLine(is);
243
244                 if (c == 'T')
245                 {
246                     /* Ignore modification times */
247
248                     continue;
249                 }
250
251                 if ((c == 1) || (c == 2))
252                     throw new IOException JavaDoc("Remote SCP error: " + line);
253
254                 if (c == 'C')
255                 {
256                     lnp = parseCLine(line);
257                     break;
258
259                 }
260                 throw new IOException JavaDoc("Remote SCP error: " + ((char) c) + line);
261             }
262
263             os.write(0x0);
264             os.flush();
265
266             long remain = lnp.length;
267
268             while (remain > 0)
269             {
270                 int trans;
271                 if (remain > buffer.length)
272                     trans = buffer.length;
273                 else
274                     trans = (int) remain;
275
276                 int this_time_received = is.read(buffer, 0, trans);
277
278                 if (this_time_received < 0)
279                 {
280                     throw new IOException JavaDoc("Remote scp terminated connection unexpectedly");
281                 }
282
283                 targets[i].write(buffer, 0, this_time_received);
284
285                 remain -= this_time_received;
286             }
287
288             readResponse(is);
289
290             os.write(0x0);
291             os.flush();
292         }
293     }
294
295     private void receiveFiles(Session sess, String JavaDoc[] files, String JavaDoc target) throws IOException JavaDoc
296     {
297         byte[] buffer = new byte[8192];
298
299         OutputStream JavaDoc os = new BufferedOutputStream JavaDoc(sess.getStdin(), 512);
300         InputStream JavaDoc is = new BufferedInputStream JavaDoc(sess.getStdout(), 40000);
301
302         os.write(0x0);
303         os.flush();
304
305         for (int i = 0; i < files.length; i++)
306         {
307             LenNamePair lnp = null;
308
309             while (true)
310             {
311                 int c = is.read();
312                 if (c < 0)
313                     throw new IOException JavaDoc("Remote scp terminated unexpectedly.");
314
315                 String JavaDoc line = receiveLine(is);
316
317                 if (c == 'T')
318                 {
319                     /* Ignore modification times */
320
321                     continue;
322                 }
323
324                 if ((c == 1) || (c == 2))
325                     throw new IOException JavaDoc("Remote SCP error: " + line);
326
327                 if (c == 'C')
328                 {
329                     lnp = parseCLine(line);
330                     break;
331
332                 }
333                 throw new IOException JavaDoc("Remote SCP error: " + ((char) c) + line);
334             }
335
336             os.write(0x0);
337             os.flush();
338
339             File JavaDoc f = new File JavaDoc(target + File.separatorChar + lnp.filename);
340             FileOutputStream JavaDoc fop = null;
341
342             try
343             {
344                 fop = new FileOutputStream JavaDoc(f);
345
346                 long remain = lnp.length;
347
348                 while (remain > 0)
349                 {
350                     int trans;
351                     if (remain > buffer.length)
352                         trans = buffer.length;
353                     else
354                         trans = (int) remain;
355
356                     int this_time_received = is.read(buffer, 0, trans);
357
358                     if (this_time_received < 0)
359                     {
360                         throw new IOException JavaDoc("Remote scp terminated connection unexpectedly");
361                     }
362
363                     fop.write(buffer, 0, this_time_received);
364
365                     remain -= this_time_received;
366                 }
367             }
368             finally
369             {
370                 if (fop != null)
371                     fop.close();
372             }
373
374             readResponse(is);
375
376             os.write(0x0);
377             os.flush();
378         }
379     }
380
381     /**
382      * Copy a local file to a remote directory, uses mode 0600 when creating
383      * the file on the remote side.
384      *
385      * @param localFile
386      * Path and name of local file.
387      * @param remoteTargetDirectory
388      * Remote target directory. Use an empty string to specify the default directory.
389      *
390      * @throws IOException
391      */

392     public void put(String JavaDoc localFile, String JavaDoc remoteTargetDirectory) throws IOException JavaDoc
393     {
394         put(new String JavaDoc[] { localFile }, remoteTargetDirectory, "0600");
395     }
396
397     /**
398      * Copy a set of local files to a remote directory, uses mode 0600 when
399      * creating files on the remote side.
400      *
401      * @param localFiles
402      * Paths and names of local file names.
403      * @param remoteTargetDirectory
404      * Remote target directory. Use an empty string to specify the default directory.
405      *
406      * @throws IOException
407      */

408
409     public void put(String JavaDoc[] localFiles, String JavaDoc remoteTargetDirectory) throws IOException JavaDoc
410     {
411         put(localFiles, remoteTargetDirectory, "0600");
412     }
413
414     /**
415      * Copy a local file to a remote directory, uses the specified mode when
416      * creating the file on the remote side.
417      *
418      * @param localFile
419      * Path and name of local file.
420      * @param remoteTargetDirectory
421      * Remote target directory. Use an empty string to specify the default directory.
422      * @param mode
423      * a four digit string (e.g., 0644, see "man chmod", "man open")
424      * @throws IOException
425      */

426     public void put(String JavaDoc localFile, String JavaDoc remoteTargetDirectory, String JavaDoc mode) throws IOException JavaDoc
427     {
428         put(new String JavaDoc[] { localFile }, remoteTargetDirectory, mode);
429     }
430
431     /**
432      * Copy a local file to a remote directory, uses the specified mode and remote filename
433      * when creating the file on the remote side.
434      *
435      * @param localFile
436      * Path and name of local file.
437      * @param remoteFileName
438      * The name of the file which will be created in the remote target directory.
439      * @param remoteTargetDirectory
440      * Remote target directory. Use an empty string to specify the default directory.
441      * @param mode
442      * a four digit string (e.g., 0644, see "man chmod", "man open")
443      * @throws IOException
444      */

445     public void put(String JavaDoc localFile, String JavaDoc remoteFileName, String JavaDoc remoteTargetDirectory, String JavaDoc mode)
446             throws IOException JavaDoc
447     {
448         put(new String JavaDoc[] { localFile }, new String JavaDoc[] { remoteFileName }, remoteTargetDirectory, mode);
449     }
450
451     /**
452      * Create a remote file and copy the contents of the passed byte array into it.
453      * Uses mode 0600 for creating the remote file.
454      *
455      * @param data
456      * the data to be copied into the remote file.
457      * @param remoteFileName
458      * The name of the file which will be created in the remote target directory.
459      * @param remoteTargetDirectory
460      * Remote target directory. Use an empty string to specify the default directory.
461      * @throws IOException
462      */

463
464     public void put(byte[] data, String JavaDoc remoteFileName, String JavaDoc remoteTargetDirectory) throws IOException JavaDoc
465     {
466         put(data, remoteFileName, remoteTargetDirectory, "0600");
467     }
468
469     /**
470      * Create a remote file and copy the contents of the passed byte array into it.
471      * The method use the specified mode when creating the file on the remote side.
472      *
473      * @param data
474      * the data to be copied into the remote file.
475      * @param remoteFileName
476      * The name of the file which will be created in the remote target directory.
477      * @param remoteTargetDirectory
478      * Remote target directory. Use an empty string to specify the default directory.
479      * @param mode
480      * a four digit string (e.g., 0644, see "man chmod", "man open")
481      * @throws IOException
482      */

483     public void put(byte[] data, String JavaDoc remoteFileName, String JavaDoc remoteTargetDirectory, String JavaDoc mode) throws IOException JavaDoc
484     {
485         Session sess = null;
486
487         if ((remoteFileName == null) || (remoteTargetDirectory == null) || (mode == null))
488             throw new IllegalArgumentException JavaDoc("Null argument.");
489
490         if (mode.length() != 4)
491             throw new IllegalArgumentException JavaDoc("Invalid mode.");
492
493         for (int i = 0; i < mode.length(); i++)
494             if (Character.isDigit(mode.charAt(i)) == false)
495                 throw new IllegalArgumentException JavaDoc("Invalid mode.");
496
497         remoteTargetDirectory = remoteTargetDirectory.trim();
498         remoteTargetDirectory = (remoteTargetDirectory.length() > 0) ? remoteTargetDirectory : ".";
499
500         String JavaDoc cmd = "scp -t -d " + remoteTargetDirectory;
501
502         try
503         {
504             sess = conn.openSession();
505             sess.execCommand(cmd);
506             sendBytes(sess, data, remoteFileName, mode);
507         }
508         catch (IOException JavaDoc e)
509         {
510             throw (IOException JavaDoc) new IOException JavaDoc("Error during SCP transfer.").initCause(e);
511         }
512         finally
513         {
514             if (sess != null)
515                 sess.close();
516         }
517     }
518
519     /**
520      * Copy a set of local files to a remote directory, uses the specified mode
521      * when creating the files on the remote side.
522      *
523      * @param localFiles
524      * Paths and names of the local files.
525      * @param remoteTargetDirectory
526      * Remote target directory. Use an empty string to specify the default directory.
527      * @param mode
528      * a four digit string (e.g., 0644, see "man chmod", "man open")
529      * @throws IOException
530      */

531     public void put(String JavaDoc[] localFiles, String JavaDoc remoteTargetDirectory, String JavaDoc mode) throws IOException JavaDoc
532     {
533         put(localFiles, null, remoteTargetDirectory, mode);
534     }
535
536     public void put(String JavaDoc[] localFiles, String JavaDoc[] remoteFiles, String JavaDoc remoteTargetDirectory, String JavaDoc mode)
537             throws IOException JavaDoc
538     {
539         Session sess = null;
540
541         /* remoteFiles may be null, indicating that the local filenames shall be used */
542
543         if ((localFiles == null) || (remoteTargetDirectory == null) || (mode == null))
544             throw new IllegalArgumentException JavaDoc("Null argument.");
545
546         if (mode.length() != 4)
547             throw new IllegalArgumentException JavaDoc("Invalid mode.");
548
549         for (int i = 0; i < mode.length(); i++)
550             if (Character.isDigit(mode.charAt(i)) == false)
551                 throw new IllegalArgumentException JavaDoc("Invalid mode.");
552
553         if (localFiles.length == 0)
554             return;
555
556         remoteTargetDirectory = remoteTargetDirectory.trim();
557         remoteTargetDirectory = (remoteTargetDirectory.length() > 0) ? remoteTargetDirectory : ".";
558
559         String JavaDoc cmd = "scp -t -d " + remoteTargetDirectory;
560
561         for (int i = 0; i < localFiles.length; i++)
562         {
563             if (localFiles[i] == null)
564                 throw new IllegalArgumentException JavaDoc("Cannot accept null filename.");
565         }
566
567         try
568         {
569             sess = conn.openSession();
570             sess.execCommand(cmd);
571             sendFiles(sess, localFiles, remoteFiles, mode);
572         }
573         catch (IOException JavaDoc e)
574         {
575             throw (IOException JavaDoc) new IOException JavaDoc("Error during SCP transfer.").initCause(e);
576         }
577         finally
578         {
579             if (sess != null)
580                 sess.close();
581         }
582     }
583
584     /**
585      * Download a file from the remote server to a local directory.
586      *
587      * @param remoteFile
588      * Path and name of the remote file.
589      * @param localTargetDirectory
590      * Local directory to put the downloaded file.
591      *
592      * @throws IOException
593      */

594     public void get(String JavaDoc remoteFile, String JavaDoc localTargetDirectory) throws IOException JavaDoc
595     {
596         get(new String JavaDoc[] { remoteFile }, localTargetDirectory);
597     }
598
599     /**
600      * Download a file from the remote server and pipe its contents into an <code>OutputStream</code>.
601      * Please note that, to enable flexible usage of this method, the <code>OutputStream</code> will not
602      * be closed nor flushed.
603      *
604      * @param remoteFile
605      * Path and name of the remote file.
606      * @param target
607      * OutputStream where the contents of the file will be sent to.
608      * @throws IOException
609      */

610     public void get(String JavaDoc remoteFile, OutputStream JavaDoc target) throws IOException JavaDoc
611     {
612         get(new String JavaDoc[] { remoteFile }, new OutputStream JavaDoc[] { target });
613     }
614
615     private void get(String JavaDoc remoteFiles[], OutputStream JavaDoc[] targets) throws IOException JavaDoc
616     {
617         Session sess = null;
618
619         if ((remoteFiles == null) || (targets == null))
620             throw new IllegalArgumentException JavaDoc("Null argument.");
621
622         if (remoteFiles.length != targets.length)
623             throw new IllegalArgumentException JavaDoc("Length of arguments does not match.");
624
625         if (remoteFiles.length == 0)
626             return;
627
628         String JavaDoc cmd = "scp -f";
629
630         for (int i = 0; i < remoteFiles.length; i++)
631         {
632             if (remoteFiles[i] == null)
633                 throw new IllegalArgumentException JavaDoc("Cannot accept null filename.");
634
635             String JavaDoc tmp = remoteFiles[i].trim();
636
637             if (tmp.length() == 0)
638                 throw new IllegalArgumentException JavaDoc("Cannot accept empty filename.");
639
640             cmd += (" " + tmp);
641         }
642
643         try
644         {
645             sess = conn.openSession();
646             sess.execCommand(cmd);
647             receiveFiles(sess, targets);
648         }
649         catch (IOException JavaDoc e)
650         {
651             throw (IOException JavaDoc) new IOException JavaDoc("Error during SCP transfer.").initCause(e);
652         }
653         finally
654         {
655             if (sess != null)
656                 sess.close();
657         }
658     }
659
660     /**
661      * Download a set of files from the remote server to a local directory.
662      *
663      * @param remoteFiles
664      * Paths and names of the remote files.
665      * @param localTargetDirectory
666      * Local directory to put the downloaded files.
667      *
668      * @throws IOException
669      */

670     public void get(String JavaDoc remoteFiles[], String JavaDoc localTargetDirectory) throws IOException JavaDoc
671     {
672         Session sess = null;
673
674         if ((remoteFiles == null) || (localTargetDirectory == null))
675             throw new IllegalArgumentException JavaDoc("Null argument.");
676
677         if (remoteFiles.length == 0)
678             return;
679
680         String JavaDoc cmd = "scp -f";
681
682         for (int i = 0; i < remoteFiles.length; i++)
683         {
684             if (remoteFiles[i] == null)
685                 throw new IllegalArgumentException JavaDoc("Cannot accept null filename.");
686
687             String JavaDoc tmp = remoteFiles[i].trim();
688
689             if (tmp.length() == 0)
690                 throw new IllegalArgumentException JavaDoc("Cannot accept empty filename.");
691
692             cmd += (" " + tmp);
693         }
694
695         try
696         {
697             sess = conn.openSession();
698             sess.execCommand(cmd);
699             receiveFiles(sess, remoteFiles, localTargetDirectory);
700         }
701         catch (IOException JavaDoc e)
702         {
703             throw (IOException JavaDoc) new IOException JavaDoc("Error during SCP transfer.").initCause(e);
704         }
705         finally
706         {
707             if (sess != null)
708                 sess.close();
709         }
710     }
711 }
712
Popular Tags