Saturday, May 3, 2008

SSH over Ant, Java

For File transferring files in SSH you require following jar "jsch-0.1.37.jar"

ANT Script

<target name="copy" description="Copy file via SSH" >
<scp file="sourcefile"
todir="userid@$hostname:destdirectory"
trust="true"
password="passowrd" />
</target>

Make sure Trust is set to true.

Java Program
Following are the java program.

import org.apache.commons.configuration.PropertiesConfiguration;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;

public class SshFileTransfer {

private static class UserDetails implements UserInfo {
/*
Inner Class. Userinfo has to implemented for getting password Information and seeing console message.
*/
private String password;

public String getPassphrase() {
return null;
}

public String getPassword() {
return password;
}

public boolean promptPassphrase(String arg0) {
return true;
}

public boolean promptPassword(String arg0) {
return true;
}

public boolean promptYesNo(String arg0) {
return true;
}

public void setPassword(String password) {
this.password = password;

}

public void showMessage(String arg0) {
//Show the Console message
System.out.println(arg0);
}

}

ChannelSftp channel;

public void connect(String server, String destFilename, String src) throws Exception {
//Connection details are Stored in Properties files.
PropertiesConfiguration properties = new PropertiesConfiguration("conf/sftp.properties");
String hostname = properties.getString("server.hostname");
String userid = properties.getString("server.user");
String password = properties.getString("server.password");
int port = Integer.parseInt(properties.getString("server.port"));
if (hostname == null || hostname.trim().length() == 0 || userid == null
|| userid.trim().length() == 0 || password == null || password.trim().length() == 0) {
throw new Exception("Server details is empty/null");
}
// System.out.println("User -->" + userid);
// System.out.println("hostname -->" + hostname);
// System.out.println("password -->" + password);
// System.out.println("port -->" + port);

JSch shell = new JSch();
Session session = shell.getSession(userid, hostname, port);
UserDetails ui = new UserDetails();
ui.setPassword(password);
session.setUserInfo(ui);
session.connect();
channel = (ChannelSftp) session.openChannel("sftp");
channel.connect();
if (isConnected()) {
channel.put(src, destFilename);
//Disconnect after file tranfer.
channel.disconnect();
}
}

public boolean isConnected() {
return (channel != null && channel.isConnected());
}

}

No comments: