Getting files in a directory using java API from Kubernetes pod - kubernetes

I am trying to get the list of files in a pod directory using this code this
Code I tried:
import io.kubernetes.client.Exec;
..........
Exec exec = new Exec();
boolean tty = System.console() != null;
String[] command = {"/bin/sh","-c", "ls", "/var/log"};
final Process proc =
exec.exec(namespace, podName, command , false, tty);
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
proc.waitFor();
in.close();
but this always output "data", instead of the files in the dir. How can i make it work. If. i try this using kubectl command line this works.

Related

How delete a channel with a specific command?

I made a code that closes the specific channel that you write the command in.
This is my code that redirects each command to its own folder and runs the code in it.
events\message.js
module.exports = (client, message) => {
// Ignore all bots
if (message.author.bot) return;
// Ignore messages not starting with the prefix (in config.json)
if (message.content.indexOf(client.config.prefix) !== 0) return;
// Our standard argument/command name definition.
const args = message.content.slice(client.config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
// Grab the command data from the client.commands Enmap
const cmd = client.commands.get(command);
// If that command doesn't exist, silently exit and do nothing
if (!cmd) return;
// Run the command
cmd.run(client, message, args);
};
And my code that deletes the channel the command is written in.
const ms = require('ms');
const Discord = require('discord.js');
const client = new Discord.Client();
exports.run = async (client, message, args) => {
if (!message.member.permissions.has("ADMINISTRATOR", "Ticket Admin"))
return message.reply('You need a specify permission to setup a ticket!');
if (message.author.bot) return;
const msgargs = message.content.slice(client.config.prefix.length).trim().split(/ +/g);
const command = msgargs.shift().toLowerCase();
if(command == "close") {
if(!message.channel.name.includes("ticket-")) return message.channel.send("You cannot use that here!")
message.channel.delete();
}
};
but the problem is that it doesn't want to delete the channel with "ticket-" in his name and it's the channel that the command was written in.
any help will be appreciated.
your file name isn't the same ass your command.
so when you send the command $ticket-close it runs the ticket-close file but in the ticket-close file, you are verifying if the command was closed and not so it end it.
you need to have the same name for your file code and your command to verify,(if(command == "close")).
or just don't check what was the command.

Execute linux command on Centos using dotnet core

I'm running a .NET Core Console Application on CentOS box. The below code is executing for normal command like uptime, but not executing for lz4 -dc --no-sparse vnp.tar.lz4 | tar xf - Logs.pdf:
try
{
var connectionInfo = new ConnectionInfo("server", "username", new PasswordAuthenticationMethod("username", "pwd"));
using (var client = new SshClient(connectionInfo))
{
client.Connect();
Console.WriteLine("Hello World!");
var command = client.CreateCommand("lz4 -dc --no-sparse vnp.tar | tar xf - Logs.pdf");
var result = command.Execute();
Console.WriteLine("yup ! UNIX Commands Executed from C#.net Application");
Console.WriteLine("Response came form UNIX Shell" + result);
client.Disconnect();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Expected output is Logs.pdf file needs to be extracted and saved in the current location. Can someone correct me where im
If application is running on Linux machine then you can try this also:
string command = "write your command here";
string result = "";
using (System.Diagnostics.Process proc = new System.Diagnostics.Process())
{
proc.StartInfo.FileName = "/bin/bash";
proc.StartInfo.Arguments = "-c \" " + command + " \"";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.Start();
result += proc.StandardOutput.ReadToEnd();
result += proc.StandardError.ReadToEnd();
proc.WaitForExit();
}
return result;

Any way to access a NFS from Bluemix runtime?

I need to push an application to Bluemix that requires access to a remote file system via NFS.
I haven't found any NFS service. Existing Object Store services use Swift API and the application requires native file system access, not other kind of APIs.
I tried to execute "mkdir" and "mount" commands from app initialization but it seems there are restrictions for such executions from the user that runs the runtime. I got return codes that mean errors.
So I run out of ideas. Do you have any suggestion or idea to explore?
I think Dockers could be an option (haven't explored yet if I can mount the nfs file system) but currently it is in Beta, so no production ready.
Thanks!
NFS is not supported, however Cloud Foundry now supports FUSE, which is a pretty close alternative to NFS.
To take advantage of FUSE you need to use the cflinuxfs2 stack.
cflinuxfs2 is a new stack that supports FUSE, see below. Cloud Foundry recently added FUSE support, see here for more info.
name description
lucid64 Ubuntu 10.04
cflinuxfs2 Ubuntu 14.04.2 trusty
When you push your app you need to use the -s option, example below.
cf push myappname -s cflinuxfs2.
Update:
The poster posted a solution to his another question on how to do this. I have pasted it below...
Ok, finally I found the reason of the issue with the help of team colleagues. Problem was with permissions of the private ssh key. It has to be 600 and by default it was 644 after the cf push.
So here it is the final code (quick and dirty) that worked, just in case it can be useful to others...
1.- Include into the app the private key and the known_hosts files.
2.- Push the app adding "-s cflinuxfs2" parameter.
3.- Execute at runtime startup some code like this:
String s = null;
Process p = null;
BufferedReader br = null;
try
{
p = Runtime.getRuntime().exec("mkdir -p /home/vcap/misc");
br = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((s = br.readLine()) != null)
System.out.println("line: " + s);
p.waitFor();
System.out.println ("#### Executing command mkdir with exit: " + p.exitValue());
p.destroy();
br.close();
p = Runtime.getRuntime().exec("chmod 600 /home/vcap/app/wlp/usr/servers/defaultServer/apps/myapp.ear/cloud.key");
br = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((s = br.readLine()) != null)
System.out.println("line: " + s);
p.waitFor();
System.out.println ("#### Executing command chmod with exit: " + p.exitValue());
p.destroy();
br.close();
p = Runtime.getRuntime().exec("chmod 600 /home/vcap/app/wlp/usr/servers/defaultServer/apps/myapp.ear/known_hosts");
br = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((s = br.readLine()) != null)
System.out.println("line: " + s);
p.waitFor();
System.out.println ("#### Executing command chmod with exit: " + p.exitValue());
p.destroy();
br.close();
p = Runtime.getRuntime().exec("sshfs ibmcloud#129.41.133.34:/home/ibmcloud /home/vcap/misc -o IdentityFile=/home/vcap/app/wlp/usr/servers/defaultServer/apps/myapp.ear/cloud.key -o StrictHostKeyChecking=yes -o UserKnownHostsFile=/home/vcap/app/wlp/usr/servers/defaultServer/apps/myapp.ear/known_hosts -o idmap=user -o compression=no -o sshfs_debug");
br = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((s = br.readLine()) != null)
System.out.println("line: " + s);
p.waitFor();
System.out.println ("#### Executing command sshfs with exit: " + p.exitValue());
p.destroy();
br.close();
p = Runtime.getRuntime().exec("ls -l /home/vcap/misc");
br = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((s = br.readLine()) != null)
System.out.println("line: " + s);
p.waitFor();
System.out.println ("#### Executing command ls with exit: " + p.exitValue());
p.destroy();
br.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
finally
{
try
{
if(br != null)
br.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
This snippet should create a folder, mount a remote file system into that folder and list the content of the remote file system.

AuthTicketsHelper.getTicket() returns null

My company uses Perforce for version control and I'm writing software that automates use of Perforce using p4java. I'm running into a problem where my code can't connect to the Perforce server even though I am passing in valid information to use the p4tickets file on my computer.
First, I logged on to perforce to get a p4ticket by running "p4 login", which created the ~/.p4tickets file. But when I run my program that uses p4java to connect using the p4ticket file, it returns null.
AuthTicket auth = AuthTicketsHelper.getTicket(username, serverAddr, p4TicketsFilePath);
// auth == null
I've double checked that the username I'm passing in matches the $P4USER environment variable I had when I used "p4 login", as well as that serverAddr matched the host name that was referenced by my $P4PORT. The p4TicketsFilePath also exists and is the correct path to the .p4tickets file which has my ticket, which is not expired. I'm looking for the reason why getTicket still returns null.
You can debug this issue by copying the source code from AuthTicketsHelper and insert print statements. here's my logger:
private static final Logger logger = LoggerFactory.getLogger(YourClass.class);
(if you don't have a logger, you can do System.out.println() with String.format("... %s ... %s") instead.) Then, copy in this code.
AuthTicket auth;
{
AuthTicket foundTicket = null;
String serverAddress = serverAddr;
String ticketsFilePath = p4TicketsFilePath;
String userName = username;
if (serverAddress != null) {
logger.info("P4TICKETS 1");
if (serverAddress.indexOf(':') == -1) {
serverAddress += "localhost:" + serverAddress;
logger.info("P4TICKETS 2");
}
for (AuthTicket ticket : AuthTicketsHelper.getTickets(ticketsFilePath)) {
logger.info("P4TICKETS 3 {} - {} - {} - {}", serverAddress, ticket.getServerAddress(), userName, ticket.getUserName());
if (serverAddress.equals(ticket.getServerAddress())
&& (userName == null || userName.equals(ticket
.getUserName()))) {
logger.info("P4TICKETS 4");
foundTicket = ticket;
break;
}
}
logger.info("P4TICKETS 5");
}
auth = foundTicket;
}
Follow the code path in the output to see what went wrong. In my case, the server name was a hostname in the code, but my .p4tickets file had an IP address for the server name.

error in build to process builder in java

I have devloped myself tagger and I want to host on the web. my server is based on jsp. But This tagger is based on svmtool and it has been written in Perl script. That's why, I have created one ".java" file. In this file I've created Processor builder and via the Runtime.getRuntime().exec through this process I am calling this file. It is working but it doesn't show my output. Plz help to solve this issue. For the better under standing below I am giving my java code and also given last line of output/stop the process:
import java.io.*;
public class ExeCommand { String outS = "", errS="";
try {
// run the Unix "type your terminal command" command
System.out.println ("Running tagger!");
String command = "perl /home/svmtool_v1.3.2/bin/SVMTagger.pl -V 4 -S LRL /home/svmtool_v1.3.2/models/ih/IN < /home/tomcat4.1.40/webapps/pos/textfile/tests.txt > /home/tomcat4.1.40/webapps/pos/textfile/output.txt"; Process p = Runtime.getRuntime().exec(command);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
// read the output from the command
System.out.println("It will take time so keep the patience:\n" + command);
System.out.println ("First error line: " + stdError.readLine());
// read any errors from the attempted command
System.out.println("Please check your command (if any):\n");
while ((errS = stdError.readLine()) != null) {
System.out.println("Error:\t" + errS);
}
stdError.close();
System.out.println ("First output line: " + stdInput.readLine());
while ((outS = stdInput.readLine()) != null) {
System.out.println("Output:\t" + outS);
}
stdInput.close();
System.out.println("Finished!");
}
catch (Exception e) {
System.out.println("found exception: " + e);
e.printStackTrace();
//System.exit(-1);
}
System.out.println("Finished all!");
}
}
After this nothing doing/ last output shows in terminal:
TAGGING < DIRECTION = left-to-right then right-to-left >
First, your perl script redirects its standard output to a file (
/home/tomcat4.1.40/webapps/pos/textfile/output.txt). So there is no way, you can capture standard output in Java.
Instead, you can use tee command which can write the output to both your output file and the standard output. Now, this can be captured in Java.
Second, use ProcessBuilder instead of Runtime. Process Builder is more flexible and gives you options to capture the standard output / input / error.
ProcessBuilder p = new ProcessBuilder();
p.inheritIO(); // Sets the source and destination for subprocess standard I/O to be the same as those of the current Java process.
p.command("perl", "somescript.pl");
p.start();
As I wrote here:
Sorry for the harsh words, but your code is a disaster. No compiler do something with it.
I have made no further tweaks to your code, I have the code modified so that it works at least:
package stackoverflow;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ExeCommand {
/**
*
* run the Unix "type your terminal command" command
*
* #param args
*/
public static void main(String[] args) {
System.out.println("Running tagger!");
String command = "perl /home/svmtool_v1.3.2/bin/SVMTagger.pl -V 4 -S LRL /home/svmtool_v1.3.2/models/ih/IN < /home/tomcat4.1.40/webapps/pos/textfile/tests.txt > /home/tomcat4.1.40/webapps/pos/textfile/output.txt";
// String command = "ls -og";
Process p = null;
try {
p = Runtime.getRuntime().exec(command);
} catch (IOException e) {
e.printStackTrace();
}
// read the output from the command
System.out.println("It will take time so keep the patience:\n" + command);
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
try {
System.out.println(": " + stdError.readLine());
} catch (IOException e) {
e.printStackTrace();
}
// read any errors from the attempted command
System.out.println("Please check your command (if any):\n");
try {
String errS = "";
while ((errS = stdError.readLine()) != null) {
System.out.println("Error:\t" + errS);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
stdError.close();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
try {
System.out.println("First output line: " + stdInput.readLine());
} catch (IOException e) {
e.printStackTrace();
}
try {
String outS = "";
while ((outS = stdInput.readLine()) != null) {
System.out.println("Output:\t" + outS);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
stdInput.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Finished!");
}
}
Replace the lines 19 and 20
String command = "perl /home/svmtool_v1.3.2/bin/SVMTagger.pl -V 4 -S LRL /home/svmtool_v1.3.2/models/ih/IN < /home/tomcat4.1.40/webapps/pos/textfile/tests.txt > /home/tomcat4.1.40/webapps/pos/textfile/output.txt";
// String command = "ls -og";
with
// String command = "perl /home/svmtool_v1.3.2/bin/SVMTagger.pl -V 4 -S LRL /home/svmtool_v1.3.2/models/ih/IN < /home/tomcat4.1.40/webapps/pos/textfile/tests.txt > /home/tomcat4.1.40/webapps/pos/textfile/output.txt";
String command = "ls -og";
Then you get this output:
Running tagger!
It will take time so keep the patience:
ls -og
: null
Please check your command (if any):
First output line: insgesamt 12
Output: drwxrwxr-x 3 4096 Mai 23 20:51 bin
Output: drwxrwxr-x 3 4096 Apr 26 15:49 src
Output: -rw-rw-r-- 1 28 Apr 26 15:51 test
Finished!