2017-08-28 72 views
-1

使用jsch我已登錄到遠程主機以不同的用戶身份執行腳本。 必須使用「exec」通道。 當前Unix動作我要做的是: 1)須藤蘇 - 2)運行腳本作爲用戶的Java Jsch sudo並執行腳本

我怎樣才能運行此命令「須藤蘇 - 」,然後在相同的信道


執行腳本更新了代碼註釋,我試着發送下面兩個命令作爲輸入。它運行在循環中,我沒有看到它正在執行。下面TW是在數組列表發送的輸入 「命令」 須藤蘇 - testusr /home/testusr/start.sh

ChannelShell channel = null; 

List<String> result = new ArrayList<String>(); 
InputStream inStream = null; 
OutputStream outStream = null; 

PipedOutputStream pOutStream = null; 
PipedInputStream pInStream = null; 
try { 
    inStream = new PipedInputStream(); 
    pOutStream = new PipedOutputStream((PipedInputStream) inStream); 

    outStream = new PipedOutputStream(); 
    pInStream = new PipedInputStream((PipedOutputStream) outStream); 
    channel = (ChannelShell) session.openChannel("shell"); 
    // channel.setPty(true); 
    channel.setInputStream(inStream); 
    channel.setOutputStream(outStream); 
    channel.connect(); 
    BufferedReader bfs = null; 

    for (String command : commands) { 
     LOGGER.info("Executing command {} ", command); 
     pOutStream.write((command.concat("\n")).getBytes()); 
    } 
    LOGGER.info(" exit status {}", channel.getExitStatus()); 
    bfs = new BufferedReader(new InputStreamReader((inStream))); 
    if (channel.getExitStatus() != 0) { 

     result.add("ERROR"); 
    } 
    String line; 
    byte[] bt = new byte[1024]; 
    while (true) { 
     while (inStream.available() > 0) { 
      int i = inStream.read(bt, 0, 1024); 
      if (i < 0) { 
       break; 
      } 
      LOGGER.info("result {}", new String(bt, 0, i)); 
     } 
     if (channel.isClosed()) { 
      LOGGER.info("exit status {}", channel.getExitStatus()); 
      break; 
     } 
     try { 
      Thread.sleep(1000); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

2ned編輯

for (String command : commands) { 
       OutputStream out = channel.getOutputStream(); 
       out.write((command.concat("\n")).getBytes()); 
       out.flush(); 
       InputStream in = channel.getInputStream(); 
       byte[] tmp = new byte[1024]; 
       while (true) { 
        while (in.available() > 0) { 
         int i = in.read(tmp, 0, 1024); 
         if (i < 0) { 
          break; 
         } 
         LOGGER.info("Output stream execution {}", new String(
           tmp, 0, i)); 
        } 
        if (channel.isClosed()) { 
         LOGGER.info("Executing exit status {}", 
           channel.getExitStatus()); 
         break; 
        } 
       } 
      } 
+0

可能重複的[JSch - 如何發出命令,因爲我已經切換到用戶](https://stackoverflow.com/questions/41097999/jsch-how-to-issue-commands-as-the-user-我已經切換到) –

+1

或[在sudo登錄後運行命令](https://stackoverflow.com/q/41670999/850848)和zillions others - >在發佈之前將您的問題提交到Google!根據這個建議可以使用 –

+0

。 ((ChannelExec)channel).setCommand(「sudo -S -p''」+ command);我如何以用戶身份通過​​運行,在會話中我將作爲登錄用戶,現在我已切換sudo su - star –

回答

0

你真的需要做sudo su -? 如果您的腳本是bash腳本,您可以撥打sudo bash your_script.sh

這應該適用於任何更改解釋器的腳本類型。

su -恢復用戶環境,如果你真的需要它,你的腳本可能會以~/.bash_profile爲例。