packagexxx.utilsimport com.jcraft.jsch.*
importorg.slf4j.Loggerimportorg.slf4j.LoggerFactoryimportjava.text.SimpleDateFormat
//使用的是groovyclassSftpUtil {private static final Logger logger =LoggerFactory.getLogger(SftpUtil.getClass())static SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd")
JSch jsch= nullSession session= nullChannelSftp channel= null
static ThreadLocal sftpLocal = new ThreadLocal()
SftpUtil(String userName, String host,intport, String password) {
connect(userName, host, port, password)
}
SftpUtil(String userName, String host,intport, String password, String keyFilePath, String passphrase) {
connect(userName, host, port, password, keyFilePath, passphrase)
}booleanisConnected() {return null != channel &&channel.isConnected()
}static SftpUtil getSftpUtil(String userName, String host, int port, String password) throwsException {
SftpUtil sftpUtils=sftpLocal.get()if (sftpUtils == null || !sftpUtils.isConnected()) {
sftpLocal.set(newSftpUtil(userName, host, port, password))
}returnsftpLocal.get()
}static SftpUtil getSftpUtil(String userName, String host, int port, String password, String keyFilePath, String passphrase) throwsException {
SftpUtil sftpUtils=sftpLocal.get()if (sftpUtils == null || !sftpUtils.isConnected()) {
sftpLocal.set(newSftpUtil(userName, host, port, password, keyFilePath, passphrase))
}returnsftpLocal.get()
}static voidrelease() {if (null !=sftpLocal.get()) {
sftpLocal.get().close()
sftpLocal.set(null)
}
}/*** 连接到指定的IP
*
*@throwsJSchException*/ChannelSftp connect(String userName, String host,intport, String password) {try{
jsch= new JSch()//创建JSch对象
session = jsch.getSession(userName, host, port)//根据用户名、主机ip、端口号获取一个Session对象
session.setConfig("PreferredAuthentications", "password")
session.setPassword(password)
session.setConfig("StrictHostKeyChecking", "no")
session.setTimeout(60000)
session.setServerAliveInterval(2000)
session.setServerAliveCountMax(8)
session.connect(3000)
logger.info("sftp session connected.")
channel= (ChannelSftp) session.openChannel("sftp")
channel.connect(3000)
logger.info("Connected successfully ${host} ${userName}")
}catch(