001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 018package examples.unix; 019 020import java.io.IOException; 021import org.apache.commons.net.bsd.RExecClient; 022 023import examples.util.IOUtil; 024 025/*** 026 * This is an example program demonstrating how to use the RExecClient class. 027 * This program connects to an rexec server and requests that the 028 * given command be executed on the server. It then reads input from stdin 029 * (this will be line buffered on most systems, so don't expect character 030 * at a time interactivity), passing it to the remote process and writes 031 * the process stdout and stderr to local stdout. 032 * <p> 033 * Example: java rexec myhost myusername mypassword "ps -aux" 034 * <p> 035 * Usage: rexec <hostname> <username> <password> <command> 036 ***/ 037 038// This class requires the IOUtil support class! 039public final class rexec 040{ 041 042 public static void main(String[] args) 043 { 044 String server, username, password, command; 045 RExecClient client; 046 047 if (args.length != 4) 048 { 049 System.err.println( 050 "Usage: rexec <hostname> <username> <password> <command>"); 051 System.exit(1); 052 return ; // so compiler can do proper flow control analysis 053 } 054 055 client = new RExecClient(); 056 057 server = args[0]; 058 username = args[1]; 059 password = args[2]; 060 command = args[3]; 061 062 try 063 { 064 client.connect(server); 065 } 066 catch (IOException e) 067 { 068 System.err.println("Could not connect to server."); 069 e.printStackTrace(); 070 System.exit(1); 071 } 072 073 try 074 { 075 client.rexec(username, password, command); 076 } 077 catch (IOException e) 078 { 079 try 080 { 081 client.disconnect(); 082 } 083 catch (IOException f) 084 {/* ignored */} 085 e.printStackTrace(); 086 System.err.println("Could not execute command."); 087 System.exit(1); 088 } 089 090 091 IOUtil.readWrite(client.getInputStream(), client.getOutputStream(), 092 System.in, System.out); 093 094 try 095 { 096 client.disconnect(); 097 } 098 catch (IOException e) 099 { 100 e.printStackTrace(); 101 System.exit(1); 102 } 103 104 System.exit(0); 105 } 106 107} 108