700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > JSch连接不上Linux服务器 windows 下 java程序jsch连接远程linux服务器执行shell命令

JSch连接不上Linux服务器 windows 下 java程序jsch连接远程linux服务器执行shell命令

时间:2018-09-19 05:04:48

相关推荐

JSch连接不上Linux服务器 windows 下 java程序jsch连接远程linux服务器执行shell命令

java远程连接服务的shell需要使用SSH的登录方式,可以使用JSch技术。JSch 是SSH2的一个纯Java实现。它允许你连接到一个sshd 服务器,使用端口转发,X11转发,文件传输等等。

远程登录shh有两种方式:一种是账号密码登录的方式,一种是秘钥登录的方式。

这里我使用的账号密码的登录方式。

执行shell命令可以在连接中使用shell通道或exec通道都可以,以下是sehll通道和exec通道的区别。

shell 通道: 在jsch中每条命令都会开一个终端界面,如果执行多条命令需要多个shell通道,相当于是多个终端界面,这些命令之间不会相互通信。

exec 通道:在exec中可以一次执行多个命令,使用“;”或“\n”分开多个命令,这些命令之间会相互通信。如果开多个exec,虽然可以执行多条命令,但这些exec之间不会相互传递状态,就行开多个shell一样。

所以建议使用exec通道。

以下是使用exec的例子:

首先需要去官网下载exec,建议下载最新版,然后将jsch的包导入到项目中。 下面是我写的一个封装好的函数,解释都有,返回值是执行的结果,服务器的信息作为全局变量,易于修改。

final static String host="192.168.1.1"; //服务器的ip地址

final static String user="test"; //服务器的账号

final static String password="test123"; //服务器的密码

/**

* @Title: exectueShellCommand

* @Description: 执行shell命令,返回得到的结果

* @param @param command 执行的shell命令

* @param @return shell命令的返回值

*/

public static String exectueShellCommand(String command){

String executeResultString = new String();

try{

java.util.Properties config = new java.util.Properties();

config.put("StrictHostKeyChecking", "no");

JSch jsch = new JSch();

Session session=jsch.getSession(user, host, 22);

session.setPassword(password);

session.setConfig(config);

session.connect();

System.out.println("Connected");

//create the excution channel over the session

Channel channel=session.openChannel("exec");

// Set the command that you want to execute

// In our case its the remote shell script

((ChannelExec)channel).setCommand(command);

channel.setInputStream(null);

((ChannelExec)channel).setErrStream(System.err);

// Gets an InputStream for this channel. All data arriving in as messages from the remote side can be

InputStream in=channel.getInputStream();

OutputStream out = channel.getOutputStream();

// Execute the command

channel.connect();

byte[] tmp=new byte[1024];

while(true){

while(in.available()>0){

int i=in.read(tmp, 0, 1024);

if(i<0)break;

executeResultString = new String(tmp, 0, i); //获取命令执行的返回值,结果是多行的也存在一个String中

}

if(channel.isClosed()){

System.out.println("exit-status: "+channel.getExitStatus());

break;

}

try{Thread.sleep(1000);}catch(Exception ee){} //让线程执行1秒

}

channel.disconnect();

session.disconnect();

System.out.println("DONE");

}catch(Exception e){

e.printStackTrace();

}

System.out.println("return values is:" + executeResultString);

return executeResultString;

}

使用 ls -l测试,测试结果如下:

发现 total 12 也存在返回的String中了,所以 大家使用的时候需要根据自己的命令格式来最后进行整理。

使用EXEC 中我发现有些在secreCRT中可以用的命令在 exec中不能用,如果碰到这种情况,只能尝试使用期他命令了。 如 ll 在exec中能识别等。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。