connecting the setInputStream and setOutputStream of the JSch to jTextField's - shell

I am new to java and i need help.
I use the jsch libraries to create a SHH connection to a remote linux machine. In the next code, given from a tutorial of the JSCH creator, you can see it is implemented shell communication, it is a direct communication from a cmd window. You enter a command from the cmd window and you get aback the results in the cmd window.
String user = "username";
String host = "hostname";
session session=jsch.getSession(user, host, 22);
String passwd = JOptionPane.showInputDialog("Enter password");
session.setPassword(passwd);
Channel channel=session.openChannel("shell");
session.connect();
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
How i can connect the next two lines to jTextField1 and jTextField2. To give an example i want to sen the command from the jTextField1 and to get the results from the jTextField2.
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
Thank you in advanced

Instead of System.in you can give your desired stream .For example
String ls = "ls \n"; // here i am passing a string to stream, you can pass as you desire
InputStream in = new ByteArrayInputStream(ls.getBytes("UTF-8"));
channel2.setInputStream(in);//you passed the string as input
ByteArrayOutputStream out = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(out);
channel2.setOutputStream(ps);
String result = out.toString();//here we get output to a string which you can add to your file.
This is one option There may be better ways.

Related

how do I extract attachments from integrity PTC items using Java API

I'm trying to extract attachments from integrity PTC items that are on a linux server from my Windows PC but it keeps giving me errors. The exact same command worked in command line
IntegrationPoint integrationPoint =
IntegrationPointFactory.getInstance().createIntegrationPoint(
hostName,
port,
APIVersion.API_4_16);
System.out.println("Start download Attachment");
// Start the Integrity client.
integrationPoint.setAutoStartIntegrityClient(true);
// Connect to the Integrity server.
Session session = integrationPoint.createSession(username, password);
Command command = new Command(Command.IM, "extractattachments");
command.addOption(new Option("issue", itemID));
command.addOption(new Option("field", "Text Attachments"));
command.addSelection(attachment);
Response response = session.createCmdRunner().execute(command);
I'm getting an error that says
Error encountered trying to get the next name: File paths must be rooted in /export/home/ptc/Integrity/ILMServer11.0/data/tmp: Current file is /export/home/ptc/Integrity/ILMServer11.0/bin/C:\Workspace\document/bear.jpg
Anytime I add cwd to the command it just appends whatever I put after the /bin/ It says it's a InvalidCommandSelectionException and a CommandException
You're missing the outputFile option on the extractattachments command.
This code worked the way I expected it to ...
IntegrationPointFactory ipfact = IntegrationPointFactory.getInstance();
IntegrationPoint ip = ipfact.createIntegrationPoint(hostname, port, APIVersion.API_4_16);
Session session = ip.createNamedSession("test", APIVersion.API_4_16, user, passwd);
CmdRunner cr = session.createCmdRunner();
Command cmd = new Command(Command.IM, "extractattachments");
cmd.addSelection(attachmentName);
cmd.addOption(new Option("issue", issueid));
cmd.addOption(new FileOption("outputFile", "d:/data/" + attachmentName));
cr.execute(cmd);
cr.release();
ip.release();

SNMPv3 not in time window

I try to query a Cisco SMB (small business switch) to read its hostname.
My code returns "not in time window (1.3.6.1.6.3.15.1.1.2.0).
Net-Snmp works fine. The difference I found using wireshark is that net-snmp sets msgAuthorativeEngineTime after it receives not in time window error.
Discovery discovery = Messenger.GetNextDiscovery(SnmpType.GetRequestPdu);
ReportMessage report = discovery.GetResponse(60000, new IPEndPoint(IPAddress.Parse("10.105.9.10"), 161));
OctetString username = new OctetString("test");
var auth = new SHA1AuthenticationProvider(new OctetString("Testtest123!"));
var priv = new DESPrivacyProvider(new OctetString("Testtest123!"), auth);
// read switch hostname
GetRequestMessage request = new GetRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, username, new List<Variable> { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.5.0")) }, priv, Messenger.MaxMessageSize, report);
ISnmpMessage reply = request.GetResponse(60000, router); (not in time window)
Please find a wireshark screenshot of sharp-snmp:
And net-snmp:
Thank you for your help!
According to the snmpget sample (updated link here), you have to call two times the GetRequestMessage method. Be aware that the code uses the report variable in the first call, then the reply one in the latter, otherwise it will not work (= not in time window message) (I lost half a day to get this!)

Collecting output from Docker in java application

I'm executing some code on docker in my java application using ProcessBuilder to run the code, however i'm having trouble retrieving the output from it. BufferedReader is not reading anything from the InputStream returned from the container. Is there a specific way to retrieve output from Docker??
I've never had trouble getting output from bash executions before, so I'm thinking maybe docker does things differently somehow. Any ideas would be appreciated
Here's a snippet of the code:
Process dockerCommand;
ProcessBuilder builder = new ProcessBuilder("bash","-c","sudo docker images");
builder.redirectErrorStream(true);
builder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
builder.redirectError(ProcessBuilder.Redirect.INHERIT);
dockerCommand = builder.start();
dockerCommand.waitFor();
List<String> result = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(dockerCommand.getInputStream()))
{
String line = reader.readLine();
while (line != null) {
result.add(line);
line = reader.readLine();
}
}
catch (IOException exc)
{}
The line
builder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
causes bash to receive the same standard output as the parent process, which is presumably your terminal window. This produces misleading results because you actually see the Docker image list, but it's being printed by the shell.
If I comment that out and then iterate over the results list, I can see the output from Docker inside the JVM.

Why can't I set a Stream using the FtpWebRequest.GetRequestStream() method?

I have been trying to write a simple ftp client using c# in .NET 2.0 for 3 days now and am
missing something. I I create an ftpWebRequest object and set all its properies.
string uri = host + remoteFile;
System.Net.FtpWebRequest ftp = (FtpWebRequest)(FtpWebRequest.Create(uri));
ftp.Credentials = new System.Net.NetworkCredential(username, password);
ftp.KeepAlive = false;
ftp.UseBinary = true;
ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
But when I go to get the stream, it fails...
System.IO.Stream strm = ftp.GetRequestStream();
Here is the error: "System.Net.WebException: The remote server returned an error: (501) Syntax error in parameters or arguments."
This method SHOULD return the stream I need to write to and many examples do exactly this. I'm not sure what I'm missing. My host looks like this: "ftp://myhostname/" and I've triple checked my credentials.
Please help!
may be ftp.UseBinary = true; is not supported by server?
You are missing the "/" after the host:
string uri = host + "/" + remoteFile;
and the remote file string should look like this: file.txt without any path.

Java Runtime Exec on Windows Fails with Unicode in Arguments

I want to launch a browser and load a web page using Java's Runtime exec. The exact call looks like this:
String[] explorer = {"C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE",
"-noframemerging",
"C:\\ ... path containing unicode chars ... \\Main.html"};
Runtime.getRuntime().exec(explorer);
In my case, the path contains "\u65E5\u672C\u8A9E", the characters 日本語.
Apparently it's a java bug:
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4947220
My question is: is there a viable workaround that can be done solely using Java? It appears that it is possible to write a JNI library for this, but I'd like to avoid that if possible. I have tried URI-encoding the path as ascii and writing the commands to a batch file, without success.
At the mentioned Java bug page you will find a workaround that is reported to work using ProcessBuilder and wrapping the parameters in environment variables. Here is the source code from Parag Thakur:
String[] cmd = new String[]{"yourcmd.exe", "Japanese CLI argument: \ufeff\u30cb\u30e5\u30fc\u30b9"};
Map<String, String> newEnv = new HashMap<String, String>();
newEnv.putAll(System.getenv());
String[] i18n = new String[cmd.length + 2];
i18n[0] = "cmd";
i18n[1] = "/C";
i18n[2] = cmd[0];
for (int counter = 1; counter < cmd.length; counter++)
{
String envName = "JENV_" + counter;
i18n[counter + 2] = "%" + envName + "%";
newEnv.put(envName, cmd[counter]);
}
cmd = i18n;
ProcessBuilder pb = new ProcessBuilder(cmd);
Map<String, String> env = pb.environment();
env.putAll(newEnv);
final Process p = pb.start();
Create a .bat/.sh file. Write your commands to that file and execute it. Make sure that you have changed the code page to unicode in case of windows(chcp 65001).
For example to execute the below command in windows:
String[] command ={"C:\\aconex\\学校\\mysql\\bin\\mysql", "-esource", "大村箕島a\\data.sql"};
Create a temp file called temp.bat and execute with the Runtime.getRuntime().exec
temp.bat
chcp 65001
C:\aconex\学校\mysql\bin\mysql -esource 大村箕島a\data.sql
These are the two solutions I considered, each of which are more or less workarounds:
Create a temp html redirect file which will redirect the browser to the proper page.
Note that IE will expect unencoded unicode for local files, while other browsers may accept only uri-encoded file paths
Use the short filename for the windows file. It won't contain unicode characters.
We've been using a JNI to start processes from Java for years. Neither Runtime.exec or ProcessBuilder will work, and it seems unlikely that they will fix this, given how long it's been already.
However, you should be able to work around the issue by using the input stream, a socket, or environment variables to pass parameters. If you don't have direct control over the executable, you'll have to make a wrapper.
You could use JNA. With version 3.3.0 or later call CreateProcess:
WinBase.PROCESS_INFORMATION.ByReference processInfo =
new WinBase.PROCESS_INFORMATION.ByReference();
WinBase.STARTUPINFO startupInfo = new WinBase.STARTUPINFO();
String command = "C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE " +
"-noframemerging \"C:\\\u65E5\u672C\u8A9E\\Main.html\"";
if (!Kernel32.INSTANCE.CreateProcess(
null, // Application name, not needed if supplied in command line
command, // Command line
null, // Process security attributes
null, // Thread security attributes
true, // Inherit handles
0, // Creation flags
null, // Environment
null, // Directory
startupInfo,
processInfo))
{
throw new IllegalStateException("Error creating process. Last error: " +
Kernel32.INSTANCE.GetLastError());
}
// The CreateProcess documentation indicates that it is very important to
// close the returned handles
Kernel32.INSTANCE.CloseHandle(processInfo.hThread);
Kernel32.INSTANCE.CloseHandle(processInfo.hProcess);
long pid = processInfo.dwProcessId.longValue();
Redirecting output from the child process is a bit harder but not impossible.
I think you can use Apache Commons Exec library or ProcessBuilder to give a try;)

Resources