java ssh 命令_java中的ssh(在另一台机器上运行命令)

有很多库可以做到这一点.我建议

Ganymed SSH-2,这也在

official OpenSSH website中提到.在同一个站点中,您还可以找到可用于Java的其他库.

这是使用Ganymed SSH-2通过SSH执行的ls -r命令的示例:

import ch.ethz.ssh2.Connection;

import ch.ethz.ssh2.Session;

import ch.ethz.ssh2.StreamGobbler;

[...]

public static ArrayList lsViaSSH(String hostname, String username, String password, String dir) {

ArrayList ls = new ArrayList();

try

{

Connection conn = new Connection(hostname);

conn.connect();

boolean isAuthenticated = conn.authenticateWithPassword(username, password);

if (isAuthenticated == false) {

return null;

}

Session sess = conn.openSession();

sess.execCommand("ls -r " + dir);

InputStream stdout = new StreamGobbler(sess.getStdout());

BufferedReader br = new BufferedReader(new InputStreamReader(stdout));

while (true)

{

String line = br.readLine();

if (line == null)

break;

ls.add(line);

}

sess.close();

conn.close();

}

catch (IOException e)

{

return null;

}

if(StringUtils.isEmpty(ls.get(0)))

return null;

return ls;

}

这不是通过SSH执行命令所需的唯一功能,但我希望它可能是一个很好的起点.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值