Java実行linux命令
2005 ワード
import java.io.InputStream; import java.util.Properties;
import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session;
public class JSCHUtil {
}
import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session;
public class JSCHUtil {
private static JSCHUtil instance;
private JSCHUtil() {
}
public static JSCHUtil getInstance() {
if (instance == null) {
instance = new JSCHUtil();
}
return instance;
}
private Session getSession(String host, int port, String ueseName)
throws Exception {
JSch jsch = new JSch();
Session session = jsch.getSession(ueseName, host, port);
return session;
}
public Session connect(String host, int port, String ueseName,
String password) throws Exception {
Session session = getSession(host, port, ueseName);
session.setPassword(password);
Properties config = new Properties();
//
config.setProperty("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
return session;
}
public void execCmd(Session session, String command)
throws Exception {
if (session == null) {
throw new RuntimeException("Session is null!");
}
ChannelExec exec = (ChannelExec) session.openChannel("exec");
InputStream in = exec.getInputStream();
byte[] b = new byte[1024];
exec.setCommand(command);
exec.connect();
while (in.read(b) > 0) {
System.out.println(new String(b));
}
exec.disconnect();
}
public void clear(Session session) {
if ((session != null) && session.isConnected()) {
session.disconnect();
session = null;
}
}
public static void main(String[] args) throws Exception {
Session session = JSCHUtil.getInstance()
.connect("192.168.0.15", 22, "xx", "@#$%123()");
String cmd = "cd /home/ym" + ";" + "/usr/tcl/bin/expect test.sh";
JSCHUtil.getInstance().execCmd(session, cmd);
}
}