SFTP file transfer using Java JSch - java

Here is my code, which retrieves content of the file, on the remote server and display as output.
package sshexample;
import com.jcraft.jsch.*;
import java.io.*;
public class SSHexample
{
public static void main(String[] args)
{
String user = "user";
String password = "password";
String host = "192.168.100.103";
int port=22;
String remoteFile="sample.txt";
try
{
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Establishing Connection...");
session.connect();
System.out.println("Connection established.");
System.out.println("Creating SFTP Channel.");
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
System.out.println("SFTP Channel created.");
InputStream out= null;
out= sftpChannel.get(remoteFile);
BufferedReader br = new BufferedReader(new InputStreamReader(out));
String line;
while ((line = br.readLine()) != null)
{
System.out.println(line);
}
br.close();
sftpChannel.disconnect();
session.disconnect();
}
catch(JSchException | SftpException | IOException e)
{
System.out.println(e);
}
}
}
Now how to implement this program that the file is copied in the localhost and how to copy a file from localhost to the server.
Here how to make work the transfer of files for any format of files.

The most trivial way to upload a file over SFTP with JSch is:
JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.connect();
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
sftpChannel.put("C:/source/local/path/file.zip", "/target/remote/path/file.zip");
Similarly for a download:
sftpChannel.get("/source/remote/path/file.zip", "C:/target/local/path/file.zip");
You may need to deal with UnknownHostKey exception.

Usage:
sftp("file:/C:/home/file.txt", "ssh://user:pass#host/home");
sftp("ssh://user:pass#host/home/file.txt", "file:/C:/home");
Implementation

Below code works for me
public static void sftpsript(String filepath) {
try {
String user ="demouser"; // username for remote host
String password ="demo123"; // password of the remote host
String host = "demo.net"; // remote host address
JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.connect();
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
sftpChannel.disconnect();
session.disconnect();
}catch(Exception ex){
ex.printStackTrace();
}
}
OR using StrictHostKeyChecking as "NO" (security consequences)
public static void sftpsript(String filepath) {
try {
String user ="demouser"; // username for remote host
String password ="demo123"; // password of the remote host
String host = "demo.net"; // remote host address
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);;
session.setPassword(password);
System.out.println("user=="+user+"\n host=="+host);
session.connect();
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
sftpChannel.disconnect();
session.disconnect();
}catch(Exception ex){
ex.printStackTrace();
}
}

Related

Connect to a server with keyboard-interactive password authentication using jsch

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();
I'm connecting to a remote machine without keyboard-interactive authentication, using the above snippet.
But when I'm trying to connect to a server with keyboard-interactive password, I'm getting a
com.jcraft.jsch.JSchException: Auth fail exception.
I added these config and tested, yet didn't succed.
config.put("PreferredAuthentications", "password");
and
config.put("PreferredAuthentications",
"keyboard-interactive,password");
Try this.
JSch jSch;
try {
Properties properties = new Properties();
properties.put("PreferredAuthentications", "publickey,keyboard-interactive,password");
properties.put("StrictHostKeyChecking", "no");
properties.put("UseDNS", "no");
jSch = new JSch();
Session session = jSch.getSession("username", "host/ip", 22);
session.setConfig(properties);
session.setTimeout(10 * 1_000);
session.setPassword("password");
session.connect();
Channel channel = session.openChannel("shell");
channel.connect();
} catch (Exception e) {
e.printStackTrace();
} finally {
channel.disconnect();
session.disconnect();
}

how to set password for ssh connection in java

I want to connect my unix server using java code. first it will connect to my server location. inside that it'll connect to my server name. but at that time it'll ask for confirmation (yes/no) and password I don't know how to do?
Here's my code that I have done.please help me out on this
public static void main (String args[]) {
String user = "user";
String password = "password";
String host = "hostName";
int port=22;
//String remoteFile="/home/john/test.txt";
//String yes="yes";
try {
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Establishing Connection...");
session.connect();
Channel channel = session.openChannel("exec");
// After this it'll ask for confirmation and password
((ChannelExec)channel).setCommand("ssh myServerName");
channel.connect();
InputStream output = channel.getInputStream();
System.out.println("aafter stream");
int readByte = output.read();
StringBuilder outputBuffer = new StringBuilder();
while (readByte != 0xffffffff) {
//System.out.println("read byte" + readByte);
outputBuffer.append((char)readByte);
readByte = output.read();
}
System.out.println(outputBuffer.toString());
channel.disconnect();
} catch (Exception e){
System.err.print("error message" + e);
}
}
You need to get the OutputStream of JSch secured channel and insert the password in it.
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand("sudo -S -p '' " + command);
channel.setInputStream(null);
OutputStream out = channel.getOutputStream();
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
((ChannelExec) channel).setPty(true);
channel.connect();
out.write((password + "\n").getBytes());
out.flush();
Complete source code here: http://codeflex.co/java-run-sudo-command-on-remote-linux-host/
try {
session = jsch.getSession(user, host, port);
}
catch (JSchException e) {
throw new TransferException("Failed to open session - " + params, e);
}
session.setPassword(password);
// Create UserInfo instance in order to support SFTP connection to any machine
// without a key username and password will be given via UserInfo interface.
UserInfo userInfo = new SftpUserInfo();
session.setUserInfo(userInfo);
try {
session.connect(connectTimeout);
}
catch (JSchException e) {
throw new TransferException("Failed to connect to session - " + params, e);
}
boolean isSessionConnected = session.isConnected();
Set the password programmatically like seen above.

Exit status 4 received for JSch exec channel

I'm coding an app to manage some remote devices. I have trouble using JSch to restart dhcpdaemon. I do:
#Override
public void createSession(String hostname) throws JSchException {
this.session = jsch.getSession(username, hostname, 22);
this.session.setPassword(password);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
this.hostname = hostname;
}
private final String RESTART_COMMAND = "/etc/init.d/isc-dhcp-server restart";
public int reloadDHCPDaemon() throws IOException, JSchException, InterruptedException {
int exitStatus = -1;
String command = RESTART_COMMAND;
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setPty(true);
channel.setCommand(command);
channel.connect();
Thread.sleep(1000);
if (channel.isClosed() == true) {
exitStatus = channel.getExitStatus();
channel.disconnect();
}
return exitStatus;
}
I'm getting 4 as an exit status no matter if the command ended successfully or not. The same code but with other commands, for example cp works fine. Can somone help me?

Running multiple commands as root with Jsch()

Im having problems running multiple commands as the root user, using the exec channel. I dont get any exceptions, however the second command is not being executed for some reason.
Here is my code
try {
JSch jsch = new JSch();
String command1 = "touch 1.txt; touch 2.txt";
//"sudo chmod 755 script.sh; sudo sh script.sh";
String user = "user";
String host = "10.68.228.140";
String privateKey = "/home/user/.ssh/blabla";
jsch.addIdentity(privateKey);
System.out.println("identity added ");
Session session = null;
while(session == null) {
Thread.sleep(1000);
session = jsch.getSession(user, host);
}
System.out.println("session created ");
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
while(!session.isConnected()) {
Thread.sleep(1000);
session.connect();
}
System.out.println("session connected.....");
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp)channel;
sftpChannel.put("/home/user/script.sh", "/home/user");
sftpChannel.disconnect();
channel.disconnect();
Channel channel1 = session.openChannel("exec");
((ChannelExec) channel1).setCommand(command);
channel1.connect();
channel1.disconnect();
session.disconnect();
} catch(JSchException e){
e.printStackTrace();
} catch(SftpException se){
se.printStackTrace();
}
catch(Exception e) {
}
So if I leave it like this, everything is fine. The two files are created on the remote machine. But if I give as command the commented line, then the script is not executed. (It changes only mode)
Could you give me a help please? I've been stuck with this all day now.

Execute commands on GlassFish inside a application in java

I need to flush a pool in GlassFish when my application detect an specific Error. Is it possible to execute commands on GlassFish inside a java aplication? I just need to flush this pool when a get the error.
It can be done with SSH
public class FlushPool {
public static void flushConncetionPool(String nameConnectionPool){
Session session = null;
Channel channel = null;
JSch jsch = new JSch();
try {
session = jsch.getSession("username", "host", port);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword("password");
session.connect();
channel = session.openChannel("shell");
OutputStream ops = channel.getOutputStream();
PrintStream ps = new PrintStream(ops, true);
channel.connect();
ps.println("sudo su -");
ps.println("/app/glassfish/glassfish/bin/asadmin --user admin --passwordfile password.txt flush-connection-pool " + nameConnectionPool);
session.diconect();
channel.disconect();
}catch(Exception e){
// do something
}
}
}
password.txt must be in server side
AS_ADMIN_PASSWORD = senha
AS_ADMIN_ADMIN_PASSWORD = senha
AS_ADMIN_USERPASSWORD=senha
AS_ADMIN_MASTERPASSWORD= senha

Categories