【问题标题】:How to use a command-line *nix command that needs an interactive terminal over JSch SSH session in Java?如何在 Java 中使用需要通过 JSch SSH 会话进行交互式终端的命令行 *nix 命令?
【发布时间】:2016-02-28 11:26:49
【问题描述】:

我正在尝试在 java 中创建代码,通过我在 Linux 中成功测试的 minicom 包使用 GSM 调制解调器发送 SMS。

知道我正在使用 JSch 库进行 SSH 并使用 minicom。我已经用普通的 Linux 命令成功地测试了这段代码。

import java.io.InputStream;

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


public class SSHCommandExecutor {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String host="localhost";
        String user="root";
        String password="XXXXX";
        String command1="minicom";
        try{

            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            JSch jsch = new JSch();
            Session session=jsch.getSession(user, host, 22);
            session.setPassword(password);
            session.setConfig(config);
            session.connect();
            System.out.println("Connected");

            Channel channel=session.openChannel("exec");
            ((ChannelExec)channel).setCommand(command1);
            channel.setInputStream(null);
            ((ChannelExec)channel).setErrStream(System.err);

            InputStream in=channel.getInputStream();
            channel.connect();
            byte[] tmp=new byte[1024];
            while(true){
              while(in.available()>0){
                int i=in.read(tmp, 0, 1024);
                if(i<0)break;
                System.out.print(new String(tmp, 0, i));
              }
              if(channel.isClosed()){
                System.out.println("exit-status: "+channel.getExitStatus());
                break;
              }
              try{Thread.sleep(1000);}catch(Exception ee){}
            }
            channel.disconnect();
            session.disconnect();
            System.out.println("DONE");
        }catch(Exception e){
            e.printStackTrace();
        }

    }

}

但问题是我无法向 minicom 发送命令,它会输出:

无光标移动能力(厘米)

我相信它需要终端环境,我不想在 Java 中使用终端模拟器。我只是想通过Java代码向minicom发送命令。

有什么办法可以做到吗?

PS:我尝试过使用 smslib 解决此问题的其他可能性,但由于 rxtx 和其他解决方案,它在 Linux 中无法正常工作。现在只有 minicom 可以正常工作。

【问题讨论】:

    标签: java sms jsch


    【解决方案1】:

    如果问题确实是命令没有在非交互式终端上启动,但它确实不需要任何交互性,您可以简单地通过使用 .setPty(true) 调用使“exec”通道“交互”。

    channel.setPty(true);
    channel.connect();
    

    【讨论】:

    • 感谢 minicom 在控制台中吃午饭,但有什么方法可以在这段代码中向 minicom 发送 AT 命令吗?
    • 不客气。我相信我已经回答了你的问题。发送 AT 命令是一个新问题的主题。
    猜你喜欢
    • 2018-07-12
    • 1970-01-01
    • 2011-01-25
    • 2012-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-24
    • 1970-01-01
    相关资源
    最近更新 更多