Last active
December 30, 2015 00:29
-
-
Save mostlylikeable/7749878 to your computer and use it in GitHub Desktop.
ssh util
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import com.jcraft.jsch.Channel | |
| import com.jcraft.jsch.ChannelSftp | |
| import com.jcraft.jsch.JSch | |
| import com.jcraft.jsch.Session | |
| import java.util.concurrent.TimeUnit | |
| class Ssh { | |
| JSch jsch = new JSch() | |
| String hostname | |
| String username | |
| String password | |
| int port = 22 | |
| boolean strictHostKeyChecking = false | |
| int connectionTimeoutMillis = TimeUnit.SECONDS.toMillis(30) | |
| def withSftpConnection(Closure cl) { | |
| withChannel('sftp') { Channel channel -> | |
| cl.delegate = new SftpDelegate(channel: (ChannelSftp) channel) | |
| cl() | |
| } | |
| } | |
| private void withChannel(String type, Closure cl) { | |
| withConnection { Session session -> | |
| Channel channel = session.openChannel(type) | |
| channel.connect() | |
| try { | |
| cl(channel) | |
| } finally { | |
| channel.disconnect() | |
| } | |
| } | |
| } | |
| private void withConnection(Closure cl) { | |
| Session session = jsch.getSession(username, hostname, port) | |
| session.password = password | |
| session.setConfig('StrictHostKeyChecking', toYesNo(strictHostKeyChecking)) | |
| session.connect(connectionTimeoutMillis) | |
| try { | |
| cl(session) | |
| } finally { | |
| session.disconnect() | |
| } | |
| } | |
| private String toYesNo(boolean value) { | |
| return value ? 'yes' : 'no' | |
| } | |
| } | |
| class SftpDelegate { | |
| ChannelSftp channel | |
| void put(String src, String dest) { | |
| put(new File(src), dest) | |
| } | |
| void put(File src, String dest) { | |
| InputStream is = new BufferedInputStream(new FileInputStream(src)) | |
| try { | |
| put(is, dest) | |
| } finally { | |
| is.close() | |
| } | |
| } | |
| void put(InputStream src, String dest) { | |
| channel.put(src, dest) | |
| } | |
| } | |
| class Test { | |
| static void main(String[] args) { | |
| new Ssh(hostname: 'bar.com', username: 'foo', password: 'password').withSftpConnection { | |
| put 'local-file.txt', 'remote-file.txt' | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment