Connect to ec2 instance through JAVA - spring

I have created REST API to create EC2 instance using AWS JAVA SDK provided.
Now I am trying to connect to created EC2 instance and then need to install software's in the instance again through java. I didn't find any appropriate article for this. Is there any possible way to do this? I don't want to use SSH client like putty.. Thanks..

Sounds like you're looking for a java ssh client.
You should set up key authentication and use the ssh client library from java to execute the installation for you.
See this post: for a list of solutions

public static void connectToEC2(){
try{
JSch jsch=new JSch();
String user = "User-name";
String host = "host";
int port = 22;
File directory = new File(".");
String privateKey = directory.getCanonicalPath() + File.separator + "pem file path";
jsch.addIdentity(privateKey);
System.out.println("identity added ");
Session session = jsch.getSession(user, host, port);
System.out.println("session created.");
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
Channel channel=session.openChannel("shell");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect(3*1000);
}
catch(Exception e){
System.out.println(e);
}
}

Related

Upgrade code from org.eclipse.jetty.websocket.websocket-client to org.eclipse.jetty.websocket.websocket-jakarta-client

I have the following application code in an application that I would like to migrate to Spring3 in order to do so javax is replaced with jakarta.
Any one have any Idea how to migrate the following code:
// Let's create and start the Web Socket
//
// For internal test, we have a self-signed certificate. So we need to short cut certificate check.
// DO NOT DO THAT IN PRODUCTION!
boolean trustAll = (System.getProperty("com.graphql-java-generator.websocket.nosslcheck") != null);
org.eclipse.jetty.util.ssl.SslContextFactory.Client sslContextFactory = new org.eclipse.jetty.util.ssl.SslContextFactory.Client(
trustAll);
org.eclipse.jetty.client.HttpClient httpClient = new HttpClient(sslContextFactory);
org.eclipse.jetty.websocket.client.WebSocketClient wsClient = new WebSocketClient(httpClient);
SubscriptionClientWebSocket<R, T> subscriptionClientWebSocket = new SubscriptionClientWebSocket<R, T>(request,
subscriptionName, subscriptionCallback, subscriptionType, messageType,
graphQLRequest.getGraphQLObjectMapper());
URI uri = getWebSocketURI();
try {
wsClient.start();
org.eclipse.jetty.websocket.client.ClientUpgradeRequest clientUpgradeRequest = new ClientUpgradeRequest();
wsClient.connect(subscriptionClientWebSocket, uri, clientUpgradeRequest);
logger.debug("Connecting to {}", uri);
} catch (Exception e) {
String msg = "Error while opening the Web Socket connection to " + uri;
logger.error(msg);
throw new GraphQLRequestExecutionException(msg, e);
}
Having not found any documentation on how to proceed with this migration.
Tried using the JakartaWebSocketClientContainer but could not find how to use with an UpgradeRequest
Your code is not using javax.websocket, so there's nothing to upgrade.
The techniques you are using in your code to manage the SSL behavior is also not possible in either javax.websocket or jakarta.websocket (There is no API you can use to manage SSL/TLS in those)

Unable to create a client-server connection in ignite

I have successfully created a connection between client and server(localhost) in ignite.But while trying to connect the ignite server which is running in remote IP(eg: 192.168.33.44), I am not able to establish connection. The client side configuration given below.
#Bean(name = "igniteConfiguration")
public IgniteConfiguration igniteConfiguration() {
IgniteConfiguration igniteConfiguration = new IgniteConfiguration();
igniteConfiguration.setClientMode(true);
igniteConfiguration.setPeerClassLoadingEnabled(true);
igniteConfiguration.setLocalHost("127.0.0.1");
TcpDiscoverySpi tcpDiscoverySpi = new TcpDiscoverySpi();
TcpDiscoveryMulticastIpFinder ipFinder = new TcpDiscoveryMulticastIpFinder();
ipFinder.setAddresses(Collections.singletonList("127.0.0.1:47500..47509"));
tcpDiscoverySpi.setIpFinder(ipFinder);
tcpDiscoverySpi.setLocalPort(47500);
// Changing local port range. This is an optional action.
tcpDiscoverySpi.setLocalPortRange(9);
tcpDiscoverySpi.setLocalAddress("localhost");
igniteConfiguration.setDiscoverySpi(tcpDiscoverySpi);
TcpCommunicationSpi communicationSpi = new TcpCommunicationSpi();
communicationSpi.setLocalAddress("localhost");
communicationSpi.setLocalPort(48100);
communicationSpi.setSlowClientQueueLimit(1000);
igniteConfiguration.setCommunicationSpi(communicationSpi);
igniteConfiguration.setCacheConfiguration(cacheConfiguration());
return igniteConfiguration;
}
Can anyone help me to make code change for creating a successful client-server connecion.Thanks in advance.
Since you are moving from localhost deployment, you need to do the following changes:
TcpDiscoveryMulticastIpFinder ipFinder = new TcpDiscoveryMulticastIpFinder();
ipFinder.setAddresses(Collections.singletonList("192.168.33.44:47500..47509"));
Most likely, the server configurations need to be changed as well.

JSCH how to get server answer in shell, in order validate commands to unlock a luks partition remotelly [duplicate]

I'm trying to manage router via Java application using Jcraft Jsch library.
I'm trying to send Router Config via TFTP server. The problem is in my Java code because this works with PuTTY.
This my Java code:
int port=22;
String name ="R1";
String ip ="192.168.18.100";
String password ="root";
JSch jsch = new JSch();
Session session = jsch.getSession(name, ip, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Establishing Connection...");
session.connect();
System.out.println("Connection established.");
ChannelExec channelExec = (ChannelExec)session.openChannel("exec");
InputStream in = channelExec.getInputStream();
channelExec.setCommand("enable");
channelExec.setCommand("copy run tftp : ");
//Setting the ip of TFTP server
channelExec.setCommand("192.168.50.1 : ");
// Setting the name of file
channelExec.setCommand("Config.txt ");
channelExec.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
int index = 0;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
System.out.println(line);
}
session.disconnect();
I get
Line has an invalid autocommand '192.168.50.1'
The problem is how can I run those successive commands.
Calling ChannelExec.setCommand multiple times has no effect.
And even if it had, I'd guess that the 192.168.50.1 : and Config.txt are not commands, but inputs to the copy run tftp : command, aren't they?
If that's the case, you need to write them to the command input.
Something like this:
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channelExec.setCommand("copy run tftp : ");
OutputStream out = channelExec.getOutputStream();
channelExec.connect();
out.write(("192.168.50.1 : \n").getBytes());
out.write(("Config.txt \n").getBytes());
out.flush();
In general, it's always better to check if the command has better "API" than feeding the commands to input. Commands usually have command-line arguments/switches that serve the desired purpose better.
A related question: Provide inputs to individual prompts separately with JSch.

IBM Watson Conversation Service Using Proxy settings from Java API

I have developed a conversation service using IBM Watson and deployed. I am able to access my service using the IBM Watson API explorer. I tried connecting the service using a Java API as explained in https://developer.ibm.com/recipes/tutorials/integration-of-ibm-watson-conversation-service-to-your-java-application/ I am working on a corporate network, so using proxy to access internet. Now I am not able to access the service from my Java API. I am getting below error.
Exception in thread "main" java.lang.RuntimeException: java.net.ConnectException: Failed to connect to gateway.watsonplatform.net/169.48.66.222:443
at com.ibm.watson.developer_cloud.service.WatsonService$1.execute(WatsonService.java:182)
at com.chat.CustomerChat.conversationAPI(CustomerChat.java:47)
at com.chat.CustomerChat.main(CustomerChat.java:32)
Caused by: java.net.ConnectException: Failed to connect to gateway.watsonplatform.net/169.48.66.222:443
at okhttp3.internal.io.RealConnection.connectSocket(RealConnection.java:187)
at okhttp3.internal.io.RealConnection.buildConnection(RealConnection.java:170)
at okhttp3.internal.io.RealConnection.connect(RealConnection.java:111)
at okhttp3.internal.http.StreamAllocation.findConnection(StreamAllocation.java:187)
at okhttp3.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:123)
at okhttp3.internal.http.StreamAllocation.newStream(StreamAllocation.java:93)
at okhttp3.internal.http.HttpEngine.connect(HttpEngine.java:296)
at okhttp3.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
at okhttp3.RealCall.getResponse(RealCall.java:243)
at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:201)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:163)
at okhttp3.RealCall.execute(RealCall.java:57)
How do we set proxy connection in IBM watson Connection service?
My code:(Modified the user credentials and workspace id here)
ConversationService service = new ConversationService("2017-05-26");
service.setUsernameAndPassword("dfgdfg-578a-46b6-55hgg-ghgg4343", "ssdsd455gfg");
MessageRequest newMessage = new MessageRequest.Builder().inputText(input).context(context).build();
String workspaceId = "fgfdgfgg-ce7a-422b-af23-gfgf56565";
MessageResponse response = service.message(workspaceId, newMessage).execute();
Not completely sure about work around for Java, but when i had similar issue with Node, i had to set up proxy variables and that helped. I would recommend you to give a try by setting up proxy variables in eclipse and JVM. And also i think this Java file must be helpful.
After going though IBM API documentation I found below method to set the proxy. It should work.
HttpConfigOptions config = new HttpConfigOptions
.Builder()
.proxy(new Proxy(Proxy.Type.HTTP,
new InetSocketAddress("<Proxy IP>", <Proxy Port>)))
.build();
service.configureClient(config);
I implemented this code with Java-sdk 6.14.0. IBM has discontinued ConversationService package and deprecated Conversation package in this version of SDK. Instead Assistant package has been introduced. My working code is as below.
Assistant service = null;
Context context = null;
if (watsonUser.equalsIgnoreCase(APIKEY_AS_USERNAME))
{
IamOptions iamOptions = new IamOptions.Builder().apiKey(watsonApikey).build();
service = new Assistant(watsonVersion, iamOptions);
}
else
{
service = new Assistant(watsonVersion, watsonUser,watsonPassword);
}
service.setEndPoint(watsonUrl);
if(watsonProxy != null)
{
HttpConfigOptions config = new HttpConfigOptions
.Builder()
.proxy(new Proxy(Proxy.Type.HTTP,
new InetSocketAddress(watsonProxyIP, watsonProxyPort)))
.build();
service.configureClient(config);
}
String workspaceId = watsonWorkspace_id;
InputData input = new InputData.Builder(inputStr).build();
MessageOptions options = new MessageOptions.Builder(workspaceId)
.context(context)
.input(input)
.build();
MessageResponse response = service.message(options).execute();
context = response.getContext();
I have checked the code with Conversation package based implementation. It worked. I couldn't checked with code given in the question as ConversationService package is no more in the current SDK.

kerberos auth and connection pooling in jdbc

I've got Java web application running on Tomcat with SSO via SPNEGO/Kerberos and I want to pass kerberos ticket to database, Oracle DB in my case (like impersonation in MS products). I've found an example of implementation (http://docs.oracle.com/cd/B28359_01/java.111/b31224/clntsec.htm):
Connection conn = (Connection)Subject.doAs(specificSubject, new PrivilegedExceptionAction({
public Object run() {
Connection con = null;
Properties prop = new Properties();
prop.setProperty(AnoServices.AUTHENTICATION_PROPERTY_SERVICES,"("+AnoServices.AUTHENTICATION_KERBEROS5 + ")");
try {
OracleDriver driver = new OracleDriver();
con = driver.connect(url, prop);
}catch (Exception except){
except.printStackTrace();
}
return con;
}
});
String auth = ((OracleConnection)conn).getAuthenticationAdaptorName();
System.out.println("Authentication adaptor="+auth);
printUserName(conn);
conn.close();
But as it is known to create a new connection is an expensive operation. To solve this problem commonly used connection pooling (like c3p0), but I cant find example, how to combine code above and connection pool. Is there any example?

Resources