How to edit a file inside a zip remotely on Secure_CRT?

Tal Angel :

I have a task to edit a file inside of a zip on SecureCRT. I am able to run Linux commands remotely using JSCH library (com.jcraft.jsch)

Here is part of my code:

 Session session = setUpSession(testParameters, softAsserter);
                Channel channel = session.openChannel("exec");
                ((ChannelExec)channel).setCommand(command);
                channel.setInputStream(null);
                ((ChannelExec)channel).setErrStream(System.err);
                InputStream inputStream = channel.getInputStream();                    
                channel.connect();

I wish to know what is the best way, or the right commands in order to edit a file (for example Test.txt) inside of a zip file on a SecureCRT server.

redhatvicky :

The contends inside the zip file can be modified in significant number of ways.

I have mentioned some ways which actually might work for you. In order to do that

We should securely transfer the source file/compiled file from local machine to server. The below link would help to transfer the file securely .

https://www.vandyke.com/int/drag_n_drop.html

As a first step , We should develop a snippet which is capable of modifying the contends of the zip file, Then we should copy the file to the server . Then we execute the command to run the file so that the contends inside the zip gets modified.

The below approach has been mentioned only to modify the zip contends.

Approach 1: Using a Simple Java snippet to achieve

We can write a simple java snippet which can open the zip file and edit , Keep the file in the machine and then execute the class file by just running "java filename" which would actually modify contends in the zip file.

Link which would help : Modifying a text file in a ZIP archive in Java

import java.io.*;
import java.nio.file.*;

class RemoteEditFileContends {

  /**
   * Edits the text file in zip.
   *
   * @param zipFilePathInstance
   *          the zip file path instance
   * @throws IOException
   *           Signals that an I/O exception has occurred.
   */
  public static void editTextFileInZip(String zipFilePathInstance) throws IOException {
    Path pathInstance = Paths.get(zipFilePathInstance);
    try (FileSystem fileSystemIns = FileSystems.newFileSystem(pathInstance, null)) {
      Path pathSourceInstance = fileSystemIns.getPath("/abc.txt");
      Path tempCopyIns = generateTempFile(fileSystemIns);
      Files.move(pathSourceInstance, tempCopyIns);
      streamCopy(tempCopyIns, pathSourceInstance);
      Files.delete(tempCopyIns);
    }
  }

  /**
   * Generate temp file.
   *
   * @param fileSystemIns
   *          the file system ins
   * @return the path
   * @throws IOException
   *           Signals that an I/O exception has occurred.
   */
  public static Path generateTempFile(FileSystem fileSystemIns) throws IOException {
    Path tempCopyIns = fileSystemIns.getPath("/___abc___.txt");
    if (Files.exists(tempCopyIns)) {
      throw new IOException("temp file exists, generate another name");
    }
    return tempCopyIns;
  }

  /**
   * Stream copy.
   *
   * @param sourecInstance
   *          the src
   * @param destinationInstance
   *          the dst
   * @throws IOException
   *           Signals that an I/O exception has occurred.
   */
  public static void streamCopy(Path sourecInstance, Path destinationInstance) throws IOException {
    try (
        BufferedReader bufferInstance = new BufferedReader(new InputStreamReader(Files.newInputStream(sourecInstance)));
        BufferedWriter writerInstance = new BufferedWriter(
            new OutputStreamWriter(Files.newOutputStream(destinationInstance)))) {
      String currentLine = null;
      while ((currentLine = bufferInstance.readLine()) != null) {
        currentLine = currentLine.replace("key1=value1", "key1=value2");
        writerInstance.write(currentLine);
        writerInstance.newLine();
      }
    }
  }

  public static void main(String[] args) throws IOException {
    editTextFileInZip("test.zip");
  }

}

Approach 2: Using python to modify the zip files

How to update one file inside zip file using python

Approach 3 : Writing a shell script to modify the contends of zip file directly, So that we can copy the shell script to the server and then execute directly the shell script. https://superuser.com/questions/647674/is-there-a-way-to-edit-files-inside-of-a-zip-file-without-explicitly-extracting

The below snippet would help you to connect and execute using the library.

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class ConnetionManager {

  private static final Logger _logger = Logger.getLogger(ConnetionManager.class.getName());

  private JSch jschSSHChannel;

  private String strUserName;

  private String strConnectionIP;

  private int intConnectionPort;

  private String strPassword;

  private Session sesConnection;

  private int intTimeOut;

  private void doCommonConstructorActions(String userNameInstance, String tokenpassword, String connetionServerIo,
      String hostFileName) {
    jschSSHChannel = new JSch();
    try {
      jschSSHChannel.setKnownHosts(hostFileName);
    } catch (JSchException exceptionInstance) {
      _logError(exceptionInstance.getMessage());
    }
    strUserName = userNameInstance;
    strPassword = tokenpassword;
    strConnectionIP = connetionServerIo;
  }

  public ConnetionManager(String userName, String password, String connectionIP, String knownHostsFileName) {
    doCommonConstructorActions(userName, password, connectionIP, knownHostsFileName);
    intConnectionPort = 22;
    intTimeOut = 60000;
  }

  public ConnetionManager(String userName, String password, String connectionIP, String knownHostsFileName,
      int connectionPort) {
    doCommonConstructorActions(userName, password, connectionIP, knownHostsFileName);
    intConnectionPort = connectionPort;
    intTimeOut = 60000;
  }

  public ConnetionManager(String userName, String password, String connectionIP, String knownHostsFileName,
      int connectionPort, int timeOutMilliseconds) {
    doCommonConstructorActions(userName, password, connectionIP, knownHostsFileName);
    intConnectionPort = connectionPort;
    intTimeOut = timeOutMilliseconds;
  }

  public String connect() {
    String errorMessage = null;
    try {
      sesConnection = jschSSHChannel.getSession(strUserName, strConnectionIP, intConnectionPort);
      sesConnection.setPassword(strPassword);
      sesConnection.connect(intTimeOut);
    } catch (JSchException exceptionInstance) {
      errorMessage = exceptionInstance.getMessage();
    }
    return errorMessage;
  }

  private String _logError(String errorMessage) {
    if (errorMessage != null) {
      _logger.log(Level.SEVERE, "{0}:{1} - {2}", new Object[] { strConnectionIP, intConnectionPort, errorMessage });
    }
    return errorMessage;
  }

  private String _logWarnings(String warnMessage) {
    if (warnMessage != null) {
      _logger.log(Level.WARNING, "{0}:{1} - {2}", new Object[] { strConnectionIP, intConnectionPort, warnMessage });
    }
    return warnMessage;
  }

  public String sendCommand(String executionCommand) {
    StringBuilder outputBuffer = new StringBuilder();
    try {
      Channel channelInstance = sesConnection.openChannel("exec");
      ((ChannelExec) channelInstance).setCommand(executionCommand);
      InputStream commandOutputStream = channelInstance.getInputStream();
      channelInstance.connect();
      int readByte = commandOutputStream.read();
      while (readByte != 0xffffffff) {
        outputBuffer.append((char) readByte);
        readByte = commandOutputStream.read();
      }
      channelInstance.disconnect();
    } catch (IOException ioExceptionInstance) {
      _logWarnings(ioExceptionInstance.getMessage());
      return null;
    } catch (JSchException schExceptionInstance) {
      _logWarnings(schExceptionInstance.getMessage());
      return null;
    }
    return outputBuffer.toString();
  }

  public void close() {
    sesConnection.disconnect();
  }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=105960&siteId=1