Connect a server through another server in putty/jump server using java - java

I need to connect to another server after i logged into putty server using java code and I need to download files from second server after I connected. Do anyone have the code.
Once the putty server screen appears, I enter username and password then i pass the command "ssh servername" then i need to enter yes for the question appears.
Once the above done, I have to navigate to different folders and download the files to Server1.
I used the below code to connect to server1 and it connected, After that I am not sure of jumping to server 2.
I am getting the error as below when i am trying a remote server through another server. The error and code I have entered below
Error:
Exception in thread "main" com.jcraft.jsch.JSchException: connection is closed by foreign host
at com.jcraft.jsch.Session.connect(Session.java:236)
at com.jcraft.jsch.Session.connect(Session.java:150)
at putty.putty.main(putty.java:42)
Code I used:
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;
import org.apache.commons.io.IOUtils;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
public class putty {
public static String user = "username";
public static String host = "server1.server.net";
public static String password = "Password";
public static String secondpassword = "Password";
public static String tunnelRemoteHost = "server2.server.net";
public static void main(String[] args) throws IOException, JSchException, SftpException {
StringBuilder outputBuffer = new StringBuilder();
int port = 22;
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
int forwardPort = 2222;
session.setPortForwardingL(forwardPort, tunnelRemoteHost, 22);
Session secondSession = jsch.getSession(user, "localhost", forwardPort);
secondSession.setPassword(secondpassword);
secondSession.setConfig("StrictHostKeyChecking", "no");
secondSession.connect();
session.openChannel("sftp");
// now we're connected to the secondary system
Channel channel = secondSession.openChannel("sftp");
channel.connect();
ChannelSftp channelSftp = (ChannelSftp)channel;
channel.disconnect();
session.disconnect();
System.out.print(outputBuffer.toString());
}
}
I am using latest jsch jar 0.1.55. Can someone look into and let me what I am missing here.

Try to update jsch to 0.1.55 https://mvnrepository.com/artifact/com.jcraft/jsch/0.1.55
Your current version 0.1.42 is almost 10 years old. It may not change anything or may help.

I am able to achieve what i wanted through Windows Commandline with plink command

Related

Unit testing FTP in Java (JSch & MockFtpServer)

I'm using JCraft's JSch library for as a FTP client for my program, it's working fine. But I had difficulties creating a mock (MockFtpServer) for unit testing.
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockftpserver.fake.FakeFtpServer;
import org.mockftpserver.fake.UserAccount;
import org.mockftpserver.fake.filesystem.FileEntry;
import org.mockftpserver.fake.filesystem.FileSystem;
import org.mockftpserver.fake.filesystem.UnixFakeFileSystem;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Properties;
#RunWith(SpringRunner.class)
#SpringBootTest
public class SFTPManagerTest {
static FakeFtpServer fakeFtpServer;
#BeforeClass
public static void startFTP() throws Exception {
fakeFtpServer = new FakeFtpServer();
fakeFtpServer.setServerControlPort(9999);
FileSystem fileSystem = new UnixFakeFileSystem();
fileSystem.add(new FileEntry("/data/JFS_HCID_APPLICATION_STATUS_20190109.TXT", "<schema/>"));
fakeFtpServer.setFileSystem(fileSystem);
UserAccount userAccount = new UserAccount("user", "password", "/");
fakeFtpServer.addUserAccount(userAccount);
fakeFtpServer.start();
}
#Test
public void getFileListing() {
try {
JSch jsch = new JSch();
Session jschSession = jsch.getSession("user", "localhost", 9999);
jschSession.setPassword("password");
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
jschSession.setConfig(config);
jschSession.connect();
Channel jschChannel = jschSession.openChannel("ftp");
jschChannel.connect();
ChannelSftp channel = (ChannelSftp) jschChannel;
Vector v = channel.ls("/data");
Assert.assertNotNull(v);
} catch (Exception ex) {
ex.printStackTrace();
}
}
#AfterClass
public static void stopFTP() {
fakeFtpServer.stop();
}
}
Dependencies:
com.jcraft:jsch:0.1.55
org.mockftpserver:MockFtpServer:2.7.1
Output: it always stuck/stall during executing test method, not finishing. When stuck/stalling I could access the MockFtpServer with WinSCP or FTP CLI. From the log it seems the command from JSch not recognized.
2019-02-18 17:54:15,996 INFO [Thread-0] org.mockftpserver.core.server.AbstractFtpServer: Connection accepted from host /127.0.0.1
2019-02-18 17:54:16,002 INFO [Thread-6] org.mockftpserver.core.command.AbstractTrackingCommandHandler: Sending reply [220 Service ready for new user. (MockFtpServer 2.7.1; see http://mockftpserver.sourceforge.net)]
2019-02-18 17:54:16,004 INFO [Thread-6] org.mockftpserver.core.session.DefaultSession: Received command: [SSH-2.0-JSCH-0.1.54]
2019-02-18 17:54:16,004 WARN [Thread-6] org.mockftpserver.core.command.UnsupportedCommandHandler: No CommandHandler is defined for command [SSH-2.0-JSCH-0.1.54]
2019-02-18 17:54:16,005 INFO [Thread-6] org.mockftpserver.core.command.AbstractTrackingCommandHandler: Sending reply [502 Command not implemented: SSH-2.0-JSCH-0.1.54.]
Where did i go wrong?
JSch is an SSH/SFTP library. You cannot use an FTP server to test it. You need to use an SFTP server. FTP and SFTP are two completely unrelated and different protocols.

GroovyCastException: Cannot cast object 'class com.jcraft.jsch.ChannelExec' with class 'java.lang.Class' to class

I am trying to connect a linux machine and executing my shell script named as "myscript.sh". While running it, I am getting cast exception while same is working fine in Java.
I am getting below error:
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'class com.jcraft.jsch.ChannelExec' with class 'java.lang.Class' to class 'com.jcraft.jsch.ChannelExec' error at line: 29
Below is the code snippet:
`import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
JSch jsch = new JSch();
Session session;
try {
// Open a Session to remote SSH server and Connect.
// Set User and IP of the remote host and SSH port.
session = jsch.getSession("user", "host", 22);
// When we do SSH to a remote host for the 1st time or if key at the remote host
// changes, we will be prompted to confirm the authenticity of remote host.
// This check feature is controlled by StrictHostKeyChecking ssh parameter.
// By default StrictHostKeyChecking is set to yes as a security measure.
session.setConfig("StrictHostKeyChecking", "no");
//Set password
session.setPassword("Pwd");
session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
session.connect();
// create the execution channel over the session
ChannelExec channelExec = (ChannelExec)
session.openChannel("exec");
// Set the command to execute on the channel and ex ecute the command
channelExec.setCommand("sh myscript.sh");
channelExec.connect();
// Get an InputStream from this channel and read messages, generated
// by the executing command, from the remote side.
InputStream ab = channelExec.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(ab));
String line;
while ((line = reader.readLine()) != null) {
log.info(line);
}
// Command execution completed here.
// Retrieve the exit status of the executed command
int exitStatus = channelExec.getExitStatus();
if (exitStatus > 0) {
log.info("Remote script exec error! " + exitStatus);
}
//Disconnect the Session
session.disconnect();
} catch (JSchException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}`
The problem is here
ChannelExec channelExec = (ChannelExec)
session.openChannel("exec");
The newline tells the groovy parser that those are two statements. This is equivalent to the following Java code:
ChannelExec channelExec = (ChannelExec.class);
session.openChannel("exec");
Note that the name of a class (here ChannelExec) becomes a Class-Literal in Groovy, whereas in Java you need to add .class, e.g. ChannelExec.class
What you want is this:
ChannelExec channelExec = (ChannelExec) session.openChannel("exec")

Using Java Mail

I would like to send an email using my Java Application.
When I press a button, there should be automatically sent an email , but somehow I didn't find the solution yet.
I found a lot of example codes in the internet, but it doesn't matter if I use Gmail / gmx or outlook, I always receive the message :
"Could not connect to SMTP host: mail.gmx.net, port: 587;
nested exception is:
java.net.ConnectException: Connection timed out: connect"
Based on the domain, so the host is mail.gmx.net or smtp.office365.com etc..
So I think there's somehow a connection problem, but I wasn't able to fix it.
Do you have some ideas / codes that worked for you ?
Thank you in advance.
Tobias
Use this code for send Email .This works fine for me
package SendMail;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
* #author akash073
*
*/
public class CrunchifyJavaMailExample {
//static Properties mailServerProperties;
// static Session getMailSession;
// static MimeMessage generateMailMessage;
public static void main(String args[]) throws AddressException, MessagingException {
generateAndSendEmail();
System.out.println("\n\n ===> Your Java Program has just sent an Email successfully. Check your email..");
}
public static void generateAndSendEmail() throws AddressException, MessagingException {
String smtpHost="put Your Host";
String smtpUser="UserName in full #somthing.com";
String smtpPassword="your password";
int smtpPort=25;//Port may vary.Check yours smtp port
// Step1
System.out.println("\n 1st ===> setup Mail Server Properties..");
Properties mailServerProperties = System.getProperties();
//mailServerProperties.put("mail.smtp.ssl.trust", smtpHost);
// mailServerProperties.put("mail.smtp.starttls.enable", true); // added this line
mailServerProperties.put("mail.smtp.host", smtpHost);
mailServerProperties.put("mail.smtp.user", smtpUser);
mailServerProperties.put("mail.smtp.password", smtpPassword);
mailServerProperties.put("mail.smtp.port", smtpPort);
mailServerProperties.put("mail.smtp.starttls.enable", "true");
System.out.println("Mail Server Properties have been setup successfully..");
// Step2
System.out.println("\n\n 2nd ===> get Mail Session..");
Session getMailSession = Session.getDefaultInstance(mailServerProperties, null);
MimeMessage generateMailMessage = new MimeMessage(getMailSession);
generateMailMessage.setFrom (new InternetAddress (smtpUser));
generateMailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress("akash073#waltonbd.com"));
generateMailMessage.addRecipient(Message.RecipientType.CC, new InternetAddress("akash073#gmail.com"));
generateMailMessage.setSubject("Greetings from Crunchify..");
String emailBody = "2.Test email by Crunchify.com JavaMail API example. " + "<br><br> Regards, <br>Crunchify Admin";
generateMailMessage.setContent(emailBody, "text/html");
System.out.println("Mail Session has been created successfully..");
// Step3
System.out.println("\n\n 3rd ===> Get Session and Send mail");
Transport transport = getMailSession.getTransport("smtp");
// Enter your correct gmail UserID and Password
// if you have 2FA enabled then provide App Specific Password
transport.connect(smtpHost,smtpPort, smtpUser, smtpPassword);
transport.sendMessage(generateMailMessage, generateMailMessage.getAllRecipients());
transport.close();
}
}
For more info crunchify

How to pass username and password in the localhost url to connect with the memcached in Java?

Hi, I want to pass the username and password to connect to localhost where I have deployed memcached.
Here is my code.
import java.io.IOException;
import java.net.InetSocketAddress;
import net.spy.memcached.MemcachedClient;
public class MemCaheConnection {
public void ConnectMemCaheConnection() throws IOException{
MemcachedClient c = new MemcachedClient(new InetSocketAddress("localhost", 11211));
c.flush();
}
}
Can anyone help?
without explicit use of http://code.google.com/p/memcached/wiki/SASLAuthProtocol there is no need for username+password, did you check the service is running on port 11211?

how to automate sending commands using SSH factory

I am using ssh factory to automate the logins. I have to automate logins till 4 gateways and send commands and get output's of it. I have successfully automated till 3 gateways. Now i have to fire command "telnet remote_ip" to get into the 4th gateway. Where i am using telnet sessions for this 4th gateway alone since i need to fire "telnet ip", since it is using telnet protocol over here. But for the previous 3 gateway's i've used ssh sessions. But it is not firing this "telnet ip" command. Can some1 help me regarding this?.
Below is the code, where i am trying to automate it.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Scanner;
import com.jscape.inet.ssh.Ssh;
import com.jscape.inet.ssh.SshAdapter;
import com.jscape.inet.ssh.SshConnectedEvent;
import com.jscape.inet.ssh.SshDataReceivedEvent;
import com.jscape.inet.ssh.SshDisconnectedEvent;
import com.jscape.inet.ssh.SshException;
import com.jscape.inet.ssh.SshScript;
import com.jscape.inet.ssh.SshSession;
import com.jscape.inet.ssh.SshTask;
import com.jscape.inet.ssh.connection.channels.SessionClient;
import com.jscape.inet.ssh.connection.channels.SessionRequests;
import com.jscape.inet.ssh.util.SshParameters;
import com.jscape.inet.telnet.Telnet;
import com.jscape.inet.telnet.TelnetException;
import com.jscape.inet.telnet.TelnetListener;
import com.jscape.inet.telnet.TelnetScript;
import com.jscape.inet.telnet.TelnetSession;
import com.jscape.inet.telnet.TelnetTask;
public class SshScriptTutorial extends SshAdapter {
public SshScriptTutorial() {}
public void executeSshScript(String hostname, String username, String password)
throws SshException, IOException, InterruptedException, TelnetException
{
// assumes that SSH shell prompt is ">" .. this MUST match exactly
String shellPrompt = ">";
String shellPrompt1 = ":";
// initialize and create new Ssh instance
SshParameters sshParams = new SshParameters(hostname,username,password);
Ssh ssh = new Ssh(sshParams);
// register this class to receive Ssh events
ssh.addSshListener(this);
// create new script object and bind to the given ssh object
SshScript script = new SshScript(ssh);
// add tasks to script object
script.addTask(new SshTask(shellPrompt, "show host", shellPrompt));
script.addTask(new SshTask(shellPrompt, "ssh ssgpun", shellPrompt1)); // 2nd g/w
script.addTask(new SshTask(shellPrompt1, "password", shellPrompt));
script.addTask(new SshTask(shellPrompt, "net ip", shellPrompt1)); // 3rd gateway
script.addTask(new SshTask(shellPrompt1, "username", shellPrompt1));
script.addTask(new SshTask(shellPrompt1, "password", shellPrompt));
// till this it is working
// connect to SSH server and execute script
ssh.connect();
// wait until last task is complete
while(!script.isComplete()) {
try {
Thread.sleep(500);
} catch(Exception e) {
System.err.println(e.getMessage());
}
}
// disconnect from server
// ssh.disconnect();
//**
Here i am trying to get into the last remote server using command "telnet ip" using telnet session since it is involving telnet protocol. But it is not firing this command itself. So, can anybody help me regarding this. How to do?... I have even tried using ssh sessions for this "telnet ip" and for username and pass. If i use ssh session for this 4th gateway, i am able to automate only "telnet ip" and it is asking for login name, and login name is not automated. So, i have tried both ssh sessions and telnet sessions. I dont know what is the prob or how to solve it.
Kindly help...
//**
// create new Telnet instance
Telnet telnet = new Telnet("10.228.128.33");
// create new TelnetScript instance and bind to Telnet instance
TelnetScript script_t = new TelnetScript(telnet);
// create a task that waits for login prompt and submits username
TelnetTask username_t = new TelnetTask(shellPrompt1,"switchind", shellPrompt1);
// create task that waits for password prompt and submits password
TelnetTask password_t = new TelnetTask(shellPrompt1, "Indore123", shellPrompt);
// add tasks to script
script_t.addTask(username_t);
script_t.addTask(password_t);
// connect to telnet server … script is executed automatically
telnet.connect();
}
public void connected(SshConnectedEvent event) {
System.out.println("Connected to host: " + event.getHost());
}
public void disconnected(SshDisconnectedEvent event) {
System.out.println("Disconnected from host: " + event.getHost());
}
public void dataReceived(SshDataReceivedEvent event) {
System.out.print(event.getData());
}
public static void main(String[] args)
{
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String hostname = "host_ip";
String username = "username";
System.out.print("Enter password: ");
String password = reader.readLine();
SshScriptTutorial tutorial = new SshScriptTutorial();
tutorial.executeSshScript(hostname, username, password);
} catch(Exception e) {
e.printStackTrace();
}
}
}

Categories