How to run perl script in remote machine from java application?
Hi I am working in a java application. I need to execute a perl script(linux) which is in remote machine in java application from local machine(windows). I need to do this process automatically that is without manual intereption. No开发者_JAVA技巧w I will explain the process clearly, at present to run the perl script,I just open the putty window, connect to the remote machine and execute the perl script.
Now I want to do above explained process automatically by clicking a button. So when I click a button, it should call a function which connects to the remote machine and then executes the perl script.Please help me to solve this. I need this code in java as soon as possible.
You can use the same procedure as your manual one, by using an ssh library you can create secured connection to your server and execute the script that you want.
This question has listed some java ssh library that you can use.
Import Jcraft jar and run the below code:
package package1;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class ConnExec
{
public void connExec()
{
String host="devHostIP.sName.dev";
String user="UN";
String password="PWD";
String commandStr = "ls /local/dev/folder/inbound";
String line;
try
{
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Session session=jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
System.out.println("Connected to the server.....\n");
Channel channel=session.openChannel("exec");
channel.setInputStream(null);
((ChannelExec)channel).setCommand(commandStr);
InputStream in=channel.getInputStream();
channel.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
while ((line = reader.readLine()) != null)
{
System.out.println(line.toString());
}
channel.disconnect();
session.disconnect();
System.out.println("Terminated.....\n");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
精彩评论