如果您已經知道軟件二進制文件的名稱(通常與進程名稱相同),則可以使用which
命令。
您可以在bash測試/殼 其中火狐 在/ usr/bin中/火狐
此外,我可以爲您提供寫在bash輸出讀數的C#示例:
字符串輸出=字符串。空的;
string output = string.Empty;
try
{
// Sets up our process, the first argument is the command
// and the second holds the arguments passed to the command
ProcessStartInfo ps = new ProcessStartInfo("bash");
ps.Arguments = "-c 'firefox'";
ps.UseShellExecute = false;
// Redirects the standard output so it reads internally in out program
ps.RedirectStandardOutput = true;
// Starts the process
using (Process p = Process.Start(ps))
{
// Reads the output to a string
output = p.StandardOutput.ReadToEnd();
// Waits for the process to exit must come *after* StandardOutput is "empty"
// so that we don't deadlock because the intermediate kernel pipe is full.
p.WaitForExit();
}
}
catch
{
// TODO manage errors
}
如果bash的輸出是多行的管道,你可以預先篩選它grep命令:
ps.Arguments = "-c 'cpuid | grep MySearchTerm'";
編輯1:回覆評論
的主要問題是需要「管理」權限的軟件安裝。 我試圖創建一個解決辦法,但下面的行打破了所有代碼:
process = Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","'echo RIadminXsrv1 | sudo -S apt-get install telnet -qy'"});
而在終端以下命令將實際嘗試安裝遠程登錄(你可能需要用戶插入/etc/sudoers重現它在你的電腦上)。
/bin/echo myUserPass | /usr/bin/sudo -S /usr/bin/apt-get install telnet -qy
在java中它會簡單地打印(echo
輸出)命令的剩餘部分:
myUserPass | /usr/bin/sudo -S /usr/bin/apt-get install telnet -qy
這是因爲我們只是執行了大量的參數/bin/echo
命令。 我認爲這是可能的實際運行整套使用bash命令的:
bash -c '/bin/echo myUserPass | /usr/bin/sudo -S /usr/bin/apt-get install telnet -qy'
..但它不是,因爲bash -c '..'
在Java中並不像它應該工作。它說-c'echo ...'腳本文件無法找到,所以我想它誤解了-c選項。 順便說一句,我從來沒有在單聲道C#這種問題。
這裏是整個片段:
package javaapplication1;
import java.io.*;
public class JavaApplication1 {
public static void main(String[] args) {
Process process;
String softwareToCheck = "telnet"; // Change here
try
{
if(!_softwareExists(softwareToCheck))
{
System.out.println("Installing missing software..");
process = Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","'echo RIadminXsrv1 | sudo -S apt-get install telnet -qy'"});
try
{
process.waitFor();
}
catch(InterruptedException e)
{
System.out.println(e.getMessage());
}
if(!_softwareExists(softwareToCheck))
{
System.out.println("Software is still missing!");
}
}
else
{
System.out.println("Software is installed!");
}
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
private static boolean _softwareExists(String binaryName) throws IOException
{
String line;
ProcessBuilder builder;
BufferedReader reader;
Process process;
builder = new ProcessBuilder("/usr/bin/which", binaryName);
builder.redirectErrorStream(true);
process = builder.start();
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
try
{
process.waitFor();
}
catch(InterruptedException e) {
System.out.println(e.getMessage());
}
while ((line = reader.readLine()) != null)
{
break; // Reads only the first line
}
return (line != null && !line.isEmpty());
}
}
我知道如何讀/寫過程,但你能告訴我如何檢查像ssh這樣的工具嗎? – Johnydep
..但是_softwareExists(String binaryName)函數對於請求的第一部分是可以的。 – Salaros
感謝您的答案 – Johnydep