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 org.apache.commons.net.examples.unix; 019 020import java.io.IOException; 021 022import org.apache.commons.net.bsd.RExecClient; 023import org.apache.commons.net.examples.util.IOUtil; 024 025/** 026 * This is an example program demonstrating how to use the RExecClient class. This program connects to an rexec server and requests that the given command be 027 * executed on the server. It then reads input from stdin (this will be line buffered on most systems, so don't expect character at a time interactivity), 028 * passing it to the remote process and writes the process stdout and stderr to local stdout. 029 * <p> 030 * Example: java rexec myhost myuser mypassword "ps -aux" 031 * <p> 032 * Usage: rexec <hostname> <username> <password> <command> 033 */ 034 035// This class requires the IOUtil support class! 036public final class rexec { 037 038 public static void main(final String[] args) { 039 040 if (args.length != 4) { 041 System.err.println("Usage: rexec <hostname> <user> <password> <command>"); 042 System.exit(1); 043 return; // so compiler can do proper flow control analysis 044 } 045 046 final RExecClient client = new RExecClient(); 047 final String server = args[0]; 048 final String user = args[1]; 049 final String password = args[2]; 050 final String command = args[3]; 051 052 try { 053 client.connect(server); 054 } catch (final IOException e) { 055 System.err.println("Could not connect to server."); 056 e.printStackTrace(); 057 System.exit(1); 058 } 059 060 try { 061 client.rexec(user, password, command); 062 } catch (final IOException e) { 063 try { 064 client.disconnect(); 065 } catch (final IOException f) { 066 /* ignored */ 067 } 068 e.printStackTrace(); 069 System.err.println("Could not execute command."); 070 System.exit(1); 071 } 072 073 IOUtil.readWrite(client.getInputStream(), client.getOutputStream(), System.in, System.out); 074 075 try { 076 client.disconnect(); 077 } catch (final IOException e) { 078 e.printStackTrace(); 079 System.exit(1); 080 } 081 082 System.exit(0); 083 } 084 085}