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 myusername 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 final String server; 040 final String username; 041 final String password; 042 final String command; 043 final RExecClient client; 044 045 if (args.length != 4) { 046 System.err.println("Usage: rexec <hostname> <username> <password> <command>"); 047 System.exit(1); 048 return; // so compiler can do proper flow control analysis 049 } 050 051 client = new RExecClient(); 052 053 server = args[0]; 054 username = args[1]; 055 password = args[2]; 056 command = args[3]; 057 058 try { 059 client.connect(server); 060 } catch (final IOException e) { 061 System.err.println("Could not connect to server."); 062 e.printStackTrace(); 063 System.exit(1); 064 } 065 066 try { 067 client.rexec(username, password, command); 068 } catch (final IOException e) { 069 try { 070 client.disconnect(); 071 } catch (final IOException f) { 072 /* ignored */} 073 e.printStackTrace(); 074 System.err.println("Could not execute command."); 075 System.exit(1); 076 } 077 078 IOUtil.readWrite(client.getInputStream(), client.getOutputStream(), System.in, System.out); 079 080 try { 081 client.disconnect(); 082 } catch (final IOException e) { 083 e.printStackTrace(); 084 System.exit(1); 085 } 086 087 System.exit(0); 088 } 089 090}