2017-10-13 184 views
1

我试图通过Java程序执行多个bash命令,该程序使用JSch连接到SSH。但sudo登录后,我无法执行任何bash命令。从我读过的sudo登录后,我们进入了一个子shell。我希望使用单个频道。对于下一步该怎么做我无能为力。sudo登录后使用Java JSch程序执行多个bash命令

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命令在一个单独的函数或文件?

回答

1

sudo不执行新的shell。但可能你的脚本start_shell.sh。您可能参考sudo su。也许你的脚本运行了su

无论如何,以提供命令给外壳,采用壳的标准输入馈送的命令:

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是任何其它命令,所以它实际上是相同的,为非常通用问题:
Providing input/subcommands to command executed over SSH with JSch

另请参阅Running command after sudo login,回答关于sudo su一个更通用的问题,没有一个叔叔使用一些未知的shell脚本。