您的位置:首页 > 运维架构 > Linux

利用java实现可远程执行linux命令的小工具

2013-08-13 17:29 881 查看
在linux的脚本中,如果不对机器做其他的处理,不能实现在linux的机器上执行命令。为了解决这个问题,写了个小工具来解决这个问题。

后面的代码是利用java实现的可远程执行linux命令的小工具,代码中使用了jsch这个开源包。

JSch 是SSH2的一个纯Java实现。它允许你连接到一个sshd 服务器,使用端口转发,X11转发,文件传输等等。jsch的jar,可从官网下载。

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

/**
*
* 类似ssh执行命令的小工具
*
* @author walker
*
*/
public class SSH {
private String userName;
private String password;
private String host;

public SSH(String host, String userName, String password) {
this.host = host;
this.userName = userName;
this.password = password;
}

private Session getSession() {
JSch jsch = new JSch();
Session session = null;

try {
session = jsch.getSession(userName, host);
session.setPassword(password);

Properties props = new Properties();
props.put("StrictHostKeyChecking", "no");
session.setConfig(props);
session.connect();
} catch (JSchException e) {
e.printStackTrace();
}
return session;
}

public boolean exec(String[] cmds) {
StringBuffer cmdBuffer = new StringBuffer();

for (int i = 0; i < cmds.length; i++) {
if (i != 3) {
cmdBuffer.append(" ");
}
cmdBuffer.append(cmds[i]);
}
return exec(cmdBuffer.toString());
}

public boolean exec(String cmd) {
Session session = getSession();
Channel channel = null;
InputStream in = null;
try {
channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(cmd);
((ChannelExec) channel).setInputStream(null);
((ChannelExec) channel).setErrStream(System.err); // 获取执行错误的信息

in = channel.getInputStream();
channel.connect();
byte[] b = new byte[1024];
int size = -1;
while ((size = in.read()) > -1) {
System.out.print(new String(b, 0, size)); // 打印执行命令的所返回的信息
}
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭流
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
// 关闭连接
channel.disconnect();
session.disconnect();
}

return false;
}

/**
* @param args
*/
public static void main(String[] args) {
if (args.length < 4) {
System.err.println("usage:\n\t" + SSH.class.getName()
+ " <host> <usename> <password> <cmds>");
System.exit(1);
}

// 用以保存命令(可能是一串很长的命令)
StringBuffer cmdBuffer = new StringBuffer();
for (int i = 3; i < args.length; i++) {
if (i != 3) {
cmdBuffer.append(" ");
}
cmdBuffer.append(args[i]);
}

SSH ssh = new SSH(args[0], args[1], args[2]);
System.exit(ssh.exec(cmdBuffer.toString()) ? 0 : 1);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: