关于 jsch 中 sudo su - 用户的想法

2024-04-22

我在 jsch 中使用 sudo su 时遇到问题,下面是我的帖子(exec.java):

package com.test;

import com.jcraft.jsch.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;

public class Exec{
  public static void main(String[] arg){
    try{
      JSch jsch=new JSch();  

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

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

      /*
      String xhost="127.0.0.1";
      int xport=0;
      String display=JOptionPane.showInputDialog("Enter display name", 
                                                 xhost+":"+xport);
      xhost=display.substring(0, display.indexOf(':'));
      xport=Integer.parseInt(display.substring(display.indexOf(':')+1));
      session.setX11Host(xhost);
      session.setX11Port(xport+6000);
      */

      // username and password will be given via UserInfo interface.
      UserInfo ui=new MyUserInfo();
      session.setUserInfo(ui);
      session.connect();
      String command = "cd bin";

      System.out.println(command);
      Channel channel=session.openChannel("exec");
      channel.setInputStream(null);
      ((ChannelExec)channel).setErrStream(System.err);

      InputStream in=channel.getInputStream();

      channel.connect();
      ((ChannelExec)channel).setCommand("sudo su - user -");

      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){}
        System.out.println("te");
      }

      channel.disconnect();
      session.disconnect();
    }
    catch(Exception e){
      System.out.println(e);
    }
  }

  public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{
    public String getPassword(){ return passwd; }
    public boolean promptYesNo(String str){
      Object[] options={ "yes", "no" };
      int foo=JOptionPane.showOptionDialog(null, 
             str,
             "Warning", 
             JOptionPane.DEFAULT_OPTION, 
             JOptionPane.WARNING_MESSAGE,
             null, options, options[0]);
       return foo==0;
    }

    String passwd;
    JTextField passwordField=(JTextField)new JPasswordField(20);

    public String getPassphrase(){ return null; }
    public boolean promptPassphrase(String message){ return true; }
    public boolean promptPassword(String message){
      Object[] ob={passwordField}; 
      int result=
        JOptionPane.showConfirmDialog(null, ob, message,
                                      JOptionPane.OK_CANCEL_OPTION);
      if(result==JOptionPane.OK_OPTION){
        passwd=passwordField.getText();
        return true;
      }
      else{ 
        return false; 
      }
    }
    public void showMessage(String message){
      JOptionPane.showMessageDialog(null, message);
    }
    final GridBagConstraints gbc = 
      new GridBagConstraints(0,0,1,1,1,1,
                             GridBagConstraints.NORTHWEST,
                             GridBagConstraints.NONE,
                             new Insets(0,0,0,0),0,0);
    private Container panel;
    public String[] promptKeyboardInteractive(String destination,
                                              String name,
                                              String instruction,
                                              String[] prompt,
                                              boolean[] echo){
      panel = new JPanel();
      panel.setLayout(new GridBagLayout());

      gbc.weightx = 1.0;
      gbc.gridwidth = GridBagConstraints.REMAINDER;
      gbc.gridx = 0;
      panel.add(new JLabel(instruction), gbc);
      gbc.gridy++;

      gbc.gridwidth = GridBagConstraints.RELATIVE;

      JTextField[] texts=new JTextField[prompt.length];
      for(int i=0; i<prompt.length; i++){
        gbc.fill = GridBagConstraints.NONE;
        gbc.gridx = 0;
        gbc.weightx = 1;
        panel.add(new JLabel(prompt[i]),gbc);

        gbc.gridx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weighty = 1;
        if(echo[i]){
          texts[i]=new JTextField(20);
        }
        else{
          texts[i]=new JPasswordField(20);
        }
        panel.add(texts[i], gbc);
        gbc.gridy++;
      }

      if(JOptionPane.showConfirmDialog(null, panel, 
                                       destination+": "+name,
                                       JOptionPane.OK_CANCEL_OPTION,
                                       JOptionPane.QUESTION_MESSAGE)
         ==JOptionPane.OK_OPTION){
        String[] response=new String[prompt.length];
        for(int i=0; i<prompt.length; i++){
          response[i]=texts[i].getText();
        }
    return response;
      }
      else{
        return null;  // cancel
      }
    }
  }
}

正常 sudo su 很好,但我想在 sudo su 之后运行多个命令,其中一些可能会提供信息。

  1. 使用用户登录服务器并使用 sudo
  2. sudo su - 用户 - 没有密码
  3. 执行一些命令

regards,

icr


第二种方法是您需要重定向并提供第二个密码。

尝试使用sudo -S -p.

过去我也遇到过同样的问题,但已经解决了。为了节省您的时间,这是我的代码:

SudoExec 类

public abstract class SudoExec {

private String mHost;
private static String passwd;
private SSHObserverItf mObserver = null;
protected boolean isForceStop = false;
protected boolean isAsIs = false;
protected Timer mTimer = null;



//default constructor
public SudoExec(String hostName,String userName,String password){
    setHost(userName+"@"+hostName);
    setPassword(password);
}

public void init(int timeToWait) {

    mTimer = new Timer();


    new Thread(){       
        public  void run(){
            execCMD();
        }           
    }.start();

    mTimer.doWait(timeToWait);

    isForceStop = true;
}


private void execCMD (){

    isForceStop = false;        

    try{
        JSch jsch=new JSch();  

        String host=getHost();


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

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



        // username and password will be given via UserInfo interface.
        UserInfo ui=new MyUserInfo();
        session.setUserInfo(ui);
        session.connect();

        String command=getCmd();

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

        ((ChannelExec)channel).setPty(true);

        if(isAsIs == true){
            ((ChannelExec)channel).setCommand(command);
            }
        else{
            ((ChannelExec)channel).setCommand("sudo -S -p '' " + command);
        }

        InputStream in=channel.getInputStream();
          OutputStream out=channel.getOutputStream();
          ((ChannelExec)channel).setErrStream(System.err);

          channel.connect();

          out.write((passwd+"\n").getBytes());
          out.flush();

        byte[] tmp=new byte[1024];
        while( isForceStop == false ){              
            while(in.available()>0 ){
                int i=in.read(tmp, 0, 1024);
                if(i<0)break;

                mObserver.onResponse((new String(tmp, 0, i)));

            }
            if(channel.isClosed()){
                mObserver.onResponse("exit-status: "+channel.getExitStatus());
                mTimer.doNotify();
                break;
            }


            try{Thread.sleep(100);}catch(Exception ee){}
        }

        mObserver.onResponse("close channel ... ");         
        channel.disconnect();
        mObserver.onResponse("close session ... ");
        session.disconnect();
    }
    catch(Exception e){
        System.out.println(e);
        mObserver.onErrorResponse(e.getMessage());
    }



}



public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{
    public String getPassword(){
        return passwd;
    }

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



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

    public void showMessage(String message){
    }

    @Override
    public String[] promptKeyboardInteractive(String arg0, String arg1,
            String arg2, String[] arg3, boolean[] arg4) {
        return null;
    }
}

public void setPassword(String password){
    passwd=password;
}

public void setHost(String hostname){
    mHost=hostname;
}

public String getPassword(){
    return passwd;
}


public String getHost(){
    return mHost;
}

protected abstract String getCmd();

public void setObserver(SSHObserverItf observer) {
    mObserver = observer;
}   
} 

SSHObserverItf 接口

public interface SSHObserverItf {
public void onResponse(String line);
public void onErrorResponse(String line);
}

SomeTask

public class SomeTask extends SudoExec implements SSHObserverItf{

private static String command = "";
private static String hostname = "";
private static String user = "";
private static String pass = "";
private static Boolean isError=false;

private static String wait = "300";



static public void main(String args[]) throws IOException, ParseException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {


    new SomeTask(hostname,user,pass);

    if (isError == true){
        System.out.println("Test failed");
    }   
    else{
        System.out.println("\nSucceeded to invoke command : " + command);
    }   

}



public CopyPeriodMergeToExternal(String hostName, String userName, String password) throws IOException, ParseException {

    super(hostName, userName, password);

    SSHObserverItf observer = this;

    super.setObserver(observer);

    super.init(Integer.parseInt(wait) * 1000);

}




@Override
protected String getCmd() {

    isAsIs = true;


    command="rm -f somescript.sh";


    System.out.println("Run followed command : " + command);

    return command;
}

@Override
public void onResponse(String line) {
    System.out.println(line);       
}

@Override
public void onErrorResponse(String line) {
    System.out.println(line);
    System.out.println("Error has occured");        
    isError = true;
}
}

主要部分在SudoExec类是:

public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{
    public String getPassword(){ //     <---
        return passwd;
    }

    public boolean promptYesNo(String str){
        return true;  //     <---
    }

希望它能解决您的问题

[EDIT]

收到第一个响应后,您可以关闭会话。

因此下一个命令以非超级用户身份启动。

我的建议是不要创建会话,而是运行每个命令sudo字首

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

关于 jsch 中 sudo su - 用户的想法 的相关文章

随机推荐

  • Ruby - 将数组映射到哈希图

    我有一个数组和一个返回给定值的函数 最终我想创建一个哈希映射 将数组的值作为键值 将 f key value 的结果作为值 是否有一种干净 简单的方法 例如类似于数组的each map 使用块来执行此操作 所以相当于 hsh 1 2 3 4
  • OpenCV 对白色像素进行分组

    我已经完成了艰苦的工作 将 MacBook 上的 iSight 摄像头变成了红外摄像头 对其进行了转换 设置了阈值等 现在得到的图像如下所示 alt text http www tommed co uk images opencv ir e
  • 将位图居中并重复边缘像素

    我正在尝试在我的 Android 应用程序中使用图像作为背景 如果图像不适合屏幕 我希望图像水平居中并垂直顶部 应通过重复边缘来填充剩余的屏幕区域 我的布局 xml 如下所示
  • 如何在“单击”槽中使用 QApplication::mouseButtons() 来判断鼠标按钮?

    我有一个 QMainWindow 并且想要处理来自其中较小的小部件 例如 tableview 的 单击 信号 最初我将信号连接到这个 QMainWindow 的插槽 这是最常见的方法 现在我需要判断单击了哪个鼠标按钮 并对左右按钮执行不同的
  • 我可以使用 System.Text.Json 通过私有构造函数反序列化 Json 吗?

    想知道是否可以拥有私有构造函数并使用新的 System Text Json 序列化器 public class MyModel public string Name get set public string Data get set pr
  • iOS:使用覆盖裁剪从 UIImagePickerController 相机抓取的静态图像

    我是 iOS 新手 过去一周我一直在网上寻找教程 例如 处理 Exif 图像 http niftybean com main blog 16 selecting regions from rotated exif images on iph
  • 计算数组的平均值

    我想使用数组计算平均数 我希望程序询问成绩的数量 然后我想输入成绩数字 在我想获得平均输出之后double 到目前为止 这是我的代码 public class Average public static void main String a
  • 使用 purrr::map 将多个数据帧写入 csv 文件 [重复]

    这个问题在这里已经有答案了 PROBLEM 我有一个数据帧列表 应将其作为 csv 文件写入磁盘 假设这是数据框列表 dfs lt list iris mtcars 什么没有奏效 我尝试像这样构建正确的文件名 但它不起作用 dfs gt m
  • 如何在AWS Lambda中模拟multiprocessing.Pool.map()?

    AWS Lambda 上的 Python 不支持multiprocessing Pool map 如记录在这另一个问题 https stackoverflow com questions 34005930 multiprocessing s
  • Breeze 使用 DB EntityType 管理 NODB EntityType

    我正在使用 Papa 的课程 CCJS 代码来研究 Breeze js 和 SPA 使用此代码 我尝试管理来自服务器的附加信息 但这不是来自 EntityFramework 的元数据中包含的实体 所以我创建了一个名为 Esto 的 NO D
  • 循环直到在表中找到 2 个特定值?

    我试图找到一种更聪明的方法来解决这个问题 这是与游戏相关的代码的摘录 它循环遍历每个背包的每个插槽 直到找到铲子和绳子 local continue local foundShovel foundRope for i 0 Container
  • 错误:无法安全地评估递归定义模块的定义

    我很想了解为什么会发生此错误以及解决该错误的最佳方法是什么 我有几个文件types ml and types mli它定义了一个变体类型value可以是许多不同的内置 OCaml 类型 float int list map set 等 由于
  • 使用 aes_256_cbc 密码加密时的默认 IV 是多少?

    我在一个文件中生成了一个随机 256 位对称密钥 用于使用 OpenSSL 命令行加密一些数据 稍后我需要使用 OpenSSL 库以编程方式解密该数据 我没有成功 我认为问题可能出在我正在使用 或没有使用 的初始化向量中 我使用以下命令加密
  • Codeigniter 3.0.4 在我的服务器上出现 404 Page Not Found 错误

    我是 codeigniter 的新手 在我的本地主机上开发一个网络应用程序后 我将我的网站上传到服务器上 然后导入我的数据库 之后我更改了database php文件中的数据库设置 并且我还更改了config php文件中的基本url 我得
  • 使用宏将word文档中的公式转换为图像

    我有这个宏可以将文档中的所有形状转换为图像 Dim i As Integer oShp As Shape For i ActiveDocument Shapes Count To 1 Step 1 Set oShp ActiveDocume
  • MVVM 层次结构中的更改通知

    假设在某个抽象 ViewModel 基类中 我有一个普通的旧属性 如下所示 public Size Size get return size set size value OnPropertyChanged Size 然后 我创建一个更具体
  • 将字符串转换为时间并在 golang 中解析

    我正在从文件中读取时间戳 并将该值分配给t t 2016 11 02 19 23 05 503705739 0000 UTC 当我尝试解析字符串时 time err time Parse 2016 11 02 19 18 57 149197
  • RxSwift 订阅块未调用

    我正在玩 RxSwift 但我被一个简单的玩具程序困住了 我的程序本质上包含一个模型类和一个视图控制器 该模型包含一个可观察对象 该可观察对象在异步网络调用之后在主队列上更新 视图控制器在 viewDidLoad 中订阅 AppDelega
  • php mysql pdo 连接不会在不破坏语句处理程序的情况下关闭

    我想在我的 php 脚本中显式关闭 mysql 连接以防止连接过多 使用以下代码 不加 sth 空 在上面的代码中 我无法关闭我的 mysql 连接 正如 PDO 文件中所述 要关闭连接 您需要通过确保销毁该对象 删除所有剩余的引用 为了确
  • 关于 jsch 中 sudo su - 用户的想法

    我在 jsch 中使用 sudo su 时遇到问题 下面是我的帖子 exec java package com test import com jcraft jsch import java awt import javax swing i