How can i keep a Jsch Session alive on android











up vote
0
down vote

favorite
1












I am writing an app to connect over SSH to a server. My intention is to give the user of the app an internet connection as long as they are connected to the server (The SSH Script runs as Android Service). The Problem is, when I start a session and create a channel everything works fine. But after about 20-30 minutes (sometimes up to several hours) the channel and the session closes.



Connect function:



 public String connecting(
String username,
final String password,
String hostname,
int port) {

try {
Log.d("MainActivity", "Start JSch session and connect");
jsch = new JSch();
session = jsch.getSession(username, hostname, port);

session.setPassword(password);

// Avoid asking for key confirmation
Properties prop = new Properties();
prop.put("StrictHostKeyChecking", "no");
session.setConfig(prop);
session.connect();
session.setServerAliveInterval(15);
session.setServerAliveCountMax(100);


Channel channel = session.openChannel("shell");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();

InputStream in = channel.getInputStream();
serviceStatus = true;
streamtext = "";
byte tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0) break;
streamtext = new String(tmp, 0, i);

}
}
if (channel.isClosed()) {
if (in.available() > 0) continue;
Log.d(TAG, "exit-status: " + channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
ee.printStackTrace();
}
}

return streamtext;
} catch (Exception except){
except.printStackTrace();
passErrorToActivity("Error: Connection error");
return "Error: Connection error";
}
}


Start function:



public void start(){
try {
new AsyncTask<Integer, Void, Void>() {
@Override
protected Void doInBackground(Integer... params) {
try {
passMessageToActivity(connecting(user, password, host, port));
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}.execute(1);
} catch (Exception exc) {
exc.printStackTrace();
}


"passMessageToActivity" Just creats an intent and sends the "streamtext" to the MainActivity



I've already tryed it with Session#setServerAliveInterval(int milliseconds) but it didn't work. Is there any posibility to keep the session and channel alive?
I've seen the solution of this user but this doesn't work for me because it's important that the connection between server and service is always up.










share|improve this question


























    up vote
    0
    down vote

    favorite
    1












    I am writing an app to connect over SSH to a server. My intention is to give the user of the app an internet connection as long as they are connected to the server (The SSH Script runs as Android Service). The Problem is, when I start a session and create a channel everything works fine. But after about 20-30 minutes (sometimes up to several hours) the channel and the session closes.



    Connect function:



     public String connecting(
    String username,
    final String password,
    String hostname,
    int port) {

    try {
    Log.d("MainActivity", "Start JSch session and connect");
    jsch = new JSch();
    session = jsch.getSession(username, hostname, port);

    session.setPassword(password);

    // Avoid asking for key confirmation
    Properties prop = new Properties();
    prop.put("StrictHostKeyChecking", "no");
    session.setConfig(prop);
    session.connect();
    session.setServerAliveInterval(15);
    session.setServerAliveCountMax(100);


    Channel channel = session.openChannel("shell");
    channel.setInputStream(System.in);
    channel.setOutputStream(System.out);
    channel.connect();

    InputStream in = channel.getInputStream();
    serviceStatus = true;
    streamtext = "";
    byte tmp = new byte[1024];
    while (true) {
    while (in.available() > 0) {
    int i = in.read(tmp, 0, 1024);
    if (i < 0) break;
    streamtext = new String(tmp, 0, i);

    }
    }
    if (channel.isClosed()) {
    if (in.available() > 0) continue;
    Log.d(TAG, "exit-status: " + channel.getExitStatus());
    break;
    }
    try {
    Thread.sleep(1000);
    } catch (Exception ee) {
    ee.printStackTrace();
    }
    }

    return streamtext;
    } catch (Exception except){
    except.printStackTrace();
    passErrorToActivity("Error: Connection error");
    return "Error: Connection error";
    }
    }


    Start function:



    public void start(){
    try {
    new AsyncTask<Integer, Void, Void>() {
    @Override
    protected Void doInBackground(Integer... params) {
    try {
    passMessageToActivity(connecting(user, password, host, port));
    } catch (Exception ex) {
    ex.printStackTrace();
    }
    return null;
    }
    }.execute(1);
    } catch (Exception exc) {
    exc.printStackTrace();
    }


    "passMessageToActivity" Just creats an intent and sends the "streamtext" to the MainActivity



    I've already tryed it with Session#setServerAliveInterval(int milliseconds) but it didn't work. Is there any posibility to keep the session and channel alive?
    I've seen the solution of this user but this doesn't work for me because it's important that the connection between server and service is always up.










    share|improve this question
























      up vote
      0
      down vote

      favorite
      1









      up vote
      0
      down vote

      favorite
      1






      1





      I am writing an app to connect over SSH to a server. My intention is to give the user of the app an internet connection as long as they are connected to the server (The SSH Script runs as Android Service). The Problem is, when I start a session and create a channel everything works fine. But after about 20-30 minutes (sometimes up to several hours) the channel and the session closes.



      Connect function:



       public String connecting(
      String username,
      final String password,
      String hostname,
      int port) {

      try {
      Log.d("MainActivity", "Start JSch session and connect");
      jsch = new JSch();
      session = jsch.getSession(username, hostname, port);

      session.setPassword(password);

      // Avoid asking for key confirmation
      Properties prop = new Properties();
      prop.put("StrictHostKeyChecking", "no");
      session.setConfig(prop);
      session.connect();
      session.setServerAliveInterval(15);
      session.setServerAliveCountMax(100);


      Channel channel = session.openChannel("shell");
      channel.setInputStream(System.in);
      channel.setOutputStream(System.out);
      channel.connect();

      InputStream in = channel.getInputStream();
      serviceStatus = true;
      streamtext = "";
      byte tmp = new byte[1024];
      while (true) {
      while (in.available() > 0) {
      int i = in.read(tmp, 0, 1024);
      if (i < 0) break;
      streamtext = new String(tmp, 0, i);

      }
      }
      if (channel.isClosed()) {
      if (in.available() > 0) continue;
      Log.d(TAG, "exit-status: " + channel.getExitStatus());
      break;
      }
      try {
      Thread.sleep(1000);
      } catch (Exception ee) {
      ee.printStackTrace();
      }
      }

      return streamtext;
      } catch (Exception except){
      except.printStackTrace();
      passErrorToActivity("Error: Connection error");
      return "Error: Connection error";
      }
      }


      Start function:



      public void start(){
      try {
      new AsyncTask<Integer, Void, Void>() {
      @Override
      protected Void doInBackground(Integer... params) {
      try {
      passMessageToActivity(connecting(user, password, host, port));
      } catch (Exception ex) {
      ex.printStackTrace();
      }
      return null;
      }
      }.execute(1);
      } catch (Exception exc) {
      exc.printStackTrace();
      }


      "passMessageToActivity" Just creats an intent and sends the "streamtext" to the MainActivity



      I've already tryed it with Session#setServerAliveInterval(int milliseconds) but it didn't work. Is there any posibility to keep the session and channel alive?
      I've seen the solution of this user but this doesn't work for me because it's important that the connection between server and service is always up.










      share|improve this question













      I am writing an app to connect over SSH to a server. My intention is to give the user of the app an internet connection as long as they are connected to the server (The SSH Script runs as Android Service). The Problem is, when I start a session and create a channel everything works fine. But after about 20-30 minutes (sometimes up to several hours) the channel and the session closes.



      Connect function:



       public String connecting(
      String username,
      final String password,
      String hostname,
      int port) {

      try {
      Log.d("MainActivity", "Start JSch session and connect");
      jsch = new JSch();
      session = jsch.getSession(username, hostname, port);

      session.setPassword(password);

      // Avoid asking for key confirmation
      Properties prop = new Properties();
      prop.put("StrictHostKeyChecking", "no");
      session.setConfig(prop);
      session.connect();
      session.setServerAliveInterval(15);
      session.setServerAliveCountMax(100);


      Channel channel = session.openChannel("shell");
      channel.setInputStream(System.in);
      channel.setOutputStream(System.out);
      channel.connect();

      InputStream in = channel.getInputStream();
      serviceStatus = true;
      streamtext = "";
      byte tmp = new byte[1024];
      while (true) {
      while (in.available() > 0) {
      int i = in.read(tmp, 0, 1024);
      if (i < 0) break;
      streamtext = new String(tmp, 0, i);

      }
      }
      if (channel.isClosed()) {
      if (in.available() > 0) continue;
      Log.d(TAG, "exit-status: " + channel.getExitStatus());
      break;
      }
      try {
      Thread.sleep(1000);
      } catch (Exception ee) {
      ee.printStackTrace();
      }
      }

      return streamtext;
      } catch (Exception except){
      except.printStackTrace();
      passErrorToActivity("Error: Connection error");
      return "Error: Connection error";
      }
      }


      Start function:



      public void start(){
      try {
      new AsyncTask<Integer, Void, Void>() {
      @Override
      protected Void doInBackground(Integer... params) {
      try {
      passMessageToActivity(connecting(user, password, host, port));
      } catch (Exception ex) {
      ex.printStackTrace();
      }
      return null;
      }
      }.execute(1);
      } catch (Exception exc) {
      exc.printStackTrace();
      }


      "passMessageToActivity" Just creats an intent and sends the "streamtext" to the MainActivity



      I've already tryed it with Session#setServerAliveInterval(int milliseconds) but it didn't work. Is there any posibility to keep the session and channel alive?
      I've seen the solution of this user but this doesn't work for me because it's important that the connection between server and service is always up.







      java android android-studio ssh jsch






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Apr 23 at 18:55









      ItsRedstone

      1




      1
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote














          • If setting keepalives only does not help, you need to keep the session busy with more high-level actions. Like sending a dummy command, like pwd. Though you may need to explain, why you have "shell" session open, that look suspicious.

          • Anyway, there's no way you can guarantee that a connection stays alive. You would have to deal with losing connection occasionally anyway.






          share|improve this answer























          • Thank you! I'll give it a try. The shell channel ist just there to receive the data from the server once. I can also use an "Exec" or any other channel. Maybe you know the app "Termius" on android where you can connect to a server over ssh and then the session and the command promt stays in the background and the session is alive without sending any commands.
            – ItsRedstone
            Apr 24 at 8:43











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














           

          draft saved


          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f49988079%2fhow-can-i-keep-a-jsch-session-alive-on-android%23new-answer', 'question_page');
          }
          );

          Post as a guest
































          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          0
          down vote














          • If setting keepalives only does not help, you need to keep the session busy with more high-level actions. Like sending a dummy command, like pwd. Though you may need to explain, why you have "shell" session open, that look suspicious.

          • Anyway, there's no way you can guarantee that a connection stays alive. You would have to deal with losing connection occasionally anyway.






          share|improve this answer























          • Thank you! I'll give it a try. The shell channel ist just there to receive the data from the server once. I can also use an "Exec" or any other channel. Maybe you know the app "Termius" on android where you can connect to a server over ssh and then the session and the command promt stays in the background and the session is alive without sending any commands.
            – ItsRedstone
            Apr 24 at 8:43















          up vote
          0
          down vote














          • If setting keepalives only does not help, you need to keep the session busy with more high-level actions. Like sending a dummy command, like pwd. Though you may need to explain, why you have "shell" session open, that look suspicious.

          • Anyway, there's no way you can guarantee that a connection stays alive. You would have to deal with losing connection occasionally anyway.






          share|improve this answer























          • Thank you! I'll give it a try. The shell channel ist just there to receive the data from the server once. I can also use an "Exec" or any other channel. Maybe you know the app "Termius" on android where you can connect to a server over ssh and then the session and the command promt stays in the background and the session is alive without sending any commands.
            – ItsRedstone
            Apr 24 at 8:43













          up vote
          0
          down vote










          up vote
          0
          down vote










          • If setting keepalives only does not help, you need to keep the session busy with more high-level actions. Like sending a dummy command, like pwd. Though you may need to explain, why you have "shell" session open, that look suspicious.

          • Anyway, there's no way you can guarantee that a connection stays alive. You would have to deal with losing connection occasionally anyway.






          share|improve this answer















          • If setting keepalives only does not help, you need to keep the session busy with more high-level actions. Like sending a dummy command, like pwd. Though you may need to explain, why you have "shell" session open, that look suspicious.

          • Anyway, there's no way you can guarantee that a connection stays alive. You would have to deal with losing connection occasionally anyway.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 5 hours ago

























          answered Apr 24 at 6:03









          Martin Prikryl

          81.7k22149333




          81.7k22149333












          • Thank you! I'll give it a try. The shell channel ist just there to receive the data from the server once. I can also use an "Exec" or any other channel. Maybe you know the app "Termius" on android where you can connect to a server over ssh and then the session and the command promt stays in the background and the session is alive without sending any commands.
            – ItsRedstone
            Apr 24 at 8:43


















          • Thank you! I'll give it a try. The shell channel ist just there to receive the data from the server once. I can also use an "Exec" or any other channel. Maybe you know the app "Termius" on android where you can connect to a server over ssh and then the session and the command promt stays in the background and the session is alive without sending any commands.
            – ItsRedstone
            Apr 24 at 8:43
















          Thank you! I'll give it a try. The shell channel ist just there to receive the data from the server once. I can also use an "Exec" or any other channel. Maybe you know the app "Termius" on android where you can connect to a server over ssh and then the session and the command promt stays in the background and the session is alive without sending any commands.
          – ItsRedstone
          Apr 24 at 8:43




          Thank you! I'll give it a try. The shell channel ist just there to receive the data from the server once. I can also use an "Exec" or any other channel. Maybe you know the app "Termius" on android where you can connect to a server over ssh and then the session and the command promt stays in the background and the session is alive without sending any commands.
          – ItsRedstone
          Apr 24 at 8:43


















           

          draft saved


          draft discarded



















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f49988079%2fhow-can-i-keep-a-jsch-session-alive-on-android%23new-answer', 'question_page');
          }
          );

          Post as a guest




















































































          Popular posts from this blog

          Schultheiß

          Verwaltungsgliederung Dänemarks

          Liste der Kulturdenkmale in Wilsdruff