File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Sockets and Internet Protocols and the fly likes Needs to connect SSH Terminal unix box from Java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Sockets and Internet Protocols
Bookmark "Needs to connect SSH Terminal unix box from Java" Watch "Needs to connect SSH Terminal unix box from Java" New topic
Author

Needs to connect SSH Terminal unix box from Java

Beth Candida
Greenhorn

Joined: Apr 26, 2012
Posts: 18
Hi All,

I am new to JAVA..I am looking out for a java code to connect to the SSH terminal using my credentials. My end result is, to read a file kept on the server.
I am facing issues while connecting to the servers. Any sort of help is much appreciated...
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42610
    
  65
JSch is a library for making SSH connections programmatically from Java code.


Ping & DNS - my free Android networking tools app
Beth Candida
Greenhorn

Joined: Apr 26, 2012
Posts: 18
The following is my code:

It fails while establishing the connection:

java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)



code:

import java.io.*;
import java.text.*;
import java.util.*;


import org.apache.commons.net.ftp.*;


/**
*
* @author shussain
* @version 0.1
*/
public class FtpTestClient {

public final static int DEFAULT_FTP_PORT = 21;

private FTPClient ftpc;

public static void main(String[] args) {


String[] host_names = {"Hostname", "***.**.**.***", ""};
String[] user_names = {"user", "superuser", "hostuser"};
String[] passwords = {"*****", "superpass", "hostpass"};
String ftp_src_folder = "/tmp/r";
String ftp_src_file = "Query.txt";

for (int i = 0; i < host_names.length; i++) {
FtpTestClient.getFile(host_names[i], user_names[i],
passwords[i], ftp_src_folder, ftp_src_file);
}
}

public FtpTestClient(String host, String login, String passwd)
throws Exception
{
this(host, String.valueOf(FtpTestClient.DEFAULT_FTP_PORT), login, passwd);
}
/**
* Creates a new instance of FtpTestClient
*
*
* @param host Server host name
* @param port Server port number
* @param login FTP login name
* @param passwd FTP login password
* @throws Exception if client create fails
*/
public FtpTestClient(String host, String port, String login, String passwd)
throws Exception
{
try {
ftpc = new FTPClient();
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}

/**
* get a single file from the server. Destination filename is same as that
* on server.
*
* @param server ftp server name
* @param username ftp server login name
* @param password ftp server password
* @param folder source folder on the ftp server
* @param fname file to be transferred
* @return true if successful
*/
public static boolean getFile(String server, String username,
String password, String folder, String fname)
{
boolean status = false;

FTPClient ftp = null;
try {
ftp = new FTPClient();

ftp.connect( server );
ftp.login( username, password );

ftp.changeWorkingDirectory( folder );

File file = new File(fname);
FileOutputStream fos = new FileOutputStream( file );

ftp.retrieveFile(fname, fos);
fos.close();

status = true;

} catch (Exception e) {
e.printStackTrace();
} finally {
try {
ftp.logout();
ftp.disconnect();
} catch (Exception e) {}
}

return status;
}

public static void getAllFiles( String server,
String username,
String password,
String folder,
String destinationFolder,
Calendar start,
Calendar end ) {
try {
// Connect and logon to FTP Server
FTPClient ftp = new FTPClient();
ftp.connect( server );
ftp.login( username, password );
System.out.println("Connected to " +
server + ".");
System.out.print(ftp.getReplyString());

// List the files in the directory
ftp.changeWorkingDirectory( folder );
FTPFile[] files = ftp.listFiles();
System.out.println( "Number of files in dir: " + files.length );
DateFormat df = DateFormat.getDateInstance( DateFormat.SHORT );
for( int i=0; i<files.length; i++ ) {
Date fileDate = files[ i ].getTimestamp().getTime();
if( fileDate.compareTo( start.getTime() ) >= 0 &&
fileDate.compareTo( end.getTime() ) <= 0 ) {
// Download a file from the FTP Server
System.out.print( df.format( files[ i ].getTimestamp().getTime() ) );
System.out.println( "\t" + files[ i ].getName() );
File file = new File( destinationFolder +
File.separator + files[ i ].getName() );
FileOutputStream fos = new FileOutputStream( file );
ftp.retrieveFile( files[ i ].getName(), fos );
fos.close();
file.setLastModified( fileDate.getTime() );
}
}

// Logout from the FTP Server and disconnect
ftp.logout();
ftp.disconnect();

} catch( Exception e ) {
e.printStackTrace();
}
}

/**
* Gets all files which matches a specified file name template. The template
* is a regular expression.
*
* @param server ftp server name
* @param username ftp server login name
* @param password ftp server password
* @param folder source folder on the ftp server
* @param ftempl regular expression for file name
* @return true if successful
* @throws Exception if unable to connect and other problems.
*/
public static boolean getFilesOfType(String server, String username,
String password, String folder, String ftempl)
throws Exception
{
FTPClient ftp = null;
boolean status = false;

try {
// Connect and logon to FTP Server
ftp = new FTPClient();
ftp.connect( server );
ftp.login( username, password );

// List the files in the directory

ftp.changeWorkingDirectory( folder );
FTPFile[] files = ftp.listFiles();

// get files which match name template
// at present just check for prefix
for (int i = 0; i < files.length; i++) {
/*
if (files[i].matches(ftempl)) {

}*/
}
} catch (Exception e) {
throw e;
}

finally {
// close connection
if (ftp != null && ftp.isConnected()) {
ftp.disconnect();
}
}

return status;
}

/**
* Upload a single file to the server. Destination filename is same as that
* on server.
*
* @param server ftp server name
* @param username ftp server login name
* @param password ftp server password
* @param folder source folder on the ftp server
* @param fname file to be transferred
* @return true if successful
*/
public boolean putFile(String server, String username,
String password, String folder, String fname)
throws Exception {
return false;
}

public void setMode(int type) {

}

public int getMode() {
return -1;
}


}
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42610
    
  65
That code tries to make an FTP connection. What does that have to do with SSH?
Beth Candida
Greenhorn

Joined: Apr 26, 2012
Posts: 18
this my goal: I first need to connect to the UNIX box and then read a flat file kept on the server.

Any help is appreciated cause I am running out of days..
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42610
    
  65
I pointed you to a library that can do this using the protocol that you said you wanted to use. Have you followed up on that? Or have the requirements changed so that another protocol is now to be used? Or does the protocol not matter?

If you're free to choose a protocol, and don't have to transfer the file -just read it- then even more possibilities open up.
Ganesh Malaichamy
Greenhorn

Joined: Feb 11, 2011
Posts: 27
Did you manually tried transferring the single file from the host through ftp in command prompt. Also check the ftp service is running in the host and the port is open for connection.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Needs to connect SSH Terminal unix box from Java