Sunteți pe pagina 1din 4

FAQs Search Recent Topics Flagged Topics Hot Topics Best Topics Register / Login

Win a copy of The Java Performance Companion this week in the Performance forum!

Post Reply Bookmark Topic Watch Topic New Topic

programming forums Forum: Other JSE/JEE APIs

Java
How to connect to Linux using Java code?

Anam Ghouri posted 4 years ago


Java JSRs Greenhorn
Posts: 2 Hi,

Mobile
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:
Certification

1 import java.io.*; ?
Databases 2 import java.net.Socket;
3
4 public class RunCommand {
5 public static void main(String args[]) {
Caching 6 String s = null;
7 try {
8 // run the Unix "grep" command
Books 9
10 Socket s1=new Socket("ip address",port);
11 PrintWriter wr=new PrintWriter(new
12 OutputStreamWriter(s1.getOutputStream()),true);
Engineering
13 wr.println("Hi Server...");
14 wr.flush();
15
Languages 16 BufferedReader br=new BufferedReader(new InputStreamReader(s1.getInputStrea
17
18 System.out.println(br.readLine());
19
Frameworks
20 Process p = Runtime.getRuntime().exec("grep info filepath");
21
22 BufferedReader stdInput = new BufferedReader(new

23 InputStreamReader(p.getInputStream()));
Products 24
25
26 BufferedReader stdError = new BufferedReader(new
This Site 27 InputStreamReader(p.getErrorStream()));
28
29 // read the output from the command
30
Careers 31 System.out.println("Here is the standard output of the command:\n"
32 while ((s = stdInput.readLine()) != null) {
33 System.out.println(s);
Other 34 }
35
36 // read any errors from the attempted command
37
all forums 38 System.out.println("Here is the standard error of the command (if any):\n"
39 while ((s = stdError.readLine()) != null) {
40 System.out.println(s);
41 }
42
43 System.exit(0);
44
45 }
46
47 catch (IOException e) {
48 System.out.println("exception happened - here's what I know: "
49 e.printStackTrace();
50 System.exit(-1);
51 }
52
53 }
54
55 }
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.

1 String os = System.getProperty("os.name"); ?
2
3 if ( os != null && os.startsWith("Windows"))
4 {
5 System.out.println ("I am windows");
6 }
7 else{
8 System.out.println ("I am Linux");
9
10
11 }

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 posted 4 years ago 2


Bartender
Posts: 2854 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
46 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 posted 4 years ago


Greenhorn
Posts: 2 Here is the code for someone who needs it:

1 import com.jcraft.jsch.*; ?
2 import java.io.*;
3
4 public class Exec{
5 public static void main(String[] arg){
6 try{
7 JSch jsch=new JSch();
8
9 String host=null;
10 if(arg.length>0){

11 host=arg[0];
12 }
13 else{
14 host="username@ipaddress"; // enter username and ipaddress for machine you need t
15 }
16 String user=host.substring(0, host.indexOf('@'));
17 host=host.substring(host.indexOf('@')+1);
18
19 Session session=jsch.getSession(user, host, 22);
20
21 // username and password will be given via UserInfo interface.
22 UserInfo ui=new MyUserInfo();
23 session.setUserInfo(ui);
24 session.connect();
25
26 String command= "grep 'INFO' filepath"; // enter any command you need to execute
27
28 Channel channel=session.openChannel("exec");
29 ((ChannelExec)channel).setCommand(command);
30
31
32 channel.setInputStream(null);
33
34 ((ChannelExec)channel).setErrStream(System.err);
35
36 InputStream in=channel.getInputStream();
37
38 channel.connect();
39
40 byte[] tmp=new byte[1024];
41 while(true){
42 while(in.available()>0){
43 int i=in.read(tmp, 0, 1024);
44 if(i<0)break;
45 System.out.print(new String(tmp, 0, i));
46 }
47 if(channel.isClosed()){
48 System.out.println("exit-status: "+channel.getExitStatus());
49 break;
50 }
51 try{Thread.sleep(1000);}catch(Exception ee){}
52 }
53 channel.disconnect();
54 session.disconnect();
55 }
56 catch(Exception e){
57 System.out.println(e);
58 }
59 }
60
61 public static class MyUserInfo implements UserInfo{
62 public String getPassword(){ return passwd; }
63 public boolean promptYesNo(String str){
64 str = "Yes";
65 return true;}
66
67 String passwd;
68
69 public String getPassphrase(){ return null; }
70 public boolean promptPassphrase(String message){ return true; }
71 public boolean promptPassword(String message){
72 passwd="password"; // enter the password for the machine you want to connect.
73 return true;
74 }
75 public void showMessage(String message){
76
77 }
78
79 }
80 }

Post Reply Bookmark Topic Watch Topic New Topic

Similar Threads

Pesky Runtime method

Unix With Java....


executing linux commands through java socket

Compile and create instance of a new java program from existing java
program
Runtime.getRuntime( ).exec( command ); Win vs Unix

All times above are in your local time zone & format. The current ranch time (not your local time) is Jul 29, 2016 11:09:50.All times above are in your local time zone & format. The current
ranch time (not your local time) is Jul 29, 2016 11:09:50.
Contact Us | advertise | mobile view | Powered by JForum | Copyright 1998-2016 Paul Wheaton

S-ar putea să vă placă și