windows下java程序jsch连接远程linux服务器执⾏shell命令      java远程连接服务的shell需要使⽤SSH的登录⽅式,可以使⽤JSch技术。JSch 是SSH2的⼀个纯Java实现。它允许你连接到⼀个sshd 服务器,使⽤端⼝转发,X11转发,⽂件传输等等。
jsch官⽹:
jsch的例⼦:
远程登录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(user, host, 22);
session.setPassword(password);
session.setConfig(config);
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).);
// Gets an InputStream for this channel. All data arriving in as messages from the remote side can be          InputStream InputStream();
OutputStream out = OutputStream();
// Execute the command
byte[] tmp=new byte[1024];
while(true){
while(in.available()>0){
int ad(tmp, 0, 1024);
if(i<0)break;
executeResultString = new String(tmp, 0, i);
//获取命令执⾏的返回值,结果是多⾏的也存在⼀个String中
}
if(channel.isClosed()){
System.out.println("exit-status: "+ExitStatus());              break;
}
shell界面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中能识别等。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。