通过java以root用户身份登录到shell

通过java以root用户身份登录到shell,java,shell,Java,Shell,通过我的java程序,我可以登录到shell并执行cmds。 要登录,我提供主机名、用户名、密码和端口 我的问题是,然后我只需要通过发出su命令(以root身份登录)来更改为root用户,然后在密码提示下提供如下rootpassword support@mygateway:/tmp$ su Password: BusyBox v1.17.3 (2020-10-08 06:33:26 CEST) built-in shell (ash) Enter 'help' for a list of b

通过我的java程序,我可以登录到shell并执行cmds。 要登录,我提供主机名、用户名、密码和端口

我的问题是,然后我只需要通过发出su命令(以root身份登录)来更改为root用户,然后在密码提示下提供如下rootpassword

support@mygateway:/tmp$ su
Password:


BusyBox v1.17.3 (2020-10-08 06:33:26 CEST) built-in shell (ash)
Enter 'help' for a list of built-in commands.

root@mygateway:~#
我能够使用以下方法(已经可用)成功创建SSHShell并在没有根访问权限的情况下执行cmds。但是如何使用root访问权限登录

/**
 * Creates the SSHShell
 */
private SSHShellConnectionManager(String host, int port, String userName, String password)
        throws JSchException, IOException {
    Closure expectClosure = getExpectClosure();
    for (String linuxPromptPattern : new String[] { "\\>", "#", "~#", "~\\$",">"}) {
        try {
            Match match = new RegExpMatch(linuxPromptPattern, expectClosure);
            linuxPromptMatches.add(match);
        } catch (MalformedPatternException malformedEx) {
            throw new RuntimeException(malformedEx);
        }
    }
    JSch jsch = new JSch();
    this.session = jsch.getSession(userName, host, port);
    session.setPassword(password);
    Hashtable<String, String> config = new Hashtable<>();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.connect(60000);
    this.channel = (ChannelShell) session.openChannel("shell");
    //this.expect = new Expect4j(channel.getInputStream(), channel.getOutputStream());
    this.expect = new Expect4j(channel.getInputStream(), channel.getOutputStream());
    channel.connect();
}

/**
 * Executes a command on the remote host.
 *
 * @param command
 *            the command to be executed
 * @param getExitStatus
 *            return the exit status captured in the stdout
 * @param withErr
 *            capture the stderr as part of the output
 * @return the content of the remote output from executing the command
 * @throws Exception
 *             exception thrown
 */
public String executeCommand(String command, Boolean getExitStatus, Boolean withErr) throws Exception {
    String result = "";
    String resultErr = "";

    Channel channel = this.session.openChannel("exec");
    System.out.println("COMMAND TO EXECUTE ON ROUTER " + command);
    ((ChannelExec) channel).setCommand(command);
    InputStream commandOutput = channel.getInputStream();
    InputStream commandErr = ((ChannelExec) channel).getErrStream();
    channel.connect();
    byte[] tmp = new byte[4096];
    while (true) {
        while (commandOutput.available() > 0) {
            int i = commandOutput.read(tmp, 0, 4096);
            if (i < 0) {
                break;
            }
            result += new String(tmp, 0, i);
        }
        while (commandErr.available() > 0) {
            int i = commandErr.read(tmp, 0, 4096);
            if (i < 0) {
                break;
            }
            resultErr += new String(tmp, 0, i);
        }
        if (channel.isClosed()) {
            if (commandOutput.available() > 0) {
                continue;
            }
            if (getExitStatus) {
                result += "exit-status: " + channel.getExitStatus();
                if (withErr) {
                    result += "\n With error:\n" + resultErr;
                }
            }
            break;
        }
        try {
            Thread.sleep(100);
        } catch (Exception ee) {
        }
    }
    channel.disconnect();
    System.out.println("COMMAND RESPONSE :" + result);
    return result;
}



/**
 * Closes shell.
 */
public void close() {
    if (expect != null) {
        expect.close();
    }
    if (channel != null) {
        channel.disconnect();
    }
    if (session != null) {
        session.disconnect();
    }
}
/**
*创建SSHShell
*/
专用SSHShellConnectionManager(字符串主机、int端口、字符串用户名、字符串密码)
抛出JSCHEException、IOException{
Closure-expectClosure=getExpectClosure();
对于(字符串linuxPromptPattern:新字符串[]{“\\>”、“\\”、“\\”、“~\\”、“\\$”、“>”}){
试一试{
Match Match=newregexpmatch(linuxPromptPattern,expectClosure);
添加(匹配);
}捕获(格式错误模式异常格式错误索引){
抛出新的RuntimeException(畸形索引);
}
}
JSch JSch=新的JSch();
this.session=jsch.getSession(用户名、主机、端口);
session.setPassword(密码);
Hashtable config=新的Hashtable();
配置放置(“检查”、“否”);
session.setConfig(config);
会话连接(60000);
this.channel=(ChannelShell)session.openChannel(“shell”);
//this.expect=new-Expect4j(channel.getInputStream(),channel.getOutputStream());
this.expect=new-Expect4j(channel.getInputStream(),channel.getOutputStream());
channel.connect();
}
/**
*在远程主机上执行命令。
*
*@param命令
*要执行的命令
*@param getExitStatus
*返回标准输出中捕获的退出状态
*@param威瑟尔
*捕获stderr作为输出的一部分
*@通过执行命令返回远程输出的内容
*@抛出异常
*抛出异常
*/
公共字符串executeCommand(字符串命令、布尔getExitStatus、布尔Wither)引发异常{
字符串结果=”;
字符串resulter=“”;
Channel=this.session.openChannel(“exec”);
System.out.println(“在路由器上执行的命令”+命令);
((ChannelExec)channel).setCommand(command);
InputStream commandOutput=channel.getInputStream();
InputStream commandErr=((ChannelExec)channel.getErrStream();
channel.connect();
字节[]tmp=新字节[4096];
while(true){
while(commandOutput.available()>0){
inti=commandOutput.read(tmp,04096);
if(i<0){
打破
}
结果+=新字符串(tmp,0,i);
}
while(commandErr.available()>0){
inti=commandErr.read(tmp,04096);
if(i<0){
打破
}
resulter+=新字符串(tmp,0,i);
}
if(channel.isClosed()){
if(commandOutput.available()>0){
继续;
}
if(getExitStatus){
结果+=“退出状态:”+channel.getExitStatus();
如果(威瑟尔){
结果+=“\n出现错误:\n”+resultr;
}
}
打破
}
试一试{
睡眠(100);
}捕获(异常ee){
}
}
通道断开();
System.out.println(“命令响应:+结果”);
返回结果;
}
/**
*关闭外壳。
*/
公众假期结束(){
如果(预期!=null){
expect.close();
}
如果(通道!=null){
通道断开();
}
if(会话!=null){
session.disconnect();
}
}

尝试以下方法:

Channel channel = this.session.openChannel("exec");
((ChannelExec) channel).setCommand("su <<!"); // updated this line
channel.setInputStream(null);
OutputStream out = channel.getOutputStream();
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
((ChannelExec) channel).setPty(true);
channel.connect();
out.write((password + "\n!\n").getBytes()); // updated this line
out.flush();
Channel=this.session.openChannel(“exec”);

((ChannelExec)channel).setCommand("su您能以root用户身份运行代码吗?不,不能这样做。我要求代码按照此登录过程进入shell,首先作为普通登录,然后切换到root用户。Sean,很遗憾,sudo在该级别不可用。只有在进入root访问后,sudo命令才可用。@DivyaBhalla好的,我修改了答案,使用su而不是sudo。但是我没有测试任何一个,我是从