从 Java 运行 Unix 命令的库
问题描述:
我正在寻找可用于从我的 Java 代码发送 Unix 命令的库.我已经尝试过 Expect4J 和 Gaynmed,但是找不到很好的文档.我的要求包括:
I am looking for libraries that I can use to send Unix commands from my Java code. I have already tried Expect4J and Gaynmed, but could not find good documentation with them. My requirements include:
- 运行多个命令.
- 捕获上一个命令的输出.
- 根据上一条命令的输出采取一些行动/运行不同的命令.
任何指针将不胜感激.
答
看你提到的库的名称,你似乎想使用 ssh 在远程服务器上运行命令.
查看http://code.google.com/p/sshxcute/
代码很简单
// Initialize a ConnBean object, parameter list is ip, username, password
ConnBean cb = new ConnBean("ip ", "username","password");
// Put the ConnBean instance as parameter for SSHExec static method getInstance(ConnBean) to retrieve a singleton SSHExec instance
ssh = SSHExec.getInstance(cb);
// Connect to server
ssh.connect();
CustomTask sampleTask = new ExecCommand("echo 123");
ssh.exec(sampleTask);
获取输出也很容易.只需检查我提供的链接.
Getting the output is easy too. Just check the link I provided.
Result res = ssh.exec(task);
if (res.isSuccess) {
System.out.println("Return code: " + res.rc);
System.out.println("sysout: " + res.sysout);
} else {
System.out.println("Return code: " + res.rc);
System.out.println("error message: " + res.error_msg);
}