1. Add Maven dependency:
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.42</version>
</dependency>
2. Java code:
import java.io.File;
import java.io.FileInputStream;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class TestJSftp {
public static void upload(String username,
String password,
String host,
int port,
String workingDir,
String localFilename){
try {
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, port);
session.setPassword(password);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp channelSftp = (ChannelSftp) channel;
channelSftp.cd(workingDir);
File f1 = new File(localFilename);
channelSftp.put(new FileInputStream(f1), f1.getName(), ChannelSftp.OVERWRITE);
channelSftp.exit();
session.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Is there a way to use ChannelSftp with sudo command?
ReplyDeleteThere is a post here: http://stackoverflow.com/questions/13152627/is-there-any-jsch-channelsftps-function-work-like-command-cp
Deletehttp://www.jcraft.com/jsch/examples/Sudo.java.html
ReplyDelete