Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ru.smoltelecom.zapret.protocol;
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import ru.smoltelecom.zapret.protocol.auth.UserPassInfo;
- import com.jcraft.jsch.Channel;
- import com.jcraft.jsch.ChannelExec;
- import com.jcraft.jsch.ChannelSftp;
- import com.jcraft.jsch.ChannelShell;
- import com.jcraft.jsch.JSch;
- import com.jcraft.jsch.Session;
- import com.jcraft.jsch.UserInfo;
- import expect4j.Expect4j;
- public class SFTP {
- private String host;
- private String userName;
- private String userPassword;
- private int port;
- private Session session;
- private Channel channel;
- private ChannelShell shell;
- private Expect4j expect;
- private ExpectHelper expectHelper;
- private JSch jsch;
- public SFTP(String host, String userName, String userPassword, int port) {
- this.host = host;
- this.userName = userName;
- this.userPassword = userPassword;
- this.port = port;
- }
- public void open() throws Exception {
- jsch = new JSch();
- session = jsch.getSession(userName, host, port);
- UserInfo ui = new UserPassInfo(userPassword);
- session.setUserInfo(ui);
- session.connect();
- }
- public ChannelSftp openSFTPChannel() throws Exception {
- channel = session.openChannel("sftp");
- channel.connect();
- return (ChannelSftp)channel;
- }
- public ExpectHelper getExpect(String rootPassword) throws Exception {
- if(shell==null){
- shell = (ChannelShell)session.openChannel("shell");
- expect = new Expect4j(shell.getInputStream(),shell.getOutputStream());
- expect.setDefaultTimeout(1000L);
- expectHelper = new ExpectHelper(expect,rootPassword);
- }
- return expectHelper;
- }
- public void closeExpect(){
- shell.disconnect();
- expect.close();
- }
- public String execCommand(String command) throws Exception {
- Channel channel = session.openChannel("exec");
- ChannelExec exec = (ChannelExec)channel;
- BufferedReader in = new BufferedReader(new InputStreamReader(exec.getInputStream()));
- exec.setCommand(command);
- exec.connect();
- String msg = null;
- String result = "";
- while ((msg = in.readLine()) != null) {
- result+=msg+"\n";
- System.out.print(msg+"\n");
- }
- exec.disconnect();
- return result;
- }
- public void close(){
- if (channel != null) {
- channel.disconnect();
- }
- if (session != null) {
- session.disconnect();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement