• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to connect to Linux using Java code?

 
Anam Ghouri
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I need to connect to Linux using java code from my Windows machine and execute a linux command. Following is the code I am using:



I am getting following error while executing this code:

java.io.IOException: Cannot run program "grep": CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at macys.RunCommand.main(RunCommand.java:45)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
... 5 more
exception happened - here's what I know:


I think it is not executing linux command because it is still in Windows operating system. When I include the following code in my program, i can see that is still in Windows.


Output: "I am windows"

I need to connect to Linux and execute a Linux command from Windows. How do I do it using Java code? Can somebody please help me out in this asap?
 
Tim Moores
Bartender
Posts: 2946
46
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh boy. With all due respect, I think you have quite limited understanding of network computing and remote access. Runtime.exec executes on the local machine; where else would it execute? Do you see anything in that method call that could be construed as telling it to do otherwise (if that were even possible, which it is not)?

If you want to execute commands on a remote machine, you need to open a Telnet or SSH session. Telnet has fallen out of favor since it's less secure than SSH, so the target machine may not support it; if it does, then you can use the Telnet client code that's part of the Apache Commons Net library.

If SSH is available, check out JSch; it's a Java client library for that.

Lastly, using readLine and println with sockets is bound to cause you grief. This is a good article on that issue: http://www.fenestrated.net/~macman/mirrors/Apple%20Technotes%20%28As%20of%202002%29/tn/tn1157.html
 
Anam Ghouri
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is the code for someone who needs it:

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic