Ganymed wont connect to windows in JAVA - java

I'm using Ganymed to run OS commands from JAVA. In Linux everything works like a charm. The problem is with Windows. I get the error: There was a problem while connecting to [IP]:[port]. I've tried to connect through localhost/router ip/internet ip and port 22/1023 and I've opened the ports on windows firewall and on the router as well.
I'm guessing the problem is that there isnt anything that listen the port like ssh in Linux. Am I right?
what do I need to do to fix that?
BTW I've looked on JSCH lib but Ganymed is much more simpler
Here's my sample code:
public class Test {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String hostname = "192.168.xxx.xxx", username = "xxx", password = "xxx";
int port = 1023;
try {
Connection conn = new Connection(hostname,port);
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (isAuthenticated == false) {
throw new IOException("Authentication failed.");
}
Session sess = conn.openSession();
sess.execCommand("ver");
System.out.println("Here is some information about the remote host:");
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while (true) {
String line = br.readLine();
if (line == null) {
break;
}
System.out.println(line);
}
System.out.println("ExitCode: " + sess.getExitStatus());
sess.close();
conn.close();
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(2);
}
}
}

You should install open ssh on windows to keep the ssh server running, which would act as a listener interface for inbound connections

Related

Java HTTP Php Server

I have a Java App that creates a local HTTP Webserver on Port 8080. Is there any possible Way how I can use/ install Php on it? I searched on google about this but couldnt find any help..... Any Help is appreciated!
My Code so far:
package minet;
import java.util.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;
public class main {
private static ServerSocket serverSocket;
public static void main(String[] args) throws IOException {
JFrame ip = new JFrame();
JTextField field = new JTextField();
field.setText("http://" + getIP() + ":8080");
field.setEditable(false);
field.setBounds(10, 10, 380, 110);
ip.add(field);
JButton shutdown = new JButton("Shutdown Minet");
shutdown.setBounds(30, 120, 340, 50);
ip.add(shutdown);
ip.setLocationRelativeTo(null);
ip.setSize(400, 200);
ip.setLayout(null);
ip.setVisible(true);
shutdown.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Shutting down Minet...");
field.setText("Shutting down Minet...");
setTimeout(() -> System.exit(0), 1000);
}
});
serverSocket = new ServerSocket(8080); // Start, listen on port 8080
while (true) {
try {
Socket s = serverSocket.accept(); // Wait for a client to connect
new ClientHandler(s); // Handle the client in a separate thread
} catch (Exception x) {
System.out.println(x);
}
}
}
public static void setTimeout(Runnable runnable, int delay) {
new Thread(() -> {
try {
Thread.sleep(delay);
runnable.run();
} catch (Exception e) {
System.err.println(e);
}
}).start();
}
private static String getIP() {
// This try will give the Public IP Address of the Host.
try {
URL url = new URL("http://automation.whatismyip.com/n09230945.asp");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String ipAddress = new String();
ipAddress = (in.readLine()).trim();
/*
* IF not connected to internet, then the above code will return one empty
* String, we can check it's length and if length is not greater than zero, then
* we can go for LAN IP or Local IP or PRIVATE IP
*/
if (!(ipAddress.length() > 0)) {
try {
InetAddress ip = InetAddress.getLocalHost();
System.out.println((ip.getHostAddress()).trim());
return ((ip.getHostAddress()).trim());
} catch (Exception ex) {
return "ERROR";
}
}
System.out.println("IP Address is : " + ipAddress);
return (ipAddress);
} catch (Exception e) {
// This try will give the Private IP of the Host.
try {
InetAddress ip = InetAddress.getLocalHost();
System.out.println((ip.getHostAddress()).trim());
return ((ip.getHostAddress()).trim());
} catch (Exception ex) {
return "ERROR";
}
}
}
}
// A ClientHandler reads an HTTP request and responds
class ClientHandler extends Thread {
private Socket socket; // The accepted socket from the Webserver
// Start the thread in the constructor
public ClientHandler(Socket s) {
socket = s;
start();
}
// Read the HTTP request, respond, and close the connection
public void run() {
try {
// Open connections to the socket
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream out = new PrintStream(new BufferedOutputStream(socket.getOutputStream()));
// Read filename from first input line "GET /filename.html ..."
// or if not in this format, treat as a file not found.
String s = in.readLine();
System.out.println(s); // Log the request
// Attempt to serve the file. Catch FileNotFoundException and
// return an HTTP error "404 Not Found". Treat invalid requests
// the same way.
String filename = "";
StringTokenizer st = new StringTokenizer(s);
try {
// Parse the filename from the GET command
if (st.hasMoreElements() && st.nextToken().equalsIgnoreCase("GET") && st.hasMoreElements())
filename = st.nextToken();
else
throw new FileNotFoundException(); // Bad request
// Append trailing "/" with "index.html"
if (filename.endsWith("/"))
filename += "index.html";
// Remove leading / from filename
while (filename.indexOf("/") == 0)
filename = filename.substring(1);
// Replace "/" with "\" in path for PC-based servers
filename = filename.replace('/', File.separator.charAt(0));
// Check for illegal characters to prevent access to superdirectories
if (filename.indexOf("..") >= 0 || filename.indexOf(':') >= 0 || filename.indexOf('|') >= 0)
throw new FileNotFoundException();
// If a directory is requested and the trailing / is missing,
// send the client an HTTP request to append it. (This is
// necessary for relative links to work correctly in the client).
if (new File(filename).isDirectory()) {
filename = filename.replace('\\', '/');
out.print("HTTP/1.0 301 Moved Permanently\r\n" + "Location: /" + filename + "/\r\n\r\n");
out.close();
return;
}
// Open the file (may throw FileNotFoundException)
InputStream f = new FileInputStream(filename);
// Determine the MIME type and print HTTP header
String mimeType = "text/plain";
if (filename.endsWith(".html") || filename.endsWith(".htm"))
mimeType = "text/html";
else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg"))
mimeType = "image/jpeg";
else if (filename.endsWith(".gif"))
mimeType = "image/gif";
else if (filename.endsWith(".class"))
mimeType = "application/octet-stream";
out.print("HTTP/1.0 200 OK\r\n" + "Content-type: " + mimeType + "\r\n\r\n");
// Send file contents to client, then close the connection
byte[] a = new byte[4096];
int n;
while ((n = f.read(a)) > 0)
out.write(a, 0, n);
out.close();
} catch (FileNotFoundException x) {
out.println("HTTP/1.0 404 Not Found\r\n" + "Content-type: text/html\r\n\r\n"
+ "<html><head></head><body>" + filename + " not found</body></html>\n");
out.close();
}
} catch (IOException x) {
System.out.println(x);
}
}
}
(Stackoverflow doesnt likes that many code... Thats why i have this external Link...)
From your question I understood that you used to use PHP as a web programing language. And you want to make an application in Java that shows some pages from PHP Web Server.
For this I think you need to include Built-in web server in your application. You just need to download it, uncompress it in your application path or wherever you want. You can find an INSTALL file in the directory. Install it as it shown, then start web server by:
$ cd path/to/built-in/php/web/server
$ php -S localhost:8000
Executing cmd commands is shown in this post. You may change port number as you want.
Another variant is you will need to include compressed Apache and PHP in your application installation package, then uncompress it, and edit config files programmatically, and after your application will be installed on some computer.
For showing pages from the PHP Web Server you just need to use WebView. An example of how to use it in Swing is shown here or you may use JavaFX directly without Swing if you want, because WebView is a part of JavaFX.
I cannot determine the exact problem you are facing. But, by the question, it seems that you wan to install a PHP server alongside your JAVA server.
This can be done easily, just select a different port number, while installing PHP. Any PHP server selects port 80 by default, so this in itself solves your problem. Just install any PHP server, it can be accessed via http://localhost, whereas your java server can be accessed via http://localhost:8080.
There has been a similar discussion here. Please check it out.

Java preventing other network connections

I have a java application that does two things with an internet connection. The first is a simple port 80 connect to send some data:
try {
url = new URL(req);
URLConnection conn = url.openConnection();
conn.setConnectTimeout(tOut);
conn.setConnectTimeout(1000);
conn.setRequestProperty("Connection", "close");
conn.setReadTimeout(urlTimeout);
// open the stream and put it into BufferedReader
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
while ((inputLine = br.readLine()) != null) {
Line = Line + inputLine ;
}
} catch (MalformedURLException e) {
//e.printStackTrace();
} catch (IOException e) {
//e.printStackTrace();
}
The second is a ssh connection that looks for information coming from the server. The connection part is:
con = SshConnector.createInstance();
transport = new SocketTransport(hostname, port);
try {
ssh = con.connect(transport, username);
} catch (Exception es) {
}
PasswordAuthentication pwd = new PasswordAuthentication();
do {
pwd.setPassword("password");
} while (ssh.authenticate(pwd) != SshAuthentication.COMPLETE
&& ssh.isConnected());
Then I loop looking for input from the server.
I have one user that is on a Verizon Jetpack. When my application is running the application runs slow, he cannot connect his VPN to his office, do a browser speed test, etc. Close my application and the VPN and browser works fine.
I do not have that problem and many others running my application are fine. Is there something I am overlooking or can change to keep from apparently shutting down his jetpack?
Tnx

Telnet Client connection refused - JAVA

I'm trying create a telnet client(apache) connection to global IP address.
If I use something like below,I can could establish the connection.
private TelnetClient telnet = new TelnetClient();
telnet.connect("172.xx.xxx.xx", port);
However writing it something like below,I get "connection refused error".
private TelnetClient telnet = new TelnetClient();
String host = "172.xx.xxx.xx";
telnet.connect(host, port);
Any suggestion?(i could not find same error in forums, also I am new at asking questions :) )
here is my full code;
public void connectionCreater(String host, int port,String uID,String pass,
String account, String password) {
try {
//telnet.connect("172.xx.xxx.xx", port); this is works.
telnet.connect(host, port);
out = new PrintWriter(telnet.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
telnet.getInputStream()));
if (readUntilThenExecute("login: ", uID + "\r")) {
if (readUntilThenExecute("Password: ", pass + "\r")) {
if (readUntilThenExecute("Enter User Name", account)) {
if (readUntilThenExecute("Enter Password", password)) {
//to do stuff }
}
}
}
} catch (IOException e) {
out.close();
try {
in.close();
} catch (IOException y) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public boolean readUntilThenExecute(String word, String command) {
try {
String result1 = "";
char[] incoming = new char[2048];
boolean check = true;
while (check) {
int lenght = in.read(incoming);
result1 = String.copyValueOf(incoming, 0, lenght);
System.out.println(result1);
if (result1.contains(word)) {
out.println(command);
check = false;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
1.Install telnet use this command in terminal(Applications/Accessories/Terminal):
sudo apt-get install xinetd telnetd
2.Edit /etc/inetd.conf using your favourite file editor with root permission,add this line:
telnet stream tcp nowait telnetd /usr/sbin/tcpd /usr/sbin/in.telnetd
3.Edit /etc/xinetd.conf,make its content look like following:
# Simple configuration file for xinetd
#
# Some defaults, and include /etc/xinetd.d/
defaults
{
# Please note that you need a log_type line to be able to use log_on_success
# and log_on_failure. The default is the following :
# log_type = SYSLOG daemon info
instances = 60
log_type = SYSLOG authpriv
log_on_success = HOST PID
log_on_failure = HOST
cps = 25 30
}
4.You can change telnet port number by edit /etc/services with this line:
telnet 23/tcp
5.If you’re not satisfied with default configuration.Edit etc/xinetd.d/telnet, add following:
# default: on
# description: The telnet server serves telnet sessions; it uses
# unencrypted username/password pairs for authentication.
service telnet
{
disable = no
flags = REUSE
socket_type = stream
wait = no
user = root
server = /usr/sbin/in.telnetd
log_on_failure += USERID
}
add these lines as you like:
only_from = 192.168.120.0/24 #Only users in 192.168.120.0 can access to
only_from = .bob.com #allow access from bob.com
no_access = 192.168.120.{101,105} #not allow access from the two IP.
access_times = 8:00-9:00 20:00-21:00 #allow access in the two times
......
6.Use this command to start telnet server:
sudo /etc/init.d/xinetd start

Testing Socket Program

So I wrote a simple Socket program that send message from Client to Server program and wanted to know what is the proper procedure to go about testing this? Both my Client and Server machines are running on Ubuntu 12.04 and I'm remote connecting to both of them.
For my Client code when I instantiate the client socket (testSocket) do I use its IP Address and Port number or Servers IP Address and Port number?
Here is the Code for Client:
public static void main(String[] args) throws UnknownHostException, IOException
{
Socket testSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
try
{
testSocket = new Socket("192.168.0.104", 5932);
os = new DataOutputStream(testSocket.getOutputStream());
is = new DataInputStream(testSocket.getInputStream());
}
catch (UnknownHostException e)
{
System.err.println("Couldn't find Host");
}
catch (IOException e)
{
System.err.println("Couldn't get I/O connection");
}
if (testSocket != null && os != null && is != null)
{
try
{
os.writeBytes("Hello Server!\n");
os.close();
is.close();
testSocket.close();
}
catch (UnknownHostException e)
{
System.err.println("Host not found");
}
catch (IOException e)
{
System.err.println("I/O Error");
}
}
}
Here is the code for Server:
public static void main(String[] args)
{
String line = new String() ;
try
{
ServerSocket echoServer = new ServerSocket(5932);
Socket clientSocket = echoServer.accept();
DataInputStream is = new DataInputStream(clientSocket.getInputStream());
PrintStream os = new PrintStream(clientSocket.getOutputStream());
while (true)
{
line = is.readLine();
os.println(line);
}
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
I'm new to Sockets and not sure what I'm supposed be seeing. I compiled both programs in terminal fine but not sure which one should I be running first or do they need to be started simultaneously?
Thanks
Your server is running in a infinite loop. Avoid that.
You have to restart your computer.
while (true)
{
line = is.readLine();
os.println(line);
}
try
while (!line.equals("Hello Server!"))
{
line = is.readLine();
os.println(line);
}
Run the server first. echoServer.accept(); waits for a connection. When it gets the first connection,
http://docs.oracle.com/javase/tutorial/networking/sockets/ this is a short java tutorial on how to work with sockets and also you can learn how to make a server that would accept multiple connections at a time. This tutorial explains you always need to start the server first, which is only logical. You should use threads to manage connections and then close them so that you use resources efficiently

Java telnet server

Does anyone know of a simple telnet server?
I want to embed in my application and set my own commands
something simple not complex .
Try this one,
http://code.google.com/p/telnetd-x/
A telnetd alone is useless. You have to connect it to a shell. We use jacl and jyson as shell.
I have written a simple Telnet server in Java: TelnetStdioRedirector
I did as below
public static void main(String[] args) {
String url = "hostname";
int port = 8080;
try (Socket pingSocket = new Socket(url, port)) {
try (PrintWriter out = new PrintWriter(pingSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(pingSocket.getInputStream()));) {
out.println("ping");
System.out.println("Telnet Success: " + in.readLine());
}
} catch (IOException e) {
System.out.println("Telnet Fail: " + e.getMessage());
}
}

Categories