let { Subprocess } = ChromeUtils.import("resource://gre/modules/Subprocess.jsm");
let result = Subprocess.call({ command: "C:\\\\windows\\\\explorer.exe" });
While this works for explorer, mspaint and calculator for instance trying to open cmd.exe using System32\cmd.exe path won't work, is there any explanation for this?
Also I can't seem to be able to pass arguments to explorer.exe, something like :
let result = Subprocess.call({ command: "C:\\\\windows\\\\explorer /seperate, C:\Windows\System32\cmd.exe" });
won't work
Any ideas or help? Thank you
Related
I am a Rust newbie. I've been wanting to learn Rust and decided my first project would be to build a connection testing tool packaged an executable for the tech support people at my work. Basically the tool needs to run by end-users on Windows computers and test three or more URLs using ping, tracert, and telnet. Also after running the tool, the results of the three commands should be logged into text files and lastly enclosed in a zip file at the end.
I put some code together and it's mostly working except for the telnet portion. I've been pulling my hair out trying to figure out why the telnet part is not working. I was able to compile my Rust code successfully and it runs, but no matter what the telnet part generates a telnet connection failed in the log indicating the telnet was not successful, even though I am able to run the telnet command on the same machine using the same command manually typed (telnet service1.somedomain.com 13101). So I can see telnet is installed and working...
Further down below is my code. I added some println! statements on lines 59-61 and the only clue I see so far is the status code that prints out when I run the tool says telnet command exited with status: exit code: 0xffffffff and nothing prints for telnet stdout/stderr. This seems to indicate telnet is aborting or not found, so I used the full path to the telnet.exe file on the Windows machine (C:\Windows\System32\telnet.exe) instead of just "telnet" and still got the same error.
use std::process::Command;
use std::fs::File;
use std::io::prelude::*;
use std::io::Error;
use std::path::{Path, PathBuf};
use std::io::Cursor;
//use zip::write::FileOptions;
//use zip::result::ZipWriter;
use zip::write::{FileOptions, ZipWriter};
use zip::result::ZipResult;
fn main() -> Result<(), Error> {
// Set the domains and ports to be tested
let domains_and_ports = [
("www.somedomain.com", "80"),
("serivce1.somedomain.com", "13101"),
("service2.somedomain.com", "13103")];
// Create a zip file to store the results
let zip_file_path = Path::new("results.zip");
let zip_file = File::create(zip_file_path)?;
let mut zip_writer = ZipWriter::new(zip_file);
// Set the password to encrypt the zip file
let password = b"password";
// Iterate over each domain and port combination
for (domain, port) in domains_and_ports {
// Run the ping command
let ping_output = Command::new("cmd")
.args(&["/C", format!("ping {}", domain).as_str()])
.output()?;
let ping_file_path = write_output_to_file(domain, "ping.txt", &ping_output)?;
// Run the tracert command
let tracert_output = Command::new("cmd")
.args(&["/C", format!("tracert {}", domain).as_str()])
.output()?;
let tracert_file_path = write_output_to_file(domain, "tracert.txt", &tracert_output)?;
let telnet_output = Command::new("cmd")
.args(&["/C", format!("telnet {} {}", domain, port).as_str()])
.output()?;
let telnet_file_path = write_output_to_file(domain, "telnet.txt", &telnet_output)?;
// Write the ping, tracert, and telnet results to the zip file
zip_writer.start_file(format!("{}_ping.txt", domain), FileOptions::default())?;
zip_writer.write_all(&read_file_contents(ping_file_path)?)?;
zip_writer.start_file(format!("{}_tracert.txt", domain), FileOptions::default())?;
zip_writer.write_all(&read_file_contents(tracert_file_path)?)?;
zip_writer.start_file(format!("{}_telnet.txt", domain), FileOptions::default())?;
println!("telnet command exited with status: {}", telnet_output.status);
println!("telnet stdout: {}", String::from_utf8_lossy(&telnet_output.stdout));
println!("telnet stderr: {}", String::from_utf8_lossy(&telnet_output.stderr));
if telnet_output.status.success() {
zip_writer.write_all(b"telnet connection successful")?;
} else {
zip_writer.write_all(b"telnet connection failed")?;
}
}
// Close the zip file
zip_writer.finish()?;
println!("Results saved in results.zip");
Ok(())
}
fn write_output_to_file(domain: &str, command: &str, output: &std::process::Output) -> Result<PathBuf, Error> {
let fname = format!("{}_{}", domain, command).as_str().to_owned();
//let file_path = Path::new(format!("{}_{}", domain, command).as_str());
let file_path = Path::new(&fname);
let mut file = File::create(file_path)?;
file.write_all(&output.stdout)?;
file.write_all(&output.stderr)?;
Ok(file_path.to_path_buf())
}
fn read_file_contents(file_path: PathBuf) -> Result<Vec<u8>, Error> {
let mut file = File::open(file_path)?;
let mut contents = Vec::new();
file.read_to_end(&mut contents)?;
Ok(contents)
}
This is what prints (one set shown for first domain, but it prints three sets with same error, for each domain/port combination)...
Does anyone have experience running telnet commands on Windows, plus logging telnet results using Rust? If anyone has tips or example code to fix my example above I would be truly grateful. As a side-note, I know something similar could be done with a Windows batch file or Python but I was really wanting to get the Rust project working so I could have a little "win" with this my first go around with it.
Thanks in advance for any help you can offer!
PS - the domains and ports are made-up for this post :).
I have the following issue with sendKeys in casperjs.
I am trying to pass the port as an option into casperjs and this is working, but when i try to use the port value with casper.cli.get it doesn't work in sendKeys!!!
var casper = require('casper').create();
casper.echo("Casper CLI passed args:");
require("utils").dump(casper.cli.args);
casper.echo("Casper CLI passed options:");
require("utils").dump(casper.cli.options);
if (casper.cli.has("ip") === false) {
casper.echo("Usage: casper.js test modify_port.js --ip=<x.x.x.x> --port=<xxxxx>").exit();
}
if (casper.cli.has("port") === false) {
casper.echo("Usage: casper.js test modify_port.js --ip=<x.x.x.x> --port=<xxxxx>").exit();
}
...
casper.then(function() {
test.assertTextExists("Change", "Data Base - Change - port");
this.sendKeys('input[name="Params.port"]', casper.cli.get("port"));
this.click('input[name="Apply"]');
});
The above way seems not to work and it doesn't give me also no error msg.
But when i hard code the port in the sendKeys line then i see that the port is changed, like:
this.sendKeys('input[name="Params.port"]', '29999');
This is also working fine (hard coded):
var myPort = '29999'
this.sendKeys('input[name="Params.port"]', myPort);
But this again is not working:
var myPort = casper.cli.get("port")
this.sendKeys('input[name="Params.port"]', myPort);
Thanks in adv. for your time
After some more readings I stepped over the part where casperjs documentation is saying about Raw parameter values.
So, I figured out to use my parameter in this way:
this.sendKeys('input[name="Params.port"]', casper.cli.raw.get('port'));
When passing variables into sendKeys they will not appear in the form unless they are preceded with an empty string "".
this.sendKeys("selector", "" + variable);
I guess this may be because sendKeys can only handle variables of type string.
Source
This is my first time writing in Swift, Cocoa (have experience in Cocoa Touch), and using Authorization, so I honestly have no idea if I am even on the right track. I am trying to make a modification to the hosts file, which requires user authentication, but both the AuthorizationCreate and AuthorizationExecuteWithPrivileges methods are giving errors.
var authorizationRef:AuthorizationRef
var status:OSStatus
status = AuthorizationCreate(nil, environment:kAuthorizationEmptyEnvironment, flags:kAuthorizationFlagDefaults, authorization:&authorizationRef)
let overwrite_hosts = "echo \(hostsContents) > /private/etc/hosts"
let args = [overwrite_hosts.cStringUsingEncoding(NSUTF8StringEncoding)]
status = AuthorizationExecuteWithPrivileges(authorizationRef, pathToTool:"/bin/sh", options:kAuthorizationFlagDefaults, arguments:args, communicationsPipe:nil)
Me calling AuthorizationCreate is throwing "Type '()' does not conform to protocol 'AuthorizationRef'" and my call of AuthorizationExecuteWithPrivileges is throwing "Could not find an overload for '__conversion' that accepts the supplied arguments"
Any ideas? Am I approaching this incorrectly?
Thanks for any help!
I was able to figure out how to do it via AppleScript, but you should be able to do it using the Authorization method I was trying before, therefore leaving this question open. Anybody looking for a quick solution (no error checks implemented) you can use what I wrote below:
func doScriptWithAdmin(inScript:String) -> String{
let script = "do shell script \"\(inScript)\" with administrator privileges"
var appleScript = NSAppleScript(source: script)
var eventResult = appleScript.executeAndReturnError(nil)
if !eventResult {
return "ERROR"
}else{
return eventResult.stringValue
}
}
I use spawn for JScript (from windows)
My problem with decode text
???? ??? T-SQL Microsoft SQL Server 2012
???? ??? - russian text.
var worker,path = require('path'), spawn = require('child_process').spawn, cscript = path.join(process.env.SystemRoot, 'system32', 'cscript.exe')
function startCscript() {
worker = spawn( cscript, [ '/nologo', 'testwsh.js' ] );
worker.stdout.setEncoding('utf8');
worker.stdout.on( 'data', onData );
}
function onData (data) {
console.log(data.toString());
}
startCscript();
How do I get Russian letters? Thanks all )
Can you try to set the worker encoding as ucs2 or utf16le.
Change this
worker.stdout.setEncoding('utf8');
to this
worker.stdout.setEncoding('ucs2');
Tell if it solves the issue.
look at issue 2190 and issue 2196:
Node.js does always expect UTF-8 output from a child process, but
Windows with Russian locale defaults to CP866
you need to execute chcp 65001 to change current console code page.
My solution: use iconv-lite, to get the Russian text in the console.
i have a new problem in image magick that look strange ..
i'm using mac osx snow leopard and i've installed image magick on it and it's working fine on command ..
but when i call it from the grails class like the following snippet it gives me
"Cannot run program "convert": error=2, No such file or directory"
the code is :-
public static boolean resizeImage(String srcPath, String destPath,String size) {
ArrayList<String> command = new ArrayList<String>(10);
command.add("convert");
command.add("-geometry");
command.add(size);
command.add("-quality");
command.add("100" );
command.add(srcPath);
command.add(destPath);
System.out.println(command);
return exec((String[])command.toArray(new String[1]));
}
private static boolean exec(String[] command) {
Process proc;
try {
//System.out.println("Trying to execute command " + Arrays.asList(command));
proc = Runtime.getRuntime().exec(command);
} catch (IOException e) {
System.out.println("IOException while trying to execute " );
for(int i =0 ; i<command.length; i++) {
System.out.println(command[i]);
}
return false;
}
//System.out.println("Got process object, waiting to return.");
int exitStatus;
while (true) {
try {
exitStatus = proc.waitFor();
break;
} catch (java.lang.InterruptedException e) {
System.out.println("Interrupted: Ignoring and waiting");
}
}
if (exitStatus != 0) {
System.out.println("Error executing command: " + exitStatus);
}
return (exitStatus == 0);
}
i've tried normal command like ls and it's ok so the problem is that grails can't find convert command itself.. is it a os problem or something?
(see lower for the answer)
I have run into the same problem. The issue appears to be something with Mac OS X specifically, as we have several Linux instances running without error. The error looks similar to the following:
java.io.IOException: Cannot run program "/usr/bin/ImageMagick-6.7.3/bin/convert /a/temp/in/tmpPic3143119797006817740.png /a/temp/out/100000726.png": error=2, No such file or directory
All the files are there, and in chmod 777 directories - and as you pointed out, running the exact command from the shell works fine.
My theory at this point is that imagemgick can not load some sort of library itself, and the "no such file" is in reference to an dylib or something along those lines.
I have tried setting LD_LIBRARY_PATH and a few others to no avail.
I finally got this working. Here is how I have it setup. I hope this helps.
The crux of the fix, for me, was I wrapped the 'convert' into a shell script, set a bunch of environment variables, and then call that shell script instead of convert directly:
(convertWrapper.sh)
export MAGICK_HOME=/usr/local/ImageMagick-6.7.5
export MAGICK_CONFIGURE_PATH=${MAGICK_HOME}/etc/ImageMagick:${MAGICK_HOME}/share/doc/ImageMagick/www/source
export PATH=${PATH}:${MAGICK_HOME}/bin
export LD_LIBRARY_PATH=${MAGICK_HOME}/lib:${LD_LIBRARY_PATH}
export DYLD_LIBRARY_PATH=${DYLD_LIBRARY_PATH}:${MAGICK_HOME}/lib
export MAGICK_TMPDIR=/private/tmp
echo "$#" >> /private/tmp/m.log 2>&1
/usr/local/ImageMagick-6.7.5/bin/convert -verbose "$#" >> /private/tmp/m.log 2>&1
(convertWrapper.sh)
Additionally, the convert call was doing some rather complicated stuff, so I added the parameter '-respect-parenthesis' (which may or may not have had an effect).
I am not sure how much of the environment variable setting is needed as I was stabbing in the dark for a while, but since this is only for my development box...
You need to work out what your PATH is set to when you run a command from Java. It must be different to the one you have when running from the terminal.
Are you running Grails (via Tomcat?) as a different user? It might have a different path to your normal user.
you might want to try one of the Image Plugins that are part of the grails ecosystem
http://www.grails.org/ImageTools+plugin
the grails path when the app is running in the server is probably different from running java from the command line
I do so:
Put "convert" file to /usr/bin
Then add to Config.groovy:
gk {
imageMagickPath = "/usr/bin/convert"
}
Then in my ImageService.groovy:
import org.springframework.web.context.request.RequestContextHolder as RCH
[..]
def grailsApplication = RCH.requestAttributes.servletContext.grailsApplication
def imPath = grailsApplication.config.gk.imageMagickPath
def command = imPath + " some_properties"
def proc = Runtime.getRuntime().exec(command)
So this way you get command like: /usr/bin/convert some_properties
And it works, but don't forget to put file "convert" to you location and use it with this location.