VPN connect using Java - java

Is there a way to connect and disconnect VPN in Forticlient programmatically?
I see that with Cisco VPN Client, there are options such as using the APIs they provide or executing connectivity commands from my Java code. Views and opinions on these ways of connecting to VPN are also most welcome.
I am looking for such options or any other that is possible, with Forticlient software.
Any directions from here would be of great help.
My trial so far :
private static final String COMMAND = "C:/Program Files/Cisco/Cisco AnyConnect Secure Mobility Client/vpncli";
private ExpectJ exp = new ExpectJ(10);
public void connectToVPNViaCLI(String server, String uname, String pwd)
{
try {
String command = COMMAND + " connect " + server;
Spawn sp = exp.spawn(command);
sp.expect("Username: ");
sp.send(uname + "\n");
sp.expect("Password: ");
sp.send(pwd + "\n");
sp.expect("accept? [y/n]: ");
sp.send("y" + "\n");
} catch(Exception e) {
LOGGER.severe(e.getMessage());
}
}

Related

Docker -- How To Connect Services Together Using Docker Compose With ZeroMQ

I have a docker compose file:
version: '3.3'
services:
bifrost:
image: ivorytoast3853/bifrost
container_name: bifrost-app
ports:
- "8084:8084"
thor:
image: ivorytoast3853/thor
container_name: thor-app
ports:
- "8085:8084"
loki:
image: ivorytoast3853/loki
container_name: loki-app
ports:
- "8086:8084"
Which is meant to test a ZeroMQ app.
Bifrost: Broker
Thor: Server
Loki: Client
I am using the exact code from ZeroMQ's start guide (and when I start it locally -- without Docker it works (Loki sends messages to Thor through the Bifrost)).
For reference, the 3 files are:
LOKI
try (ZContext context = new ZContext()) {
ZMQ.Socket requester = context.createSocket(SocketType.REQ);
boolean didConnect = requester.connect("tcp://0.0.0.0:5559");
log.info("Loki connected to the bifrost: " + didConnect);
for (int request_nbr = 0; request_nbr < 10; request_nbr++) {
requester.send("One", 0);
String reply = requester.recvStr(0);
System.out.println("Received reply " + request_nbr + " [" + reply + "]");
}
}
Thor
try (ZContext context = new ZContext()) {
ZMQ.Socket responder = context.createSocket(SocketType.REP);
boolean didConnect = responder.connect("tcp://0.0.0.0:5560");
log.info("Thor connected to the bifrost: " + didConnect);
while (!Thread.currentThread().isInterrupted()) {
String string = responder.recvStr(0);
System.out.printf("Received request: [%s]\n", string);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
responder.send("You sent me: " + string);
}
}
Bifrost
while (true) {
try (ZContext context = new ZContext()) {
ZMQ.Socket frontend = context.createSocket(SocketType.ROUTER);
ZMQ.Socket backend = context.createSocket(SocketType.DEALER);
frontend.bind("tcp://*:5559");
backend.bind("tcp://*:5560");
log.info("Started Bifrost to connect Loki and Thor");
ZMQ.Poller items = context.createPoller(2);
items.register(frontend, ZMQ.Poller.POLLIN);
items.register(backend, ZMQ.Poller.POLLIN);
boolean more = false;
byte[] message;
while (!Thread.currentThread().isInterrupted()) {
items.poll();
if (items.pollin(0)) {
while (true) {
message = frontend.recv(0);
more = frontend.hasReceiveMore();
backend.send(message, more ? ZMQ.SNDMORE : 0);
if (!more) {
break;
}
}
}
if (items.pollin(1)) {
while (true) {
message = backend.recv(0);
more = backend.hasReceiveMore();
frontend.send(message, more ? ZMQ.SNDMORE : 0);
if (!more) {
break;
}
}
}
}
}
}
Am I doing something wrong with the Docker compose file? I know Docker compose creates a network automatically...
Thanks!
Turns out I was not internalizing fundamental ideas of docker and containers as a whole.
The Problem
I was trying to connect to: "tcp://0.0.0.0:5560" from Loki/Thor to Bifrost.
Why is that a problem?
It is a problem because unlike starting all 3 spring boot applications on the same computer (with the same IP), I am starting each spring application in its OWN docker container -- which has its OWN UNIQUE IP. Therefore, I cannot say to Loki/Thor to "on this computer (IP), connect to Bifrost." -- since Bifrost lies on a completely separate IP address.
How did I fix it:
I changed the docker-compose file for Bifrost to contain a network alias:
image: ivorytoast3853/bifrost
container_name: bifrost-app
networks:
my-net:
aliases:
- queue
All this does is allow me to say, "if I give you the hostname of "queue", please connect to the IP address of the container that the Bifrost application is found on."
Then, all I had to do is change the host:port string in Loki and Thor to reflect the following:
responder.connect("tcp://queue:5560");
Hope this helps anyone who comes across a similar issue (or lack of understanding in my case)

How to automate connect to a ssh server with keyboard-interactive authentication using jsch lib in java [duplicate]

This question already has an answer here:
How to automate challenge-response authentication using Java
(1 answer)
Closed 2 years ago.
I want to automate connect to a ssh server with keyboard-interactive authentication(or challenge-response authentication) using jsch.
I'd already set userinfo and config like this.
session.setUserInfo(myUserInfo);
session.setConfig("StrictHostKeyChecking", "no");
session.setConfig("PreferredAuthentications",
"publickey,keyboard-interactive,password");
myUserInfo object implement the UserInfo interface
When I debug the source, I'm always getting a com.jcraft.jsch.JSchException: Auth fail exception.
Somebody said myUserInfo should implement UIKeyboardInteractive.
But I can't understand the official JSch UserAuthKI example. It's too complicated to understand.
I just want get a connection automate.
Who can give me a simple example, please.
Thanks.
I found solution.
Let's myUserInfo class implements UIKeyboardInteractive interface.
And rewrited promptKeyboardInteractive method like this.
#Override
public String[] promptKeyboardInteractive(String destination, String name,
String instruction, String[] prompt,
boolean[] echo)
{
System.out.println("#####promptKeyboardInteractive#####");
System.out.println("destination: " + destination);
System.out.println("name: " + name);
System.out.println("instruction: " + instruction);
System.out.println("prompt.length: " + prompt.length);
System.out.println("prompt[0]: " + prompt[0]);
System.out.println("echo[0]: " + echo[0]);
String[] response=new String[prompt.length];
response[0] = passwd;
return response;
}
It's works. I can get a connection from the ssh server.

How to connent to Oracle database with SSH in IntelliJ IDEA

I'm trying to configure the data source using SSH to access the Database from IntelliJ off-campus. The configuration is as shown in the screenshots, and I got
[08006][17002] IO Error: Got minus one from a read call, connect lapse 30003 ms., Authentication lapse 0 ms. oracle.net.ns.NetException: Got minus one from a read call.
In fact, I've succeeded to connect to the DB with the loginProxy() and loginDB() in a Java program. From running the code, I knew that the jdbcPort should be dynamic, and I assume that's also what should be filled in the "Port" blank in the "General" tab in "Data Source and Drivers" configuration window.
So here comes the problem, how can I configure it if the Port to be filled in is DYNAMIC? Or did I get anything wrong so that actually there should be another approach?
An additional question: String URL = "jdbc:oracle:thin:#" + jdbcHost + ":" + jdbcPort + "/" + database; What URL format is used here? It doesn't look like SID, Service Name, or TNS, but it does work... and it's funny that when I substitute the "/" with ":", which matches the SID format, it doesn't work anymore...
/**
* Login the proxy. Do not change this function.
*
* #return boolean
*/
public boolean loginProxy() {
if (getYESorNO("Using ssh tunnel or not?")) { // if using ssh tunnel
String[] namePwd = getUsernamePassword("Login cs lab computer");
String sshUser = namePwd[0];
String sshPwd = namePwd[1];
try {
proxySession = new JSch().getSession(sshUser, proxyHost, proxyPort);
proxySession.setPassword(sshPwd);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
proxySession.setConfig(config);
proxySession.connect();
proxySession.setPortForwardingL(forwardHost, 0, databaseHost, databasePort);
forwardPort = Integer.parseInt(proxySession.getPortForwardingL()[0].split(":")[0]);
// 👆 forwardPort is set here, seems to be dynamic...
} catch (JSchException e) {
e.printStackTrace();
return false;
}
jdbcHost = forwardHost; // 👈 this is used in case of SSH connection, which is "localhost"
jdbcPort = forwardPort; // 👈 this is used in case of SSH connection
} else {
jdbcHost = databaseHost;
jdbcPort = databasePort;
}
return true;
}
/**
* Login the oracle system. Change this function under instruction.
*
* #return boolean
*/
public boolean loginDB() {
String username = "myDBUsername";
String password = "myDBPassword";
/* Do not change the code below */
String URL = "jdbc:oracle:thin:#" + jdbcHost + ":" + jdbcPort + "/" + database;
try {
System.out.println("Logging " + URL + " ...");
conn = DriverManager.getConnection(URL, username, password);
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
On general tab you need to specify real db server hostname and port, not localhost. With configured SSH tunnel on next tab all the things for connection will be done automatically.

Jenkins pipeline get JPPF node connected

I am working in a project using Jenkins and JPPF.
How do I get which node is connected to JPPF server? If possible, please give me the guideline detail.
Thanks,
Disclaimer: JPPF developer here.
You can monitor the nodes connected to a JPPF server using the JMX-based server management APIs. There are many things you can monitor, and a lot of different information you can obtain from the server and the nodes. Hopefully, the following example will give you a good starting point:
// connect using a JMX remote connection wrapper
try (JMXDriverConnectionWrapper serverJmx = new JMXDriverConnectionWrapper("jppf_server_host", 11111)) {
serverJmx.connectAndWait(5_000L);
if (serverJmx.isConnected()) {
// get summary information on all the connected nodes
Collection<JPPFManagementInfo> nodeInfos = serverJmx.nodesInformation();
System.out.println("there are " + nodeInfos.size() + " connected nodes:");
for (JPPFManagementInfo info: nodeInfos) {
System.out.println("node uuid: " + info.getUuid() + ", host is " + info.getHost());
}
// get detailed information on the nodes
// the node forwarder will send the same request to all selected nodes
// and group the results in a map where each key is a node uuid
JPPFNodeForwardingMBean forwarder = serverJmx.getNodeForwarder();
Map<String, Object> responses = forwarder.systemInformation(NodeSelector.ALL_NODES);
for (Map.Entry<String, Object> response: responses.entrySet()) {
String nodeUuid = response.getKey();
if (response.getValue() instanceof Exception) {
System.out.println("node with uuid = " + nodeUuid + " raised an exception:");
((Exception) response.getValue()).printStackTrace(System.out);
} else {
JPPFSystemInformation systemInfo = (JPPFSystemInformation) response.getValue();
System.out.println("system properties for node uuid " + nodeUuid + " :");
System.out.println(systemInfo.getSystem());
}
}
} else {
System.out.println("could not connect to jppf_server_host:11111");
}
} catch (Exception e) {
e.printStackTrace();
}
Note that the web and standalone administration consoles, which are built on top of the same management APIs, will also provide this information.

How to take mysql database backup by using java? [duplicate]

This question already has answers here:
backup mysql database java code
(3 answers)
Closed 9 years ago.
I am trying to take mysql database backup by using following code but I am getting exception like below when I run the program. Plz can anyone plz help out to solve this problem.
Java Code:
String path = "D:/databasbac.sql";
String username = "root";
String password = "";
String dbname = "ranjith";
String executeCmd = "<Path to MySQL>/bin/mysqldump -u " + username + " -p" + password + " --add-drop-database -B " + dbname + " -r " + path;
Process runtimeProcess;
try {
// System.out.println(executeCmd);//this out put works in mysql shell
runtimeProcess = Runtime.getRuntime().exec(new String[] { "cmd.exe", "/c", executeCmd });
// runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
System.out.println("Backup created successfully");
} else {
System.out.println("Could not create the backup");
}
} catch (Exception ex) {
ex.printStackTrace();
}
There are at least two issues:
Provide a full path to mysqldump.exe (e.g. C:\Program Files\MySQL\bin\mysqldump.exe)
-p parameter without a password value forces mysqldump to prompt for it. And you don't want it since you running it in a batch mode. Therefore either provide a password -p"your password" or better (and more secure) use an option file to avoid giving the password on the command line. Read more on this End-User Guidelines for Password Security

Categories