java jsch使用

/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/**
 * This program enables you to connect to sshd server and get the shell prompt.
 *   $ CLASSPATH=.:../build javac Shell.java 
 *   $ CLASSPATH=.:../build java Shell
 * You will be asked username, hostname and passwd. 
 * If everything works fine, you will get the shell prompt. Output may
 * be ugly because of lacks of terminal-emulation, but you can issue commands.
 *
 */
import com.jcraft.jsch.*;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


import javax.swing.*;


public class MyShell{
public static void main(String[] args)
{

try {
JSch jSch = new JSch();
Session session = jSch.getSession("root", "192.168.199.148", 22);
session.setPassword("gzy");

session.setUserInfo(new MyUserInfo());
session.connect();

//交互式命令必须使用shell
Channel channel = session.openChannel("shell");

channel.setInputStream(null);
channel.setOutputStream(null);

/**
* out的输入方是本端,接收方是远端
* in的输入方式远端,接收方是本端
*/
InputStream in = channel.getInputStream();
OutputStream out = channel.getOutputStream();

channel.connect();

String cmdStr = "gdb\n";
out.write(cmdStr.getBytes());
// 该语句10分关键,不写,输入不会有效
out.flush();

byte[] tmp = new byte[1024];
while(true)
{
if (in.available()>0)
{
int i = in.read(tmp, 0, 1024);
if(i<0)
{
break;
}
System.out.print(new String(tmp,0, i));
}
if (channel.isClosed())
{
break;
}
Thread.sleep(100);
}

channel.disconnect();
session.disconnect();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}


    static class MyUserInfo implements UserInfo, UIKeyboardInteractive 
    {
public String getPassword() {
return null;
}


public boolean promptYesNo(String str) {
//非文件认证,返回true
return true;
}


public String getPassphrase() {
return null;
}


public boolean promptPassphrase(String message) {
return false;
}


public boolean promptPassword(String message) {
return false;
}


public void showMessage(String message) {
}


public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt,
boolean[] echo) {
return null;
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值