Telnet Client connection refused - JAVA - 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

Related

FTP using Apache commons not working - Error: 550 Dataset not found (FTPid that i am using is getting appended to filename)

I am trying to ftp the file from Linux VM to an AS400 server. I was able to login to server in passive mode but when trying to use the STOR command to upload the file getting below error:
STOR XX.YY600040.XXXZZZXXX
**550 Dataset not found, DSN=FTPID.XX.YY600040.XXXZZZXXX**
Not sure why the ftpid that i am using is getting prefixed to the filename. Is there any way to avoid it?
Below is the sample code that i am using:
private static String sendFTPFile(String fileName) throws Exception {
StringBuffer ftpMessage = new StringBuffer();
if (SHOW_DEBUG) ftpMessage.append("<ul>");
FTPClient ftp = null;
try {
String server = "****";
String username = "****";
String password = "XXXXX";
String hostDir = "";
String localFileName = fileName;
String localFilePath = "***/**/*";
boolean binaryTransfer = false, error = false;
FTPClient ftp = new FTPClient();
ftp.addProtocolCommandListener(new PrintCommandListener(
new PrintWriter(System.out)));
int reply;
ftp.connect(server)
// After connection attempt, you should check the reply code to verify
// success.
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply))
{
ftp.disconnect();
error = true;
}
if(!error) {
if (!ftp.login(username, password))
{
ftp.logout();
error = true;
}
if(!error) {
if (binaryTransfer)
ftp.setFileType(FTP.BINARY_FILE_TYPE);
// Use passive mode as default
ftp.enterLocalPassiveMode();
InputStream input;
input = new FileInputStream(localFilePath+localFileName);
boolean ftpSuccess = ftp.storeFile(hostDir+localFileName, input);
input.close();
if (!ftpSuccess) {
throw new Exception("File ftp error");
}else {
if (SHOW_DEBUG) ftpMessage.append("<li>isFtpSuccess()...success").append("</li>");
}
ftp.logout();
if (SHOW_DEBUG) ftpMessage.append("<li>ftp.logout()...success").append("</li>");
}
}
}
catch (Exception ex) {
ex.printStackTrace();
System.out.println("Exception occur while transfering file using ftp"+ ex.toString());
throw new Exception(ftpMessage.toString(), ex);
}
finally {
if (ftp!=null && ftp.isConnected())
{
try
{
ftp.disconnect();
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("Exception occur while transfering file using ftp"+ e.toString());
throw new Exception(ftpMessage.toString(), e);
}
}
if (SHOW_DEBUG) ftpMessage.append("</ul>");
}
return ftpMessage.toString();
}
I did some more debugging on doing ftp from linux to as400. And when doing pwd after logging to ftp server its giving message as:
ftp> pwd
257 "'FTPID.'" is current prefix
And thinking how to remove that prefix so i ran the below command got output as no prefix defined:
ftp> cd ..
200 "" no prefix defined
And after that when i uploaded the file using put command it was uploaded successfully. So i did some research on how to go back one directory using Apache commons.net api's that i am using and found the CDUP method.
When i ran the FTPClient.cdup() method before uploading the file. I was able to successfully FTP the file from java code as well.
ftp.cdup();
input = new FileInputStream(localFilePath+localFileName);
boolean ftpSuccess = ftp.storeFile(hostDir+localFileName, input);

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.

Not Connect modbus TCP

I have a problem with the connection through ethernet modbus tcp.
I insert in to AndroidManifest the permission:
And i create task or connecting and reading Modbus.
I use jamod library.
When I start the application gives me a connection failed error.
This my code that i use:
class Task implements Runnable {
#
Override
public void run() {
try {
ReadMultipleRegistersResponse result = null;
//Read And Write Register Sample
int port = Modbus.DEFAULT_PORT;
String refe = "4000"; //HEX Address
int ref = Integer.parseInt(refe, 16); //Hex to int
int count = 98; //the number Address to read
int SlaveAddr = 1;
String astr = "192.168.0.18"; //Modbus Device
InetAddress addr = InetAddress.getByName(astr);
TCPMasterConnection con = new TCPMasterConnection(addr);
ModbusTCPTransaction trans = null; //the transaction
//1.Prepare the request
/************************************/
ReadMultipleRegistersRequest Rreq = new ReadMultipleRegistersRequest(ref, count);
ReadMultipleRegistersResponse Rres = new ReadMultipleRegistersResponse();
Rreq.setUnitID(SlaveAddr); //set Slave Address
Rres.setUnitID(SlaveAddr); //set Slave Address
//2. Open the connection
con.setPort(port);
con.connect();
con.setTimeout(2500);
//3. Start Transaction
trans = new ModbusTCPTransaction(con);
trans.setRetries(5);
trans.setReconnecting(true);
trans.setRequest(Rreq);
trans.execute();
/*Print Response*/
Rres = (ReadMultipleRegistersResponse) trans.getResponse();
} catch (ModbusSlaveException me) {
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (java.lang.Exception e) {;
e.printStackTrace();
}
}
}
Where am I doing wrong ?
Follow the steps
Check your slave is working
Check your device of slave that have the same network with the master
Check your port setting of security (default 502)

Ganymed wont connect to windows in 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

Writing a simple application to inject messages onto a queue

I'm trying to write a simple Java program to inject an MQ message onto a queue. I'm very inexperienced with writing to MQ queues using Java and have a couple of questions.
Can I connect to the unix queue on the unix box from my windows machine?
When I try to run the application I get a ....
java.lang.UnsatisfiedLinkError: no mqjbnd05 in java.library.path
From the sounds of what I could find in google I am missing some sort of resource. I'm thinking I'm getting this error possibly bc I'm not allowed to connect to the queue from windows?
Any good examples of how to achieve what I'm doing or help would be appreciated.
public class MQInject {
private MQQueueManager _queueManager = null;
private Hashtable params = null;
public int port = 1414;
public static final String hostname = "UQMYPOSIS1";
public static final String channel = "MQTX1012.MQTX1013";
public static final String qManager = "MQTX1013";
public static final String outputQName = "IIS.TLOG.5";
public MQInject(){
super();
}
public void init(){
//Set MQ connection credentials to MQ Envorinment.
MQEnvironment.hostname = hostname;
MQEnvironment.channel = channel;
MQEnvironment.port = port;
//MQEnvironment.userID = "";
//QEnvironment.password = password;
//set transport properties.
MQEnvironment.properties.put(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_CLIENT);
try {
//initialize MQ manager.
_queueManager = new MQQueueManager(qManager);
} catch (MQException e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
MQInject write = new MQInject();
try
{
write.selectQMgr();
write.write();
}
catch (IllegalArgumentException e)
{
System.out.println("Usage: java MQWrite <-h host> <-p port> <-c channel> <-m QueueManagerName> <-q QueueName>");
System.exit(1);
}
catch (MQException e)
{
System.out.println(e);
System.exit(1);
}
}
private void selectQMgr() throws MQException
{
_queueManager = new MQQueueManager(qManager);
}
private void write() throws MQException{
String line;
int lineNum=0;
int openOptions = MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING;
try {
MQQueue queue = _queueManager.accessQueue( outputQName,
openOptions,
null, // default q manager
null, // no dynamic q name
null ); // no alternate user id
DataInputStream input = new DataInputStream(System.in);
System.out.println("MQWrite v1.0 connected");
System.out.println("and ready for input, terminate with ^Z\n\n");
// Define a simple MQ message, and write some text in UTF format..
MQMessage sendmsg = new MQMessage();
sendmsg.format = MQC.MQFMT_STRING;
sendmsg.feedback = MQC.MQFB_NONE;
sendmsg.messageType = MQC.MQMT_DATAGRAM;
sendmsg.replyToQueueName = "ROGER.QUEUE";
sendmsg.replyToQueueManagerName = qManager;
MQPutMessageOptions pmo = new MQPutMessageOptions(); // accept the defaults, same
// as MQPMO_DEFAULT constant
while ((line = input.readLine()) != null){
sendmsg.clearMessage();
sendmsg.messageId = MQC.MQMI_NONE;
sendmsg.correlationId = MQC.MQCI_NONE;
sendmsg.writeString(line);
// put the message on the queue
queue.put(sendmsg, pmo);
System.out.println(++lineNum + ": " + line);
}
queue.close();
_queueManager.disconnect();
}catch (com.ibm.mq.MQException mqex){
System.out.println(mqex);
}
catch (java.io.IOException ioex){
System.out.println("An MQ IO error occurred : " + ioex);
}
}
}
For your first question, yes you can have a queue manager running on a UNIX host which is accessed by a client running on a Windows host.
For your second question, the mqjbnd05 library is only used to connect to the queue manager in binding mode (i.e. when the queue manager and the program accessing the queues are on the same host) and is not part of the MQ client installation. See http://www-01.ibm.com/support/docview.wss?uid=swg21158430 for more details. Looking through your code I can see that the init() function is specifying MQC.TRANSPORT_MQSERIES_CLIENT although I cannot see that the init() function is being called. Also it might be worth checking whether mqjbnd05 is specified in the library path and if so removing it.
Whilst probably not related to the error your getting, one other thing that might be worth checking is that the channel MQTX1012.MQTX1013 is a server connection channel as opposed to a sender or receiver channel.

Categories