I'd like to use JSch to open an SFTP connection to download some files.
String SFTPPRIVATEKEY = "/folder/privatekeyfile";
String SFTPUSER = "user";
String SFTPPASS = "";
String SFTPHOST = "server.tld";
String SFTPPORT = "22";
int usePrivateKey = 1;
public boolean connect() {
boolean isConnected = false;
try {
JSch jsch = new JSch();
if (usePrivateKey) {
jsch.addIdentity(SFTPPRIVATEKEY);
}
session = jsch.getSession(SFTPUSER,SFTPHOST,SFTPPORT);
if (!usePrivateKey) {
session.setPassword(SFTPPASS);
}
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
if (session.isConnected() == true) {
log.println("Connection to Session server is successfully");
}
channel = session.openChannel("sftp");
channel.connect();
channelSftp = (ChannelSftp)channel;
isConnected = true;
} catch (JSchException e) {
log.println("SFTPClient Connect ERROR: "+e.getMessage());
e.printStackTrace();
}
return isConnected;
}
If i run my code i get:
com.jcraft.jsch.JSchException: USERAUTH fail
I tried to connect using sftp on the shell on the same client where my Java code runs. I run
sftp -i privatekeyfile user#server.tld
It prompts for a passphrase for the privatekeyfile. I entered the passphrase and the connection works great.
But JSch did not connect. I found no option to set the passphrase in JSch. Maybe this is the problem?
Can some of you help?
Thanks
There's JSch.addIdentity overload that takes the passphrase:
public void addIdentity(String prvkey, String passphrase)
Obligatory warning: Do not use StrictHostKeyChecking=no to blindly accept all host keys. That is a security flaw. You lose a protection against MITM attacks. For the correct (and secure) approach, see: How to resolve Java UnknownHostKey, while using JSch SFTP library?
Related
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.
I want to connect a Linux server and execute a command, but when I send the command sh and su - it requires password, but my program sends password just before it asks. How can i solve this problem?
public class Stream
{
public void getStream(String fileName)
{
String user = usernametext.getText();
String host = hostiptext.getText();
String password = pass.getText();
String command4 = "sh\nsu -\nmypassword\n";
try
{
System.out.println("preparing the host information for stream.");
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect(10 * 1000);
Channel channel = session.openChannel("shell");
InputStream is = new ByteArrayInputStream(command4.getBytes());
channel.setInputStream(is);
channel.setOutputStream(System.out);
channel.connect(15 * 1000);
session.connect(10 * 10);
channel.disconnect();
session.disconnect();
}
catch (Exception ex)
{
System.out.println("Exception found while streaming.");
}
}
}
As you are using a shell channel why do you need to call another sh?
Any how I do the above is to pass individual command and then read the inputStream until you get back to the prompt and then you can set the next input e.g. the password or what ever.
Pseudo-code being
write "su -"
readUntil "password:"
write "******"
readUntil prompt
etc.
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
I'm using the following code to make an SSH connection and download a file to the SSH server through curl. It gives me an exception without a message. Not really sure what to do at this point.
try{
JSch jsch=new JSch();
String host=selectedItem.getHost();
String user="down2home";
int port = selectedItem.getPort();
String password = selectedItem.getPass();
String dlurl = dlurlField.getText().toString();
Session session=jsch.getSession(user, host, port);
session.setPassword(password);
UserInfo ui = new MyUserInfo(){
};
ByteArrayOutputStream out = new ByteArrayOutputStream();
String command = "curl -L --create-dirs -o /home/paul/Desktop/geeknights/geeknights.mp3 "+dlurl+"\r\n";
out.write(command.getBytes());
out.flush();
InputStream in = new ByteArrayInputStream(out.toByteArray());
session.setUserInfo(ui);
session.connect(30*1000); // making a connection with timeout.
Channel channel=session.openChannel("shell");
channel.setInputStream(in);
channel.setOutputStream(System.out);
channel.connect(3*1000);
}
catch(Exception e){
String errorMessage = (e.getMessage()==null)?"Message is empty":e.getMessage();
Log.e("Exception:", errorMessage );
}
Traceback:
06-08 00:33:16.561: E/Exception:(9293): Message is empty
Turned out to be a NetworkOnMainThreadException. Not sure why it wouldn't give me that message with e.getMessage()
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();
}
}