java 远程shell_Java远程执行Shell命令

需要ganymed-ssh2-build210.jar

1 连接

Connection conn = new Connection(ip地址, 端口号);

conn.connect();

2认证并判断

boolean isAuthenticated = conn.authenticateWithPassword(用户名, 密码);

if (isAuthenticated == false){

System.out.println("密码错误");

throw new IOException("Authentication failed.");

}

3打开一个Session

final Session session=conn.openSession();

4上传文件(根据情况)

SCPClient client = new SCPClient(conn);

client.put(updateFileBytes, "xlsbz_server.zip", "/app/mhfx/");

5执行Shell命令(一般放线程里执行)

new Thread(new Runnable() {

public void run() {

try {

session.requestDumbPTY();                            //建立虚拟终端

session.startShell();                                         //打开一个shell

OutputStream fout = session.getStdin();          //也可以用PrintWriter out = new PrintWriter(session.getStdin());

//输入命令

fout.write(("bash xlsbz_server/bin/telnet.sh" + "\n").getBytes());

Thread.sleep(1000);

fout.write(("freeze" + "\n").getBytes());

Thread.sleep(60000);

fout.write(("quit" + "\n").getBytes());

Thread.sleep(1000);

fout.write(("bash xlsbz_server/bin/xlsbz.sh" + "\n").getBytes());

Thread.sleep(1000);

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}).start();

6关闭session和相应流

session.close();

Thread.sleep(1000);

conn.close();

Thread.sleep(1000);

补充一点:

有时候需要从远程服务器获取返回结果

final InputStream is = new StreamGobbler(session.getStdout());                      //StreamGobbler的作用是把session的标准输出包装成InputStream,用于接收目标服务器上的控制台返回结果,读取br中的内容。然后在循环中,把每一行的内容添加到StringBuffer里面。

new Thread() {

public void run() {

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

while (true) {

try {

String line = br.readLine();

if (line == null) break;

System.out.println(line);

} catch (IOException e) {

e.printStackTrace();

}

}

try {

is.close();

br.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}.start();

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值