假如有一台知道
ip
的主机,上面放着你想执行的shell脚本,你想在windows下写这个程序,
并调试,你打算怎么做?
Maven
<dependencies>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
</dependencies>
复制到pom.xml
中,这个第三方库的官网:
http://www.jcraft.com/jsch/examples/KnownHosts.java.html
工具类
这是我写的一个小插件,里面有丰富的注释。
RemoteShellScriptor
不用修改,它是一个工具类:
package com.oneslide.www.system;
import com.jcraft.jsch.*;
import java.io.IOException;
import java.io.InputStream;
public class RemoteShellScriptExecutor {
private final Session session;
private final Channel channel;
private final static int CONNECT_TIME_OUT=30000;
private byte[] sshChannelBuffer=new byte[1024];
/**
* init some parameters
* including user,host,password to login destination host
* **/
public RemoteShellScriptExecutor(String user,String host,String password) throws JSchException {
//open session
this.session=new JSch().getSession(user,host,22);
//set password
session.setPassword(password);
/**insecure debug for skipping host authenticity checking**/
session.setConfig("StrictHostKeyChecking","no");
//connect to remote server
session.connect(RemoteShellScriptExecutor.CONNECT_TIME_OUT);
//connect to exec Channel
}
/**
* this method automatically connect to Channel at the beginning,
* and disconnect after method ends
*
* @return
* String Buffer contains the result of command issued
*
* @param
* <code>String command</code> command issued
* **/
public String issueCommand(String command) throws JSchException, IOException {
//open a channel every time a command is issued,channel is disposable
this.channel=session.openChannel("exec");
//set command issued
((ChannelExec)this.channel).setCommand(command);
InputStream inputStream=channel.getInputStream();
//connect to channel
channel.connect();
StringBuffer stringBuffer=new StringBuffer();
while(true){
while(inputStream.available()>0){
int byteRead=inputStream.read(this.sshChannelBuffer,0,1024);
stringBuffer.append(new String(this.sshChannelBuffer,0,byteRead));
if (byteRead<0){
break;
}
}
//channel closed while some byte haven't been write to StringBuffer
if (this.channel.isClosed()){
if (inputStream.available()>0){
continue;
}
System.out.println("Exit Code"+this.channel.getExitStatus());
break;
}
}
channel.disconnect();
return stringBuffer.toString();
}
public void disconnect(){
this.session.disconnect();
}
}
用法
使用上面工具类的方法是:
public class Main {
public static void main(String[] args) {
try {
RemoteShellScriptExecutor remoteShellScriptExecutor=new RemoteShellScriptExecutor("root","10.0.7.54","xxx");
// 这里写入你想要执行的shell命令,再shell命令行里写什么,这里就写什么
//初始目录是用户根目录
String result=remoteShellScriptExecutor.issueCommand("ls");
System.out.println(result);
remoteShellScriptExecutor.disconnect();
} catch (JSchException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
CMD输入ssh ip_you_want_connect来将主机fingprint加入本机已知主机列表