简体   繁体   English

jsch 并运行“sudo su -”

[英]jsch and running "sudo su -"

Using jsch使用 jsch

when i run the following cmd 'sudo su -' the program hangs当我运行以下 cmd 'sudo su -' 程序挂起

[TestNG] Running:
C:\Users\brian.crosby\AppData\Local\Temp\testng-eclipse-952620154\testng-customsuite.xml
[root@tbx2-toy-1 ~]# 

It looks like the "sudo su -" worked becasue the output states "[root@tbx2-toy-1 ~]#" but when i send it another cmd it is unresponsive.它看起来像“sudo su -”因为输出状态“[root@tbx2-toy-1 ~]#”而起作用,但是当我向它发送另一个cmd时它没有响应。

heres the code:继承人的代码:

package com.linux;

import java.io.InputStream;
import org.testng.annotations.*;
import com.jcraft.jsch.*;
import com.thoughtworks.selenium.*;

public class LinuxConnection extends SeleneseTestBase{

    String host = null;
    private StringBuilder strFileData;
    String randomFileName = null;

    public String getFileData() {
        return strFileData.toString();
    }
    public String getRandomFileName() {
        return randomFileName;
    }

    public LinuxConnection() {
        strFileData = new StringBuilder();
    }

    @Test
    public void createUpdateTBX2FileData(String command)throws Exception {

        try {
            JSch jsch = new JSch();
            host = "brian-crosby@************.net"; 

            String user = host.substring(0, host.indexOf('@'));
            host = host.substring(host.indexOf('@') + 1);

            Session session = jsch.getSession(user, host, 22);

            UserInfo ui = new MyUserInfo();
            session.setUserInfo(ui);
            session.connect();

            ChannelExec channel = (ChannelExec)session.openChannel("exec");
            ((ChannelExec)channel).setPty(true);
            ((ChannelExec) channel).setCommand(command);

            ((ChannelExec) channel).setErrStream(System.err);

            InputStream in = channel.getInputStream();
            channel.connect();

            byte[] tmp = new byte[2048];

            while (in.read(tmp, 0, 2048) > 0) {
                String str = new String(tmp);
                strFileData.append(str);
                System.out.println(strFileData);
            }
            in.close();
            channel.disconnect();
            session.disconnect();
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    public static class MyUserInfo implements UserInfo {

        public String getPassword() {
            return "********";
        }

        public boolean promptYesNo(String str) {
            str = "Yes";
            return true;
        }

        String passwd;

        public String getPassphrase() {
            return null;
        }

        public boolean promptPassphrase(String message) {
            return true;
        }

        public boolean promptPassword(String message) {
            passwd = "*******"; 
            return true;
        }

        public void showMessage(String message) {

        }
    }

}

Here is where i am sending the cmds:这是我发送 cmds 的地方:

package com.linux;

import org.testng.annotations.*;

public class testLinuxConnection {

    @Test
    public void testLinux() throws Exception{
        LinuxConnection obj = new LinuxConnection();
        String command = "touch tester1.txt; sudo su -; rm tester1.txt;";
        obj.createUpdateTBX2FileData(command);  
    }
}

Again i have spent hours on google trying to find a solution but was unsuccessful我再次在谷歌上花了几个小时试图找到解决方案但没有成功

Any help is appreciated任何帮助表示赞赏

You are code is missing the rest of the code needed for this to run.您的代码缺少运行所需的其余代码。 You need to initialize the type of channel you need out of the initialized session object.您需要从初始化的会话对象中初始化您需要的通道类型。 Since you need to be able to run more than one command after each other, you need a Shell type channel:由于您需要能够依次运行多个命令,因此您需要一个Shell类型的通道:

You should check JSch 's examples (ie Shell.java), here it is for a quick reference:你应该检查JSch的例子(即 Shell.java),这里是一个快速参考:

/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/**
 * This program enables you to connect to sshd server and get the shell prompt.
 *   $ CLASSPATH=.:../build javac Shell.java 
 *   $ CLASSPATH=.:../build java Shell
 * You will be asked username, hostname and passwd. 
 * If everything works fine, you will get the shell prompt. Output will
 * be ugly because of lacks of terminal-emulation, but you can issue commands.
 *
 */
import com.jcraft.jsch.*;
import java.awt.*;
import javax.swing.*;

public class Shell{
  public static void main(String[] arg){

    try{
      JSch jsch=new JSch();

      //jsch.setKnownHosts("/home/foo/.ssh/known_hosts");

      String host=null;
      if(arg.length>0){
        host=arg[0];
      }
      else{
        host=JOptionPane.showInputDialog("Enter username@hostname",
                                         System.getProperty("user.name")+
                                         "@localhost"); 
      }
      String user=host.substring(0, host.indexOf('@'));
      host=host.substring(host.indexOf('@')+1);

      Session session=jsch.getSession(user, host, 22);

      String passwd = JOptionPane.showInputDialog("Enter password");
      session.setPassword(passwd);

      UserInfo ui = new MyUserInfo(){
        public void showMessage(String message){
          JOptionPane.showMessageDialog(null, message);
        }
        public boolean promptYesNo(String message){
          Object[] options={ "yes", "no" };
          int foo=JOptionPane.showOptionDialog(null, 
                                               message,
                                               "Warning", 
                                               JOptionPane.DEFAULT_OPTION, 
                                               JOptionPane.WARNING_MESSAGE,
                                               null, options, options[0]);
          return foo==0;
        }

        // If password is not given before the invocation of Session#connect(),
        // implement also following methods,
        //   * UserInfo#getPassword(),
        //   * UserInfo#promptPassword(String message) and
        //   * UIKeyboardInteractive#promptKeyboardInteractive()

      };

      session.setUserInfo(ui);

      // It must not be recommended, but if you want to skip host-key check,
      // invoke following,
      // session.setConfig("StrictHostKeyChecking", "no");

      //session.connect();
      session.connect(30000);   // making a connection with timeout.

      Channel channel=session.openChannel("shell");

      // Enable agent-forwarding.
      //((ChannelShell)channel).setAgentForwarding(true);

      channel.setInputStream(System.in);
      /*
      // a hack for MS-DOS prompt on Windows.
      channel.setInputStream(new FilterInputStream(System.in){
          public int read(byte[] b, int off, int len)throws IOException{
            return in.read(b, off, (len>1024?1024:len));
          }
        });
       */

      channel.setOutputStream(System.out);

      /*
      // Choose the pty-type "vt102".
      ((ChannelShell)channel).setPtyType("vt102");
      */

      /*
      // Set environment variable "LANG" as "ja_JP.eucJP".
      ((ChannelShell)channel).setEnv("LANG", "ja_JP.eucJP");
      */

      //channel.connect();
      channel.connect(3*1000);
    }
    catch(Exception e){
      System.out.println(e);
    }
  }

  public static abstract class MyUserInfo
                          implements UserInfo, UIKeyboardInteractive{
    public String getPassword(){ return null; }
    public boolean promptYesNo(String str){ return false; }
    public String getPassphrase(){ return null; }
    public boolean promptPassphrase(String message){ return false; }
    public boolean promptPassword(String message){ return false; }
    public void showMessage(String message){ }
    public String[] promptKeyboardInteractive(String destination,
                                              String name,
                                              String instruction,
                                              String[] prompt,
                                              boolean[] echo){
      return null;
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM