Using JSCH Java [duplicate] - java

This question already has answers here:
Skipping Kerberos authentication prompts with JSch [duplicate]
(2 answers)
Closed 7 years ago.
I am trying to use JsCH for connecting to a remote server and then manipulate PostgreSQL.
Everything going fine if I use PUTTY and also with JSCH.
My only problem is the JsCH only accepts username and password from the Eclipse console even if I set these properties.
public void connect() {
//
int assigned_port;
final int local_port=5432;
// Remote host and port
final int remote_port=5432;
final String remote_host="myserver011";
try {
JSch jsch = new JSch();
// Create SSH session. Port 22 is your SSH port which
// is open in your firewall setup.
Session session = jsch.getSession("companyusername", remote_host, 22);
session.setPassword("password");
// Additional SSH options. See your ssh_config manual for
// more options. Set options according to your requirements.
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
config.put("Compression", "yes");
config.put("ConnectionAttempts","2");
session.setConfig(config);
// Connect
session.connect();
// Create the tunnel through port forwarding.
// This is basically instructing jsch session to send
// data received from local_port in the local machine to
// remote_port of the remote_host
// assigned_port is the port assigned by jsch for use,
// it may not always be the same as
// local_port.
assigned_port = session.setPortForwardingL(local_port,
remote_host, remote_port);
System.out.println("SSH Connection succes!");
} catch (JSchException e) {
e.printStackTrace();
LOGGER.log(Level.SEVERE, e.getMessage()); return;
}
if (assigned_port == 0) {
LOGGER.log(Level.SEVERE, "Port forwarding failed !");
return;
}
}
But the console still needs the username and password.
Kerberos username [myusername]: companyusername <---- here I set again the username
Kerberos password for companyusername : password <---- and the password
SSH Connection succes!
Opened database successfully
And then everything works. But I don't want to set these again, and I cant find anywhere the source of this "bug"?! I don't know, maybe it's a server config parameter to force the user to manually give the input?
Any advice or hint would be great.

//this works pretty well for me.
Session session;
ssh = new JSch();
session = ssh.getSession(username,hostname,port);
session.setConfig(config);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking","no");
session.connect();

Related

How to get server's SSH version without authenticating in JSch?

I tried to use JSch:
#Test
public void test() throws Exception {
var session = new JSch().getSession("host");
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
var version = session.getServerVersion();
System.out.println("version = " + version);
}
but I'm getting
java.lang.NullPointerException: Cannot read the array length because "str" is null
It seems that this implementation requires you to connect and authenticate.
How can I get this information with Java, without the need to authenticate?
This Python code works for me on a server that requires authentication yet I didn't have to authenticate in order to get the remote version.
import paramiko
ssh = paramiko.Transport(("host", 22))
ssh.start_client()
print(ssh.remote_version)
ssh.close()
The SSH identification string is sent in plain text right after opening the connection.
So you do not need an SSH library to obtain the string.
You can do with a simple code like shown here:
Read Data from a Java Socket
Or just try to login using dummy credentials with JSch and then read Session.getServerVersion.
You do not even have to try to login. You can abort the connection right at the host key check:
config.put("StrictHostKeyChecking", "yes");

Algorithm negotiation fail error while connecting to solaris server through jsch

I am trying to connect to remote sftp server over ssh with JSch (0.1.52) but during session.connect(); I am getting Algorithm negotiation fail exception:
code snippet which I tried given below:
log.info("trying to connect to ssh");
JSch.setLogger(new MyLogger());
JSch jsch = new JSch();
String host = "abcd";
int port =22;
String success;
Session session = jsch.getSession(username,host, port);
log.info("Recieved the username>>>>>>>>>>>>>"+ username);
session.setPassword(password);
log.info("Recieved the password>>>>>>>>>>>>>"+ password);
Properties config = new Properties();
config.put("kex", "curve25519-sha256,curve25519-sha256#libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256");
config.put("CheckKexes", "diffie-hellman-group-exchange-sha256");//diffie-hellman-group-exchange-sha256
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
ConfigRepository configRepository =
com.jcraft.jsch.OpenSSHConfig.parseFile("/abc/config_file.txt");
jsch.setConfigRepository(configRepository);
log.info("Establishing connection to host...");
log.info("Session.................."+session);
session.connect();
Channel channel=session.openChannel("sftp");
channel.connect();
I tried updating the jsch latest jar,jdk 1.8 in java & corrected the checkkexes & ciphers in server and client but getting the same Algorithm negotiation fail. Please provide your suggestions to resolve this error, Thank you

Can't connect to corporate machine with SSH JCraft JSch

I've got a problem with connecting to corporate machine with SSH using JCraft JSch.
public static void main(String[] args) throws JSchException {
JSch jSch = new JSch();
String username = "username";
String host = "host";
int port = 22;
jSch.addIdentity("Path\\to\\key\\file");
jSch.setKnownHosts("known_hosts");
/* In known_hosts file, I've got Host IP, and public key,
the same that's on server
*/
Session session = jSch.getSession(username,host,port);
Properties config = new Properties();
config.put("StrictHostKeyChecking","yes");
session.setConfig(config);
session.connect(5000);
}
That's my code, after running it, there is an error: HostKey has been changed: [host adress], if i change StrictHostKeyChecking to no, another error appears: Auth fail.
I can connect to that machine via PuTTy or WinSCP, and I dont need to use tunneling. Also the key format is right(I made that mistake allready). When I connect to the machine via PuTTy, I need to pick the right machine(there are 5), and each of them has their own key pair, and the main connection to the "menu", has also it's own key pair, it's CAPI key.
Does anyone had something like that before? Also I made a forwarding port, and tried to connect with that, but I'm not sure how it works. Can anyone tell me how to do the port forwarding, or maybe somebody has another idea.
Thanks in advice

Why is Jsch asking for Kerberos username? [duplicate]

So I'm writing a little program that needs to connect to a remote server through SFTP, pull down a file, and then processes the file. I came across JSch through some answers here and it looked perfect for the task. So far, easy to use and I've got it working, with one minor thing I'd like to fix. I'm using the following code to connect and pull the file down:
JSch jsch = new JSch();
Session session = null;
try {
session = jsch.getSession("username", "127.0.0.1", 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword("password");
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
sftpChannel.cd(REMOTE_FTP_DIR);
sftpChannel.lcd(INCOMING_DIR);
sftpChannel.get(TMP_FILE, TMP_FILE);
sftpChannel.exit();
session.disconnect();
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
}
So this works and I get the file. I'm running this code on a linux server and when I run the code JSch asks me for my Kerberos username and password. It looks like:
Kerberos username [george]:
Kerberos password for george:
I just hit enter for both questions and then the program seems to continue on with no problems. However I need this code to be automated through a cron task and so I'd rather not having it pausing the program to ask me these two questions. Is there something I'm not supplying it so that it won't ask this? Something I need to do to stop it asking? Hopefully someone has some ideas. Thanks.
Thought I'd post an answer here since in case anyone else ends up running into a similar issue. Turns out I am missing a piece of code that makes all the difference. I just needed to add
session.setConfig("PreferredAuthentications",
"publickey,keyboard-interactive,password");
before
session.connect();
and everything works perfectly now.
While the solution in the self-accepted answer is correct, it lacks any explanation.
The problem is that the OP have a Kerberos/GSSAPI authentication set as the preferred (the JSch default). Yet OP does not seem to actually use/want it, as OP claims not to specify any username or password for the Kerberos prompts.
This problem can appear spontaneously, when either Kerberos gets installed on the the client PC or the server starts to support Kerberos.
The solution is to remove the Kerberos/GSSAPI (gssapi-with-mic) from the list of preferred authentication methods in JSch:
session.setConfig(
"PreferredAuthentications", "publickey,keyboard-interactive,password");
All answers are correct, I'll just add here the way it can be done for Spring Integration when trying to integrate with an SFTP server.
So, if you are using SFTP Spring Integration and the weird user and password for Kerberos is prompting in the same way the OP is asking.
Then modify your Spring configuration (I'm using Java Spring Integration config, if you are using XML config you can try to translate it yourself - I really don't like XML config :P ):
So in the bean you are using as SessionFactory you need to add this change in config:
#Bean
public SessionFactory<LsEntry> sftpSessionFactory() {
DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory(true);
factory.setHost("hostname");
factory.setPort(22);
factory.setUser("username");
factory.setPassword("superstrongpassword");
factory.setAllowUnknownKeys(true);
factory.setSessionConfig(buildSessionProperties());
return new CachingSessionFactory<>(factory);
}
/**
* Build JSch property PreferredAuthentications without "gssapi-with-mic"
* This way it won't prompt for Kerberos authentication every time it tries to connect
* to the SFTP.
*/
private Properties buildSessionProperties() {
Properties sessionProperties = new Properties();
sessionProperties.setProperty("PreferredAuthentications", "publickey,keyboard-interactive,password");
return sessionProperties;
}

Trouble sending via gmail's SMTP server with Java

One of my customers is using Gmail for business (part of Google Apps) and I had to reconfigure the website I've developed so it would match the new credentials. After a bit of struggle due to TLS errors, I've managed to make the code work on localhost and on my test server (both Apache Tomcat 5.5). Everything was going smooth until I had to move it on his server (another Tomcat 5.5 as the hosting company told me). On the client's server I get the following error:
javax.mail.SendFailedException: Sending failed;
nested exception is:
class javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.io.IOException: Couldn't connect using "javax.net.ssl.SSLSocketFactory" socket factory to host, port: smtp.gmail.com, 465; Exception: java.lang.reflect.InvocationTargetException
The strange thing is that on localhost and the test server the port 465 works fine, and the guys from hosting said that port is opened on their server.
The code that connects to the mailserver is:
private void initConfigParams() throws CMSGeneralException {
try {
props = System.getProperties();
String smtpHost = Messages.getDBConfString("mail.smtp.host");
String mailPort = Messages.getDBConfString("mail.smtp.port");
String socketFallback = Messages.getDBConfString("mail.smtp.socketFactory.fallback");
String enableTls = Messages.getDBConfString("mail.smtp.starttls.enable");
String authSmtp = Messages.getDBConfString("mail.smtp.auth");
String tlsRequired = Messages.getDBConfString("mail.smtp.stattls.required");
String sktFactory = Messages.getDBConfString("mail.smtp.socketFactory.class");
props.put("mail.smtp.starttls.enable", enableTls);
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.auth", authSmtp);
props.put("mail.smtp.starttls.required", tlsRequired);
props.setProperty("mail.smtp.socketFactory.class", sktFactory);
props.setProperty("mail.smtp.socketFactory.fallback", socketFallback);
props.setProperty("mail.smtp.port", mailPort);
props.setProperty("mail.smtp.socketFactory.port", mailPort);
props.put("mail.transport.protocol", Messages.getDBConfString("mail.transport.protocol"));
Authenticator auth = null;
userName = Messages.getDBConfString("mail.username");
userPassword = Messages.getDBConfString("mail.userpassword");
if (!CMSUtils.isEmptyString(userName) && !CMSUtils.isEmptyString(userPassword)){
/* props.put("mail.smtp.auth", "true"); */
auth = new SMTPAuthenticator(userName, userPassword);
}
session = Session.getDefaultInstance(props, auth);
session.setDebug(false);
address = new InternetAddress[1];
address[0] = new InternetAddress(recipients);
mbText = new MimeBodyPart();
mbText.setContent(text, "text/html");
mp = new MimeMultipart();
mp.addBodyPart(mbText);
} catch (MessagingException e) {
e.printStackTrace();
throw new CMSGeneralException();
}
}
With the following .properties file
mail.smtp.starttls.enable=true
mail.smtp.host=smtp.gmail.com
mail.smtp.auth=true
mail.smtp.starttls.required=true
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
mail.smtp.socketFactory.fallback=false
mail.smtp.port=465
mail.transport.protocol=smtps
mail.username=website#example.com
mail.userpassword=password
mail.from=website#example.com
mail.to=mail#example.com
I tried the other ports for GMail, 587, but it doesn't work on any of the servers. Not even port 25 won't do the trick.
So, what am I doing wrong, and what should I do to make the mailing work?
Get rid of all the socket factory properties; if you're using a reasonably recent version of JavaMail you don't need them. See the JavaMail FAQ for how to configure JavaMail to access Gmail. You'll also find debugging tips there if it still doesn't work.
Also, change Session.getDefaultInstance to Session.getInstance.
And finally, if you're setting "mail.transport.protocol" to "smtps", you need to set the other properties as "mail.smtps." properties, not "mail.smtp." properties.
It seems to you have problems with java.lang.reflect.InvocationTargetException. So, I mean it's not a network problem. May be you've specified some parameters wrong and JavaMail API routes couldn't invoke a method. May be you should also specify property mail.smtp.ssl.socketFactory.
Some documentation here http://javamail.kenai.com/nonav/javadocs/com/sun/mail/smtp/package-summary.html .

Categories

Resources