Файлы запуска зависят от оболочки.

аюсь запустить команды, которые используют локальные логические пути Linux, такие какcat $test_dir/test.dat, но логический путь$test_dir (которая является переменной среды пользователя) недоступна черезChannelExec, Но когда я использую интерактивныйChannelShellЯ могу видеть пользовательские переменные и команды отлично работают в интерактивном сеансе. Я могу просматривать переменную среды системного уровня только из сеанса "exec". Возможно ли это даже с использованием библиотеки JSch, если да, то как мне ее достичь, а если нет, то какую библиотеку я буду использовать для достижения этой цели?

Добавив код моего класса ниже: `public class SecureShell {

private static final Logger logger = LogManager.getLogger(SecureShell.class);

private String uName;
private String pWord;
private String hName;
private int port;

private Session session = null;
private Channel channel = null;

/**Create an instance to start and stop the remote shell and execute commands remotely via java.
 * 
 * @param uName
 *          host username 
 * @param pWord
 *          host password
 * @param hName
 *          host name
 * @param port
 *          host port number
 */
public SecureShell(String uName, String pWord, String hName, int port) {
    this.uName = uName;
    this.pWord = pWord;
    this.hName = hName;
    this.port = port;
}

/**Create an instance to start and stop the remote shell and execute commands remotely via java.
 * 
 *@param uName
 *          host username 
 * @param pWord
 *          host password
 * @param hName
 *          host name
 */
public SecureShell(String uName, String pWord, String hName) {
    this.uName = uName;
    this.pWord = pWord;
    this.hName = hName;
    this.port = 22;
}

/**Start the session with the host.
 * @return
 *      true if the session started successfully, false otherwise
 */
public boolean startSession() {
    JSch jsch = new JSch();
    try {
        session = jsch.getSession(uName, hName, por,t);

        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.setPassword(pWord);
        session.connect();

    } catch (JSchException jsche) {
        logger.error(jsche.getMessage());
        return false;
    } 

    return true;
}

/** Execute commands on the host;
 * @param command
 *          command to be executed on the host.
 * @return
 *      status of the execution
 */
public int execute(String command) {

    int status = -1;
    if(session != null && session.isConnected()) {
        try {
            channel = session.openChannel("exec");
            //((ChannelExec)channel).setEnv("LC_XXX", "xxxxxxx");
            ((ChannelExec)channel).setPty(true);
            ((ChannelExec) channel).setCommand(command);

            InputStream in = channel.getInputStream();

            channel.connect();

             byte[] buffer = new byte[1024];
             while(true){
                 while(in.available()>0){
                     int i=in.read(buffer, 0, 1024);
                     System.out.print(new String(buffer, 0, i));
                     if(i<0)
                         break;
                }
                 if(channel.isClosed()){
                     if(in.available()>0) 
                         continue; 
                     status = channel.getExitStatus();
                     break;
                 }
            }
        } catch (JSchException jsche) {
            logger.error(jsche.getMessage());
        } catch (IOException ioe) {
            logger.error(ioe.getMessage());
        } finally {
            if(channel!=null && channel.isConnected())
                channel.disconnect();
        } 
    }

    return status;
}

/**Stop the session with the remote.
 * 
 */
public void stopSession() {

    if(session!=null && session.isConnected())
        session.disconnect();
}

public static void main(String[] args) {
    SecureShell ssh  = new SecureShell("user", "password", "hostname");
    ssh.startSession();
    System.out.println(ssh.execute("env"));
    ssh.stopSession();
}

} `

Ответы на вопрос(2)

Ваш ответ на вопрос