Executing Unix shell from Java Program
807603Jan 10 2008 — edited Jan 10 2008Hi,
I have written a java application using Maverick J2sshtools API which connects to a Unix box using SSH.The program authenticates with the remote box successfully,but It dosen't return the environment info or execute the test script.Have attached the complete code.
package shellInteraction;
import com.maverick.ssh.*;
import com.maverick.ssh2.Ssh2Client;
import com.maverick.ssh2.Ssh2Context;
import com.maverick.ssh2.Ssh2PasswordAuthentication;
import com.sshtools.net.*;
import java.io.*;
import java.util.Iterator;
import java.util.Vector;
public class JavaShell{
public static void main(String[] args) {
SshConnector con = null;
SshClient ssh = null;
ShellProcess process = null;
Shell shell = null;
try{
// Create a session to remote host
con = SshConnector.getInstance();
ssh = connectionSetup(con);
System.out.println(ssh);
// Start a session and do basic IO
if (ssh.isAuthenticated()) {
shell = new Shell(ssh);
System.out.println("Authenticated");
if(shell.getEnvironment().hasEnvironmentVariable("hostname"))
System.out.println("We are connected to " + shell.getEnvironment().getEnvironmentVariable("hostname"));
//System.out.println("Remote operating system is " + shell.getEnvironment().getOperatingSystem());
// boolean isWindows = shell.getEnvironment().getOSType()==ShellEnvironment.OS_WINDOWS;
//if(shell.getEnvironment().hasEnvironmentVariable("USERPROFILE")) {
//System.out.println("User home is " + shell.getEnvironment().getEnvironmentVariable("USERPROFILE"));
//} else if(shell.getEnvironment().hasEnvironmentVariable("HOME")) {
//System.out.println("User home is " + shell.getEnvironment().getEnvironmentVariable("HOME"));
//}
// Commands only executed for Unix OS
//if(!isWindows) {
// Execute a script
traverseDirectory(shell);
}
}
shell.exit();
ssh.disconnect();
System.out.println("Shell has exited");
} catch(Throwable t) {
t.printStackTrace();
}
}
private static void traverseDirectory(Shell shell) throws Exception{
System.out.println("\n\nTraverse Directory");
// Execute a simple script than prints a directory tree
ShellProcess process = shell.execute("bash test.sh ");
try{
process.expect("Total directories", 1000, true);
System.out.print(process.toString());
} catch (ShellTimeoutException ex1) {
System.out.println("TRAVERSE Expect operation timed out. Sending interrupt to kill the process");
process.interrupt();
}finally {
process.close();
}
}
static private Ssh2Client connectionSetup(SshConnector con)throws SshException{
Ssh2Client ssh = null;
final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.print("Hostname: ");
String hostname = reader.readLine();
int idx = hostname.indexOf(':');
int port = 22;
if(idx > -1) {
port = Integer.parseInt(hostname.substring(idx+1));
hostname = hostname.substring(0, idx);
}
System.out.print("Username [Enter for " + System.getProperty("user.name") + "]: ");
String username = reader.readLine();
if(username==null || username.trim().equals(""))
username = System.getProperty("user.name");
System.out.println("Connecting to " + hostname);
/**
* Create an SshConnector instance
*/
con = SshConnector.getInstance();
// Lets do some host key verification
HostKeyVerification hkv = new PasswordHostKey();
con.setSupportedVersions(SshConnector.SSH2);
/**
* Set our preferred public key type
*/
con.getContext(SshConnector.SSH2).setHostKeyVerification(hkv);
((Ssh2Context)con.getContext(SshConnector.SSH2)).setPreferredPublicKey(Ssh2Context.PUBLIC_KEY_SSHDSS);
/**
* Connect to the host
*/
ssh = (Ssh2Client)con.connect(new SocketTransport(hostname, port), username, true);
/**
* Authenticate the user using password authentication
*/
Ssh2PasswordAuthentication passwordAuthentication = new Ssh2PasswordAuthentication();
System.out.print("Password: ");
passwordAuthentication.setPassword(reader.readLine());
if(ssh.authenticate(passwordAuthentication)!=SshAuthentication.COMPLETE) {
System.out.println("Authentication failed!");
System.exit(0);
}
}catch(Exception ex1) {
throw new SshException(ex1.getMessage(), ex1.getCause());
}
return ssh;
}
}
When I execute the program
Hostname:****
Username [Enter for thaya]: **
Connecting to CATL
The connected host's key (ssh-dss) is
b6:85:91:6b:8b:ea:cb:40:b5:6f:01:2e:66:78:7f:62
Password: *****
SSH2 CATLMSXP62:22 [kex=diffie-hellman-group1-sha1 hostkey=ssh-dss client->server=aes128-cbc,hmac-sha1,none server->client=aes128-cbc,hmac-sha1,none]
Authenticated
Traverse Directory
com.maverick.ssh.ShellTimeoutException: The shell did not return to the prompt in the given timeout period 10000ms
at com.maverick.ssh.Shell.A(Unknown Source)
at com.maverick.ssh.Shell.execute(Unknown Source)
at shellInteraction.ShellInteraction.traverseDirectory(ShellInteraction.java:108)
at shellInteraction.ShellInteraction.main(ShellInteraction.java:68)
This is the error message what i get.