【问题标题】:Sending commands to remote server through ssh by Java with JSch使用 JSch 通过 Java 通过 ssh 向远程服务器发送命令
【发布时间】:2013-05-04 07:47:10
【问题描述】:

我正在尝试设置一个类,以便我可以通过 ssh 连接到远程服务器(我有 IP、用户名和密码),然后发送类似 echo "test" 的命令,然后接收返回的输出(例如, “测试”)。我正在使用 JSch 来执行此操作,但我不明白如何执行此操作。

import com.jcraft.jsch.*;

public class ConnectSSH {

public int execute (String command) {
    
    JSch jsch   = new JSch();
    String ip   = "00.00.00.00";
    String user = "root";
    String pass = "password";
    int port    = 22;

    Session session = jsch.getSession(user, ip, port);   
    session.setPassword(pass);
    session.connect();

    ...

连接后卡住了。

【问题讨论】:

    标签: java ssh jsch


    【解决方案1】:
     1. List item
    
    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="10.75.81.21";
            String user="root";
            String password="Avaya_123";
            String command1="ls -l";
            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));
                  }`enter code here`
                  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();
            }
    
        }
    
    
     1. List item
    
    }
    

    【讨论】:

    • 您能否详细说明您的解决方案?
    【解决方案2】:

    试试这个:

    JSch jsch=new JSch();
    Session session=jsch.getSession(remoteHostUserName, RemoteHostName, 22);
    session.setPassword(remoteHostpassword);
    Properties config = new Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.connect();
    
    ChannelExec channel=(ChannelExec) session.openChannel("exec");
    BufferedReader in=new BufferedReader(new InputStreamReader(channel.getInputStream()));
    channel.setCommand("pwd;");
    channel.connect();
    
    String msg=null;
    while((msg=in.readLine())!=null){
      System.out.println(msg);
    }
    
    channel.disconnect();
    session.disconnect();
    

    【讨论】:

    【解决方案3】:

    shamnu 上面的回答是正确的。我无法对其添加评论,因此这里有一些示例可以增强他的答案。一个是如何远程执行“ls -l”,另一个是“mkdir”,另一个是本地到远程复制。全部使用 0.1.51 版的 jsch (http://www.jcraft.com/jsch/) 完成。

      public void remoteLs() throws JSchException, IOException {
        JSch js = new JSch();
        Session s = js.getSession("myusername", "myremotemachine.mycompany.com", 22);
        s.setPassword("mypassword");
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        s.setConfig(config);
        s.connect();
    
        Channel c = s.openChannel("exec");
        ChannelExec ce = (ChannelExec) c;
    
        ce.setCommand("ls -l");
        ce.setErrStream(System.err);
    
        ce.connect();
    
        BufferedReader reader = new BufferedReader(new InputStreamReader(ce.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
          System.out.println(line);
        }
    
        ce.disconnect();
        s.disconnect();
    
        System.out.println("Exit code: " + ce.getExitStatus());
    
      }
    
    
    
      public void remoteMkdir() throws JSchException, IOException {
        JSch js = new JSch();
        Session s = js.getSession("myusername", "myremotemachine.mycompany.com", 22);
        s.setPassword("mypassword");
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        s.setConfig(config);
        s.connect();
    
        Channel c = s.openChannel("exec");
        ChannelExec ce = (ChannelExec) c;
    
        ce.setCommand("mkdir remotetestdir");
        ce.setErrStream(System.err);
    
        ce.connect();
    
        BufferedReader reader = new BufferedReader(new InputStreamReader(ce.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
          System.out.println(line);
        }
    
        ce.disconnect();
        s.disconnect();
    
        System.out.println("Exit code: " + ce.getExitStatus());
    
      }
    
      public void remoteCopy() throws JSchException, IOException, SftpException {
        JSch js = new JSch();
        Session s = js.getSession("myusername", "myremotemachine.mycompany.com", 22);
        s.setPassword("mypassword");
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        s.setConfig(config);
        s.connect();
    
        Channel c = s.openChannel("sftp");
        ChannelSftp ce = (ChannelSftp) c;
    
        ce.connect();
    
        ce.put("/home/myuser/test.txt","test.txt");
    
        ce.disconnect();
        s.disconnect();    
      }
    

    【讨论】:

    • 请注意,如果您所做的只是文件操作,您可以使用ChannelSftp,它提供了 cd()、mkdir() 和 put() 等方法。
    【解决方案4】:

    我建议查看 JCraft 网站上的隐藏示例:http://www.jcraft.com/jsch/examples/UserAuthKI.java

    他们的示例提示输入用户名、主机名、密码,因此可以开箱即用地进行测试。我在我的网络上运行它,无需更改任何代码即可连接到 AIX 服务器。

    注意,他们的示例有问题(这可能是它被隐藏的原因).. 它永远不会关闭通道。如果您发送“退出”,服务器将断开您的连接,但通道对象保持打开状态并且您的 Java 程序永远不会退出。我在这里提供了一个修复:Never ending of reading server response using jSch

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-10
      • 1970-01-01
      • 2021-01-17
      • 1970-01-01
      • 2013-11-22
      • 2011-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多