sudo登录后使用Java JSch程序执行多个bash命令 [英] Executing multiple bash commands using a Java JSch program after sudo login

查看:160
本文介绍了sudo登录后使用Java JSch程序执行多个bash命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过Java程序执行多个bash命令,该Java程序使用JSch连接到SSH.但是sudo登录后,我无法执行任何bash命令.从我阅读的内容来看,在sudo登录之后,我们进入了一个子shell.我希望使用一个渠道.我不知道下一步该怎么做.

I am trying to execute multiple bash commands through a Java program which connects to a SSH using JSch. But after sudo login, I am unable to execute any bash commands. From what I have read, after sudo login, we enter into a sub-shell. I wish to use a single channel. I am clueless as to what to do next.

ChannelExec chnlex=(ChannelExec) session.openChannel("exec");

InputStream in = chnlex.getInputStream();

BufferedReader br=new BufferedReader(new InputStreamReader(in));
chnlex.setCommand("sudo -u appbatch -H  /opt/apptalk/local/bin/start_shell.sh -c <<exit");

chnlex.connect();

System.out.println("channel connection done");

String msg=null;
while((msg=br.readLine())!=null){
  System.out.println(msg);
}

chnlex.disconnect();
System.out.println("channel disconnected");

有人还能告诉我如何在单独的函数或文件中编写这些bash命令吗?

Also could anyone tell me how to write these bash commands in a separate function or file?

推荐答案

sudo不执行新的Shell.但是可能您的start_shell.sh脚本可以.您可能参考了sudo su.也许您的脚本运行su?

The sudo does not execute a new shell. But probably your start_shell.sh script does. You probably refer to sudo su. Maybe your script runs the su?

无论如何,要向shell提供命令,请使用shell的标准输入来提供命令:

Anyway, to provide commands to the shell, feed the commands using shell's standard input:

ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand("sudo su");
channel.connect();
OutputStream out = channel.getOutputStream();
out.write(("command1\n").getBytes());
out.write(("command2\n").getBytes());
out.flush();


sudo/su和其他命令一样,因此实际上与一个非常通用的问题相同:
为使用JSch通过SSH执行的命令提供输入/子命令


The sudo/su are commands as any other, so it's actually the same as a very generic question:
Providing input/subcommands to command executed over SSH with JSch

另请参见在sudo登录后运行命令,该命令在sudo su上回答了一个更通用的问题,没有明确的用法一些未知的shell脚本.

Also see Running command after sudo login, which answers a more generic question on sudo su, without an unclear use of some unknown shell script.

这篇关于sudo登录后使用Java JSch程序执行多个bash命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆