01: /*
02: * Copyright 2001-2005 The Apache Software Foundation
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16: package examples;
17:
18: import java.io.IOException;
19: import org.apache.commons.net.bsd.RCommandClient;
20:
21: /***
22: * This is an example program demonstrating how to use the RCommandClient
23: * class. This program connects to an rshell daemon and requests that the
24: * given command be executed on the server. It then reads input from stdin
25: * (this will be line buffered on most systems, so don't expect character
26: * at a time interactivity), passing it to the remote process and writes
27: * the process stdout and stderr to local stdout.
28: * <p>
29: * On Unix systems you will not be able to use the rshell capability
30: * unless the process runs as root since only root can bind port addresses
31: * lower than 1024.
32: * <p>
33: * Example: java rshell myhost localusername remoteusername "ps -aux"
34: * <p>
35: * Usage: rshell <hostname> <localuser> <remoteuser> <command>
36: * <p>
37: ***/
38:
39: // This class requires the IOUtil support class!
40: public final class rshell {
41:
42: public static final void main(String[] args) {
43: String server, localuser, remoteuser, command;
44: RCommandClient client;
45:
46: if (args.length != 4) {
47: System.err
48: .println("Usage: rshell <hostname> <localuser> <remoteuser> <command>");
49: System.exit(1);
50: return; // so compiler can do proper flow control analysis
51: }
52:
53: client = new RCommandClient();
54:
55: server = args[0];
56: localuser = args[1];
57: remoteuser = args[2];
58: command = args[3];
59:
60: try {
61: client.connect(server);
62: } catch (IOException e) {
63: System.err.println("Could not connect to server.");
64: e.printStackTrace();
65: System.exit(1);
66: }
67:
68: try {
69: client.rcommand(localuser, remoteuser, command);
70: } catch (IOException e) {
71: try {
72: client.disconnect();
73: } catch (IOException f) {
74: }
75: e.printStackTrace();
76: System.err.println("Could not execute command.");
77: System.exit(1);
78: }
79:
80: IOUtil.readWrite(client.getInputStream(), client
81: .getOutputStream(), System.in, System.out);
82:
83: try {
84: client.disconnect();
85: } catch (IOException e) {
86: e.printStackTrace();
87: System.exit(1);
88: }
89:
90: System.exit(0);
91: }
92:
93: }
|