DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Hey there! I'm a computer nerd who spends his days messing with Grails/Groovy/Java/SQL. From time to time I dabble in mobile development and have been occasionally seen speaking about those applications around California. In my previous life, I was an adjunct computer science instructor and spent my nights grading papers, trying to get students to learn C++. These nights, my wife puts up with me tossing and turning thinking about whatever it is us computer folk think about in the wee hour of the morning, wondering if I'll ever fall asleep. Who knows? Brad has posted 2 posts at DZone. You can read more from them at their website. View Full User Profile

Groovy and JSch : SFTP transferring files

01.14.2014
| 2249 views |
  • submit to reddit
@Grab(group='com.jcraft', module='jsch', version='0.1.46')
import com.jcraft.jsch.*

java.util.Properties config = new java.util.Properties()
config.put "StrictHostKeyChecking", "no"

JSch ssh = new JSch()
Session sess = ssh.getSession "user", "server.domain.com", 22
sess.with {
	setConfig config
	setPassword "somecomplicatedpassword"
	connect()
	Channel chan = openChannel "sftp"
	chan.connect()
	
	ChannelSftp sftp = (ChannelSftp) chan;
	def sessionsFile = new File('c:/important_document.doc')
	sessionsFile.withInputStream { istream -> sftp.put(istream, "/home/brippe/Documents/important_document.doc") }
	chan.disconnect()
	disconnect()
}

This is a simple example of how to transfer a file using Groovy, JSch, and SFTP.