Как редактировать файл внутри zip удаленно на Secure_CRT? - PullRequest
3 голосов
/ 26 марта 2019

У меня есть задача отредактировать файл внутри zip на SecureCRT.Я могу запускать команды Linux удаленно, используя библиотеку JSCH (com.jcraft.jsch)

Вот часть моего кода:

 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();

Я хочу знать, что является лучшим способом,или правильные команды для редактирования файла (например, Test.txt) внутри zip-файла на сервере SecureCRT.

1 Ответ

1 голос
/ 02 апреля 2019

Контексты внутри zip-файла могут быть изменены различными способами.

Я упомянул несколько способов, которые на самом деле могут работать для вас.Для этого

Мы должны безопасно передать исходный файл / скомпилированный файл с локального компьютера на сервер.Приведенная ниже ссылка поможет безопасно передать файл.

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

В качестве первого шага мы должны разработать фрагмент, способный изменять контекст zip-файла.следует скопировать файл на сервер.Затем мы выполняем команду для запуска файла так, чтобы контексты внутри zip были изменены.

Описанный ниже подход упоминался только для изменения контентов zip.

Подход 1: Использование простогоФрагмент Java для достижения

Мы можем написать простой фрагмент кода Java, который может открыть файл zip и отредактировать его. Сохраните файл в машине, а затем выполните файл класса, просто запустив «имя файла java», которое фактически изменит контексты.в zip-файле.

Ссылка, которая поможет: Изменение текстового файла в ZIP-архиве на 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");
  }

}

Подход 2: Использование python для изменения zipfiles

Как обновить один файл внутри zip-файла, используя python

Подход 3: Написание сценария оболочки для непосредственного изменения контекста zip-файла, чтобы мы могли скопироватьсценарий оболочки на сервер, а затем непосредственно выполнить сценарий оболочки.https://superuser.com/questions/647674/is-there-a-way-to-edit-files-inside-of-a-zip-file-without-explicitly-extracting

Приведенный ниже фрагмент поможет вам подключиться и выполнить с помощью библиотеки.

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();
  }

}
...