How to execute `docker exec -it netvertex bash` by Java Program - java

How to execute docker exec -it netvertex bash by Java Program.
By this i am trying to execute but not working
public void execute(String command) {
try {
System.out.println("===========>" + command);
Channel channel1 = session.openChannel("exec");
((ChannelExec) channel1).setPty(true);
((ChannelExec) channel1).setCommand(command);
// X Forwarding
// channel.setXForwarding(true);
//channel.setInputStream(System.in);
channel1.setInputStream(null);
//channel.setOutputStream(System.out);
//FileOutputStream fos=new FileOutputStream("/tmp/stderr");
//((ChannelExec)channel).setErrStream(fos);
((ChannelExec) channel1).setErrStream(System.err);
InputStream in1 = channel1.getInputStream();
channel1.connect();
byte[] tmp1 = new byte[1024];
while (true) {
while (in1.available() > 0) {
int i = in1.read(tmp1, 0, 1024);
if (i < 0) break;
System.out.print(new String(tmp1, 0, i));
}
if (channel1.isClosed()) {
if (in1.available() > 0) continue;
System.out.println("exit-status: " + channel1.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
}
}
} catch (Exception e) {
}
}
By above code my other Linux command are working. But docker exec it not working.
And the other option i tried
try {
String host = "root#10.121.21.224";
String passwd = "root#10";
Terminal exec = new Terminal(pageUiUtils);
exec.loginSSH(host, passwd);
String[] command = {"docker", "exec", "-it", "netvertex", "bash"};
ProcessBuilder pb = new ProcessBuilder(command);
pb.inheritIO();
Process proc = pb.start();
InputStream is = proc.getInputStream();
OutputStream os = proc.getOutputStream();
BufferedReader reader
= new BufferedReader(new InputStreamReader(is));
BufferedWriter writer
= new BufferedWriter(new OutputStreamWriter(os));
writer.write("pwd");
writer.flush();
String line = "";
while ((line = reader.readLine()) != null) {
System.out.print(line + "\n");
}
exec.execute("docker exec -it netvertex bash");
pageUiUtils.pause(1000);
exec.execute("pwd");
//proc.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
by above code also showing error that
The input device is not a TTY

Related

How to execute a command after exception

I have a 2d array someArray with some system commands. Let's say I have these commands -
ls
lol (invalid command)
pwd
the second command will trigger an IOException and the third command does not get executed. How do I make sure that the last command will get executed regardless of any exception? Any advice?
for ( int i = 0; i < someArray.length; i++ ) {
try{
ProcessBuilder pb = new ProcessBuilder(someArray[index]);
pb.redirectErrorStream(true);
Process process = pb.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ( (line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}catch(IOException e){
System.err.println( "Command not found" );
}
}
Instead of using IOException in the catch use the general class Exception which will catch any kind of Exception thrown
for ( int i = 0; i < someArray.length; i++ ) {
try{
ProcessBuilder pb = new ProcessBuilder(someArray[i]);
pb.redirectErrorStream(true);
Process process = pb.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ( (line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
} catch (IOException e) {
System.err.println( "Command not found" );
} catch (Exception e) {
System.err.println("Unexpected Exception caught to continue other commands");
e.printStackTrace();
}
}
edit: fixed to report the unexpected error

Send command Line to Android using Java

I got a server applicatino in java in my computer and multiples virtual machines with Android OS. I would like execute the following command line in VM:
su am start -n <PackageName>/ <OtherAtribute>
Look what I already have:
The call:
cvb.accessShell(ip, 5555);
cvb.startApp(appPackageName, mainPath);
THe functions accessShell and startApp:
cvb.accessShell(ip, 5555);
cvb.startApp(appPackageName, mainPath);
public void accessShell(String ip, int port) {
String script = "/home/decom/1018119/adt-bundle-linux-x86_64-20131030/sdk/platform-tools/adb -s "
+ ip + ":" + port + " shell";
System.out.println(script);
try {
System.out.println("Get in");
Runtime.getRuntime().exec(script); // stuck here
System.out.println("Get out");
} catch (IOException e) {
System.out.println("Cant connect to shell");
}
}
public void startApp(String appPackageName, String mainPath) {
String script = "su am start -n " + appPackageName + "/" + mainPath;
System.out.println(script);
try {
Runtime.getRuntime().exec(script);
} catch (IOException e) {
System.out.println("Cant connect to shell");
}
}
The problem is (like the comments on code): My code stuck at shell access and when I run the exactly command by terminal, it works ok.
I tried read the output and nothing is printed.
Try this
Process p = Runtime.getRuntime().exec("ls -la");
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
so, in your code:
try {
System.out.println("Get in");
Process p = Runtime.getRuntime().exec(script);
System.out.println("Get out");
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Cant connect to shell");
}

No output from Runtime.getRuntime().exec("ls")

ping and date returned output, but it's not returning anything from "ls" or "pwd". What I want to do ultimately is run an SSH command. Any idea what I am missing below?
//Works and shows the output
executeCommand("ping -c 3 " + "google.com");
//Works and shows the output
executeCommand("date");
//Does not work. No output
executeCommand("sudo ls");
//Does not work. No output
executeCommand("ls");
private void executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
Log.d("Output", "Output: " + output.toString());
}
I have two solutions
first solution (you need Java 7):
...
ProcessBuilder pb = new ProcessBuilder("ls");
pb.redirectOutput(Redirect.INHERIT);
Process p = pb.start();
second solution:
Process p=Runtime.getRuntime().exec("ls");
InputStream is = p.getInputStream();
int c;
StringBuilder commandResponse = new StringBuilder();
while( (c = is.read()) != -1) {
commandResponse.append((char)c);
}
System.out.println(commandResponse);
is.close();

java write netstat in cmd

My goal is to print all the internet connections on my computer. When i type netstat on cmd i get the internet connections list. I wanted to do the same in java, automatically.
My code:
Runtime runtime = Runtime.getRuntime();
process = runtime.exec(pathToCmd);
byte[] command1array = command1.getBytes();//writing netstat in an array of bytes
OutputStream out = process.getOutputStream();
out.write(command1array);
out.flush();
out.close();
readCmd(); //read and print cmd
But with this code i get C:\eclipse\workspace\Tracker>Mais? instead of the list of connections. Obviously i'm working with eclipse, in windows 7. What am I doing wrong? I've looked in similar topics but i cound't find whats wrong. Thank you for the answers.
EDIT:
public static void readCmd() throws IOException {
is = process.getInputStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
Try this : I was able to create a file in my default temporary directory with all the connections
final String cmd = "netstat -ano";
try {
Process process = Runtime.getRuntime().exec(cmd);
InputStream in = process.getInputStream();
File tmp = File.createTempFile("allConnections","txt");
byte[] buf = new byte[256];
OutputStream outputConnectionsToFile = new FileOutputStream(tmp);
int numbytes = 0;
while ((numbytes = in.read(buf, 0, 256)) != -1) {
outputConnectionsToFile.write(buf, 0, numbytes);
}
System.out.println("File is present at "+tmp.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace(System.err);
}
You can also use an instance of java.util.Scanner to read the output of the command.
public static void main(String[] args) throws Exception {
String[] cmdarray = { "netstat", "-o" };
Process process = Runtime.getRuntime().exec(cmdarray);
Scanner sc = new Scanner(process.getInputStream(), "IBM850");
sc.useDelimiter("\\A");
System.out.println(sc.next());
sc.close();
}
final String cmd = "netstat -ano";
try {
Process process = Runtime.getRuntime().exec(cmd);
InputStream in = process.getInputStream();
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace(System.err);
} finally{
in = null;
isr = null;
br = null;
}

Writing data to InputStream of grep program invoked in java

I'm trying to process data obtained from a run of diff to an instance of GNU grep in a java program. I've managed to get the output of diff using the Process object's outputStream, but I'm currently having programs sending this data to the standard input of grep (through another Process object created in Java). Running Grep with the input only returns status code 1. What am I doing wrong?
Below is the code I have so far:
public class TestDiff {
final static String diffpath = "/usr/bin/";
public static void diffFiles(File leftFile, File rightFile) {
Runtime runtime = Runtime.getRuntime();
File tmp = File.createTempFile("dnc_uemo_", null);
String leftPath = leftFile.getCanonicalPath();
String rightPath = rightFile.getCanonicalPath();
Process proc = runtime.exec(diffpath+"diff -n "+leftPath+" "+rightPath, null);
InputStream inStream = proc.getInputStream();
try {
proc.waitFor();
} catch (InterruptedException ex) {
}
byte[] buf = new byte[256];
OutputStream tmpOutStream = new FileOutputStream(tmp);
int numbytes = 0;
while ((numbytes = inStream.read(buf, 0, 256)) != -1) {
tmpOutStream.write(buf, 0, numbytes);
}
String tmps = new String(buf,"US-ASCII");
inStream.close();
tmpOutStream.close();
FileInputStream tmpInputStream = new FileInputStream(tmp);
Process addProc = runtime.exec(diffpath+"grep \"^a\" -", null);
OutputStream addProcOutStream = addProc.getOutputStream();
numbytes = 0;
while ((numbytes = tmpInputStream.read(buf, 0, 256)) != -1) {
addProcOutStream.write(buf, 0, numbytes);
addProcOutStream.flush();
}
tmpInputStream.close();
addProcOutStream.close();
try {
addProc.waitFor();
} catch (InterruptedException ex) {
}
int exitcode = addProc.exitValue();
System.out.println(exitcode);
inStream = addProc.getInputStream();
InputStreamReader sr = new InputStreamReader(inStream);
BufferedReader br = new BufferedReader(sr);
String line = null;
int numInsertions = 0;
while ((line = br.readLine()) != null) {
String[] p = line.split(" ");
numInsertions += Integer.parseInt(p[1]);
}
br.close();
}
}
Both leftPath and rightPath are File objects pointing to the files to be compared.
Just a couple of hints, you could:
pipe the output of diff directly into grep: diff -n leftpath rightPath | grep "^a"
read the output file from grep instead of stdin: grep "^a" tmpFile
use ProcessBuilder to get your Process where you can easily avoid a blocking process because you're not reading stderr by using redirectErrorStream

Categories

Resources