2017-10-13 146 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腳本。