com.jcraft.jsch.JSchException: timeout: socket is not established - java

I am trying to upload a file to a server (with java) where I have an acount and the SFTP connection stopped working (for a timeout problem I guess). I want to know is there a way to reset this connection and get it working. This is the function:
public static void upload(File file, boolean retry) {
try
{
System.out.println("Uplodaing file " + file.getName());
JSch jsch = new JSch();
Session session = jsch.getSession("****", "*****", 22);
session.setPassword("*****");
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setTimeout(5);
System.out.println("Establishing connection");
session.connect(10);
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
if (!retry)
sftpChannel.put(file.getAbsolutePath(), file.getName(),new SystemOutProgressMonitor(), ChannelSftp.OVERWRITE);
else
sftpChannel.put(file.getAbsolutePath(), file.getName(),new SystemOutProgressMonitor(), ChannelSftp.RESUME);
channel.disconnect();
session.disconnect();
}
catch (Exception e)
{
e.printStackTrace();
upload(file, false);
}
}

I know this question is quite old but in case anyone stumbles over it (as I did):
The problem is the connection timeout, which should be in milliseconds. In case OP intended 10 seconds, it should be 10000 here. 10 milliseconds simply isn't enough.

Related

Audit Log on machine shows login every time channel connected in JSch

I am using JSch to fetch data from remote server on brocade switch. A new session is created and a new channel is opened with type as 'shell'. I have few commands which fetches data from this server. I created new Channel for every command and disconnects channel after fetching data.
Now in Audit log on server shows new login for every channel which i created for each command.
Should login be shown for every session created instead of every channel connected?
public Session getSession(String hostName,
String username,
String password,
Integer port) throws Exception {
Session session = null;
try {
JSch jsch = new JSch();
if (port == null) {
port = 22;
}
session = jsch.getSession(username, hostName, port);
session.setPassword(password);
session.setConfig("max_input_buffer_size", Integer.toString(100 * 1024 * 1024));
session.setConfig("StrictHostKeyChecking", "no");
session.setConfig("UserKnownHostsFile", "/dev/null");
session.connect(15 * 1000);
} catch (Exception e) {
if (session != null) {
session.disconnect();
}
throw new Exception("Error in connecting to: " + hostName, e);
}
return session;
}
private Channel getChannel(Session session,String type) throws Exception {
if (session == null || !session.isConnected()) {
session = getSession();
}
Channel channel = null;
try {
channel = session.openChannel(type);
} catch (Exception e) {
throw e;
}
channel.setInputStream(null);
return channel;
}
SSH channel does not create a new login.
But it creates a new shell session. Maybe your "audit log" logs shell session as if it were a new login. With a normal SSH client, you typically create only one shell session for each login. So it's easy to mismatch these two things.

JSCH session connection issue

I ran the below program and reboot the host which takes almost 6 to 8 mins to complete the reboot, but i never get the timed out.. i.e is it never go to else part.
public static void main(String a[]) throws JSchException, InterruptedException {
java.util.Properties config = new java.util.Properties();
JSch jsch = new JSch();
String user = "cli";
String host = "135.104.217.114";
String password = "cli";
int port = 22;
Session session = jsch.getSession(user,host,port);
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword(password);
session.connect();
while(true)
{
if(session.isConnected())
{
System.out.println("session connected");
}
else
{
System.out.println("sesion not connected--------------");
}
Thread.sleep(1000);
}
}
You most likely need to configure the "Sever Alive" properties.
session.setServerAliveInterval(5000); // Check if server is alive every 5 seconds
session.setServerAliveCountMax(5); // Disconnect after 5 Server Alive checks did not receive a response.

Connection health check for sftp with JSch

I need to check the health of the SFTP connection using JSch liberary. I have used the following approach. Please correct me if I am wrong.
public boolean checkConnection() throws JSchException {
try {
JSch jsch = new JSch();
Session session = sch.getSession(username, host);
session.setPort(PORT);
session.setPassword(password);
session.connect();
return true;
} catch(Exception ex){
LOG.error("Error while connecting to SFTP", ex);
}
return false
}

Interact with linux server using java JSCH

I have created java program using JSch class. Program successfully execute the (ls, cd, change) commands. These commands dint need any inputs. But while executing the /usr/ses/b/kr command it require the password.
Can you please reply how I can send password to linux server using JSch. Or there is any another way?
((ChannelExec)channel).setCommand("/usr/ses/b/kr;");
You should set StrictHostKeyChecking property "no" and channel should be set shell.as following.
String username = "xxxyyyzzz";
String password = "aaabbbccc";
String host = "192.168.1.1"; // sample ip address
if(command.getText().toString() != ""){
JSch jsch = new JSch();
try {
session = jsch.getSession(username, host, 22);
session.setPassword(password);
Properties properties = new Properties();
properties.put("StrictHostKeyChecking", "no");
session.setConfig(properties);
session.connect(30000);
channel = session.openChannel("shell");
channel.setInputStream(bais);
channel.setOutputStream(baos);
channel.connect();
} catch (JSchException e) {
// TODO Auto-generated catch block
}
}
else{
//
}

Why does an SFTP connection still exist after the JSCH Channel has been closed?

When the code below has finished running, netstat -a|grep sftp shows an open SFTP connection. It also shows up as an open connection in JProfiler.
channel.isConnected() in the finally block prints false. Any ideas why the connections is not being closed as I'm at a loss?
public static void clean() {
com.jcraft.jsch.ChannelSftp channel = null;
try {
channel = Helper.openNewTLSftpChannel();
channel.connect();
channel.cd(remoteFileDirectory);
List<ChannelSftp.LsEntry> list = channel.ls("*." + fileType);
for (ChannelSftp.LsEntry file : list) {
String fileName = file.getFilename();
DateTime fileDate = new DateTime(parseDateFromFileName(fileName));
//if this file is older than the cutoff date, delete from the SFTP share
if (fileDate.compareTo(cleanupCutoffdate) < 0) {
channel.rm(fileName);
}
}
} catch (Exception exception) {
exception.printStackTrace();
} finally {
if (channel != null) {
channel.disconnect();
System.out.println(channel.isConnected());
}
}
}
Adding openNewTLSftpChannel() below:
public static ChannelSftp openNewSftpChannel(String privateKeyFileName, String password, String username, String host, int port)
throws ConfigurationErrorException {
JSch jsch = new JSch();
File sftpPrivateFile = new File(privateKeyFileName);
Channel channel;
try {
if (!sftpPrivateFile.canRead()) {
throw new ConfigurationErrorException("File access error: " + sftpPrivateFile.getAbsolutePath());
}
jsch.addIdentity(sftpPrivateFile.getAbsolutePath(), password);
Session session = jsch.getSession(username, host, port);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channel = session.openChannel("sftp");
} catch (JSchException jschException) {
throw new ConfigurationErrorException("File access error: " + sftpPrivateFile.getAbsolutePath());
}
return (ChannelSftp) channel;
}
If you take a look at the JSCH examples for SFTP you'll see how the session is terminated:
//setup Session here
...
session.connect();
...
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
...run sftp logic...
//close sessions here
sftpChannel.exit();
session.disconnect();
You'll notice that there are two parts to the connection and disconnection; the Session object and the Channel object.
In my code I use the Session object to set my authentication information, and the Channel object to execute the sftp commands I need.
In your instance, you're creating the Session object in your openNewSftpChannel method, but it is never closed, hence your session stays alive.
For further context, check out the examples.
Robert H is correct, you need to exit your channel and disconnect your session. I wanted to add that the session exists even when the channel has been closed. Since you create your session within a try block inside a method, it seems you have lost your session, but you can get it back using 'getSession' on your sftpChannel channel.
You can change your finally block to this:
} finally {
if (channel != null) {
Session session = channel.getSession();
channel.disconnect();
session.disconnect();
System.out.println(channel.isConnected());
}
}

Categories