• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

Needs to connect SSH Terminal unix box from Java

 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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...
 
Rancher
Posts: 43081
77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
JSch is a library for making SSH connections programmatically from Java code.
 
Beth Candida
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Rancher
Posts: 43081
77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That code tries to make an FTP connection. What does that have to do with SSH?
 
Beth Candida
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Rancher
Posts: 43081
77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic