需求: 将本地的一个脚本传到另一台并执行,两个工具类实现,ShellFileUtil 远程传文件ShellUtil远程操作虚拟机执行脚本
以下是代码
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;
import java.util.Vector;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
public class ShellFileUtil {
/**
* 连接sftp服务器
*
* @param host
* 主机
* @param port
* 端口
* @param username
* 用户名
* @param password
* 密码
* @return
*/
public static ChannelSftp connect(String host, int port, String username,
String password) {
ChannelSftp sftp = null;
try {
JSch jsch = new JSch();
//jsch.getSession(username, host, port);
Session sshSession = jsch.getSession(username, host, port);
System.out.println("Session created.");
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
System.out.println("Session connected.");
System.out.println("Opening Channel.");
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
System.out.println("Connected to " + host + ".");
} catch (Exception e) {
}
return sftp;
}
/**
* 上传文件
*
* @param directory
* 上传的目录
* @param uploadFile
* 要上传的文件
* @param sftp
*/
public static void upload(String directory, String uploadFile, ChannelSftp sftp) {
try {
sftp.cd(directory);
File file = new File(uploadFile);
sftp.put(new FileInputStream(file), file.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 下载文件
*
* @param directory
* 下载目录
* @param downloadFile
* 下载的文件
* @param saveFile
* 存在本地的路径
* @param sftp
*/
public static void download(String directory, String downloadFile,
String saveFile, ChannelSftp sftp) {
try {
sftp.cd(directory);
File file = new File(saveFile);
sftp.get(downloadFile, new FileOutputStream(file));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 删除文件
*
* @param directory
* 要删除文件所在目录
* @param deleteFile
* 要删除的文件
* @param sftp
*/
public static void delete(String directory, String deleteFile, ChannelSftp sftp) {
try {
sftp.cd(directory);
sftp.rm(deleteFile);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 列出目录下的文件
*
* @param directory
* 要列出的目录
* @param sftp
* @return
* @throws SftpException
*/
public static Vector listFiles(String directory, ChannelSftp sftp)
throws SftpException {
return sftp.ls(directory);
}
}
下面是远程操作的工具,其中有部分变量未使用,我只使用了连接和执行的方法,多余的啥的也没管,没啥影响
import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;
import expect4j.Closure;
import expect4j.Expect4j;
import expect4j.ExpectState;
import expect4j.matches.EofMatch;
import expect4j.matches.Match;
import expect4j.matches.RegExpMatch;
import expect4j.matches.TimeoutMatch;
import org.apache.oro.text.regex.MalformedPatternException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
public class ShellUtil {
private Session session;
private ChannelShell channel;
private static Expect4j expect = null;
private static final long defaultTimeOut = 1000;
private StringBuffer buffer=new StringBuffer();
public static final int COMMAND_EXECUTION_SUCCESS_OPCODE = -2;
public static final String BACKSLASH_R = "\r";
public static final String BACKSLASH_N = "\n";
public static final String COLON_CHAR = ":";
public static String ENTER_CHARACTER = BACKSLASH_R;
public static final int SSH_PORT = 22;
//正则匹配,用于处理服务器返回的结果
public static String[] linuxPromptRegEx = new String[] { "~]#", "~#", "#",
":~#", "/$", ">" };
public static String[] errorMsg=new String[]{"could not acquire the config lock "};
//ssh服务器的ip地址
private String ip;
//ssh服务器的登入端口
private int port;
//ssh服务器的登入用户名
private String user;
//ssh服务器的登入密码
private String password;
public ShellUtil(){
}
public ShellUtil(String ip,int port,String user,String password) {
this.ip=ip;
this.port=port;
this.user=user;
this.password=password;
expect = getExpect();
}
private Expect4j getExpect() {
try {
JSch jsch = new JSch();
session = jsch.getSession(user, ip, port);
session.setPassword(password);
session.setTimeout(200000);
Hashtable<String, String> config = new Hashtable<String, String>();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
localUserInfo ui = new localUserInfo();
session.setUserInfo(ui);
session.connect();
channel = (ChannelShell) session.openChannel("shell");
Expect4j expect = new Expect4j(channel.getInputStream(), channel
.getOutputStream());
channel.connect();
return expect;
}catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* 执行配置命令
* @param commands 要执行的命令,为字符数组
* @return 执行是否成功
*/
public boolean executeCommands(String[] commands) {
// 如果expect返回为0,说明登入没有成功
if (expect == null) {
return false;
}
System.out.println("----------Running commands are listed as follows:----------");
for (String command : commands) {
System.out.println(command);
}
System.out.println("----------End----------");
Closure closure = new Closure() {
public void run(ExpectState expectState) throws Exception {
buffer.append(expectState.getBuffer());// buffer is string
// buffer for appending
// output of executed
// command
expectState.exp_continue();
}
};
List<Match> lstPattern = new ArrayList<Match>();
String[] regEx = linuxPromptRegEx;
if (regEx != null && regEx.length > 0) {
synchronized (regEx) {
for (String regexElement : regEx) {// list of regx like, :>, />
// etc. it is possible
// command prompts of your
// remote machine
try {
RegExpMatch mat = new RegExpMatch(regexElement, closure);
lstPattern.add(mat);
} catch (MalformedPatternException e) {
return false;
} catch (Exception e) {
return false;
}
}
lstPattern.add(new EofMatch(new Closure() { // should cause
// entire page to be
// collected
public void run(ExpectState state) {
}
}));
lstPattern.add(new TimeoutMatch(defaultTimeOut, new Closure() {
public void run(ExpectState state) {
}
}));
}
}
try {
boolean isSuccess = true;
for (String strCmd : commands) {
isSuccess = isSuccess(lstPattern, strCmd);
}
// 防止最后一个命令执行不了
isSuccess = !checkResult(expect.expect(lstPattern));
// 找不到错误信息标示成功
String response = buffer.toString().toLowerCase();
for (String msg : errorMsg) {
if (response.indexOf(msg) > -1) {
return false;
}
}
return isSuccess;
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
}
//检查执行是否成功
private boolean isSuccess(List<Match> objPattern, String strCommandPattern) {
try {
boolean isFailed = checkResult(expect.expect(objPattern));
if (!isFailed) {
expect.send(strCommandPattern);
expect.send("\r");
return true;
}
return false;
} catch (MalformedPatternException ex) {
return false;
} catch (Exception ex) {
return false;
}
}
//检查执行返回的状态
private boolean checkResult(int intRetVal) {
if (intRetVal == COMMAND_EXECUTION_SUCCESS_OPCODE) {
return true;
}
return false;
}
/*
* 测试是否连接成功
*/
public boolean checkConnect(){
if(expect==null){
return false;//未连接成功
}else{
return true;//连接成功
}
}
/**
* 关闭SSH远程连接
*/
public void disconnect(){
if(channel!=null){
channel.disconnect();
}
if(session!=null){
session.disconnect();
}
}
/**
* 获取服务器返回的信息
* @return 服务端的执行结果
*/
public String getResponse(){
return buffer.toString();
}
//设置不提示输入密码、不显示登入信息等
public static class localUserInfo implements UserInfo {
String passwd;
public String getPassword() {
return passwd;
}
public boolean promptYesNo(String str) {
return true;
}
public String getPassphrase() {
return null;
}
public boolean promptPassphrase(String message) {
return true;
}
public boolean promptPassword(String message) {
return true;
}
public void showMessage(String message) {
}
}
}