Today we will look into the JSch example tutorial. We can use JSch for creating an SSH connection in java. Earlier I wrote a program to connect to remote database on SSH server. Today, I am presenting a program that can be used to connect to the SSH-enabled server and execute shell commands. I am using JSch to connect to remote ssh server from java program.
You can download JSch jar from its official website. You can also get the JSch jars using below maven dependency.
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.53</version>
</dependency>
Below is a simple JSch example program to run the “ls -ltr” command on the server.
import java.io.InputStream;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class JSchExampleSSHConnection {
/**
* JSch Example Tutorial
* Java SSH Connection Program
*/
public static void main(String[] args) {
String host="ssh.journaldev.com";
String user="sshuser";
String password="sshpwd";
String command1="ls -ltr";
try{
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Session session=jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
System.out.println("Connected");
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command1);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in=channel.getInputStream();
channel.connect();
byte[] tmp=new byte[1024];
while(true){
while(in.available()>0){
int i=in.read(tmp, 0, 1024);
if(i<0)break;
System.out.print(new String(tmp, 0, i));
}
if(channel.isClosed()){
System.out.println("exit-status: "+channel.getExitStatus());
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
channel.disconnect();
session.disconnect();
System.out.println("DONE");
}catch(Exception e){
e.printStackTrace();
}
}
}
Let me know if you face any problem with the execution of the JSch example program. It’s a pretty straight forward example of JSch to create an SSH connection in java program. You can download JSch jar file from its official website.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Transfer file using scp command JSch jsch = new JSch(); Session session = jsch.getSession(“root”,“192.168.0.1”,“22”); session.setPassword(“IQANIOT850”); session.setConfig(confing); session.connect(); ChannelExec channel= session.openChannnel(“exec”); channel.setPty(try); channel.setCommand(“scp file:// android_asset/situ.txt” root@192.168.0.1: /mnt/internal_storage); After executing this command using SCP. we need to pass yes or no, then need to provide a password. After providing the password then file transfer is possible. How we can do this.Please help me to resolve this issue.
- Sitakanta
nice ! it works … just changed password to private key … Thank you
- Hemant
Hi Pankaj, I need to enter password after executing pbrun command. In terminal I will get password question and need to enter the password after the question prompts. How can I automate the scenario. Please help me. Thanks
- Sailu
Hi Pankaj, Great article. But I was looking for a way to implement this dynamically. Like a scenario where input commands are spread across time. For example, the user enters one command, then observes its output, then enters another, and then more. And all commands are sent over single channel How can that be achieved ?
- Anmol Chadha
I am executing a command using JSch which starts a process on port 80 That process does not start. When I do ssh using putty and execute the same command, then also it does not work (after doing Jsch) Although, If I use the same command before doing Jsch, then that command works pretty fine. I am running this on Lighsail ubuntu instance.
- Aakash
For example I try to change txt file. Manually in ubuntu command line the command works. Your code is running without errors but the txt file is not changed
- Oleksandr Mudryi
Hi. Could you help me? When I try to setCommand(“sudo apt install …”) - command with some action -> this script doesn’t work. When I set this command manually in linux console it works. I my testing, your code works only when we need to print information from console. How can I do some action by your code? Maybe need to use another protocol
- Oleksandr Mudryi
Hi Pankaj, Thanks for the solution but it seems I am facing issue while executing the command, I am able to connect my server but command execution is not happening. I am getting this error 👇 Connected “ls” isn’t allowed to be executed. exit-status: 1 DONE Could you please help me with this, it will be great help. Thank you in advance.
- Shashank Jha
SHELL PARSER FAILURE: ‘echo’ - no matching entry found: I am getting this error for every command I am trying to execute. Please help
- Palak
How to open the command prompt using session.openChannel and run the bat file?
- Preethi