How do I send a Carriage Return with Windows Netcat? - powershell

I want to type directly into the Powershell prompt too, not pipe in a text file.
Foo`r doesn't work for me. For example:
echo "RJ`r`n" | .\nc.exe -u 192.168.1.247 2639
but what I'd really like to do is just
.\nc.exe -u 192.168.1.247 2639
then start typing into the prompt.

Try:
"Foo`ndoes work for me"
If you need a full CRLF sequence then:
"Foo`r`ndoes work for me"
Note that the escapes chars only work in double-quoted strings - not single quoted strings.
Update: Redirect in < is not supported in PowerShell at this time so you can only get stdin to the exe from the interactive prompt using the pipeline. Is it possible nc.exe is expecting another character (or escape char) to terminate the input? I know that console exes can receive stdin from PowerShell. If you have the C# compiler, you can see this by compiling the following source (csc echostdin.cs):
using System;
public class App
{
public static void Main()
{
int ch;
while ((ch = Console.In.Read()) != -1)
{
Console.Write((char)ch);
}
}
}
Then execute the exe:
PS> "foo`r`n" | .\echostdin.exe
foo
PS>

Related

console output using shellexecuteW

I'm using ShellExecuteW from shell32.dll:
int value= ShellExecuteW(0, "open", "C:\test.bat", strParameters, "", 1);
The batch file runs a java app which seems to open but returns an error and quickly the console window closes.
I want to capture the error from the console. I've tried adding the following re-directions at the end of my command in the batch file:
> output.txt
2> output.txt
> output.txt 2>&1
1> output.txt 2>&1
| output.txt
I would expect these common commands to work but none of them result in anything being written in output.txt. What could I be doing wrong here?
I'm using Metatrader5 (MQL5 language) to call shellexecuteW from.
Thankyou for your replies.
First you should put the bat file in Terminal path in "File" folder because of mql5 security policy, Secondly put these codes in your script to use "ShellExecuteW" function correctly.
#import "shell32.dll"
int ShellExecuteW(int hwnd,string operation,string file,string parameters,string directory,int showCmd);
#import
int result;
string strParameters = "";
string filename="test.bat";
string Batfile_path=TerminalInfoString(TERMINAL_COMMONDATA_PATH)+"\\Files\\"+filename;
Print("Batfile_path:",Batfile_path);
result = ShellExecuteW(0, "open", Batfile_path, strParameters, "", 0);
if(result <= 32)Print("Shell Execute for running bat file Failed: ", result);

Run a long Powershell command as parameter when executing a BATCH file [duplicate]

This question already has answers here:
Convert a small PS script into a long line in a .BATch file
(3 answers)
Closed 4 years ago.
I want to run the following Powershell command by executing a .bat file:
Add-Type -TypeDefinition #'
using System.Runtime.InteropServices;
[Guid("5CDF2C82-841E-4546-9722-0CF74078229A"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IAudioEndpointVolume
{
// f(), g(), ... are unused COM method slots. Define these if you care
int f(); int g(); int h(); int i();
int SetMasterVolumeLevelScalar(float fLevel, System.Guid pguidEventContext);
int j();
int GetMasterVolumeLevelScalar(out float pfLevel);
int k(); int l(); int m(); int n();
int SetMute([MarshalAs(UnmanagedType.Bool)] bool bMute, System.Guid pguidEventContext);
int GetMute(out bool pbMute);
}
[Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IMMDevice
{
int Activate(ref System.Guid id, int clsCtx, int activationParams, out IAudioEndpointVolume aev);
}
[Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IMMDeviceEnumerator
{
int f(); // Unused
int GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice endpoint);
}
[ComImport, Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")] class MMDeviceEnumeratorComObject { }
public class Audio
{
static IAudioEndpointVolume Vol()
{
var enumerator = new MMDeviceEnumeratorComObject() as IMMDeviceEnumerator;
IMMDevice dev = null;
Marshal.ThrowExceptionForHR(enumerator.GetDefaultAudioEndpoint(/*eRender*/ 0, /*eMultimedia*/ 1, out dev));
IAudioEndpointVolume epv = null;
var epvid = typeof(IAudioEndpointVolume).GUID;
Marshal.ThrowExceptionForHR(dev.Activate(ref epvid, /*CLSCTX_ALL*/ 23, 0, out epv));
return epv;
}
public static float Volume
{
get { float v = -1; Marshal.ThrowExceptionForHR(Vol().GetMasterVolumeLevelScalar(out v)); return v; }
set { Marshal.ThrowExceptionForHR(Vol().SetMasterVolumeLevelScalar(value, System.Guid.Empty)); }
}
public static bool Mute
{
get { bool mute; Marshal.ThrowExceptionForHR(Vol().GetMute(out mute)); return mute; }
set { Marshal.ThrowExceptionForHR(Vol().SetMute(value, System.Guid.Empty)); }
}
}
'#
[audio]::Volume = 1
The problem with cmd command prompt is that it interprets a new line of code as execute this command.
However, when I enter everything into a PowerShell command line, it does not do so.
Is there any possibility to run this whole PowerShell script by executing a batch script?
I have already tried powershell -command "and the whole script", but that did not work either... cmd keeps thinking a new line means to execute it.
Try this if you want to execute your PS1 File:
powershell.exe -executionpolicy bypass -file "YOUR_FILE_NAME.ps1"
If you want to do everythin in one batch File do this:
powershell.exe
"Your Command"
You just need to put your command into the next line.
First of all, if you have a long PowerShell command, the maximum limit of characters per cmd command line can be easily reached (I believe it is ~8191 characters?).
Furthermore, it is quite uncommon to execute such big PowerShell commands directly in the cmd command line. Usually you should put it inside a file ending with .ps1, and then you execute it using the following command:
powershell.exe -executionpolicy bypass -file script.ps1
In case you really need to run the PowerShell command as you mentioned, you must first modify it a little bit. Take as example the following PS script:
function Say-Hello
{
[CmdletBinding()]
Param
(
[string] $name
)
Process
{
# Let's say hello!
$str = "Hello " + $name
Write-Output $str
}
}
Say-Hello "Jason"
The trick is to replace all \r\n line endings with \n, using a text editor (like Notepad++ for instance):
HOWEVER, you must first add some ; at the end of many of your PowerShell commands, because that is the only way you can tell PowerShell that a new PowerShell command is being issued. Otherwise, PowerShell may take 2 lines of your code and execute them as a single one, since they look all concatenated after you removed the newlines.
Then remove all line comments from your code, and escape all double quotes (or alternatively, just replace them with single quotes):
function Say-Hello
{
[CmdletBinding()]
Param
(
[string] $name
)
Process
{
$str = 'Hello ' + $name;
Write-Output $str
}
}
Say-Hello 'Jason'
Now you are ready to copy it from your text editor tool (Notepad++ in my case) and paste it to your command line like this:
powershell.exe -executionpolicy bypass -command "function Say-Hello { [CmdletBinding()] Param ([string] $name) Process { $str = 'Hello ' + $name; Write-Output $str }} Say-Hello 'Jason'"
And the expected output for that is:
Hello Jason

Expect Interact and special characters

trying to create a macro program with expect to help me manage my cisco devices>
I want to keep all native cisco functions like tab complete ETC.
initially I wanted to type "!...!" where my macro is inside the bangs, my code looked like this:
interact {
-re "!(.+)!" { #find correct macro }
}
but with this method, there is no feedback to the user. what happens if they misspell? etc then they can't see their corrections with backspace.
then I started thinking about just capturing each character press and building a string
interact {
#book says backspace character
"\b" {
set command [lreplace $command end end]
}
#detect return, sending command
-re "\r" {
set command [join $command ""]
if [regexp "^!" $command] {
#send ctrl+u to erase line sent
send "\025"
findMacro $command
}
set command ""
send "\r"
}
#send tab for tab completion
"\t" { send "\t" }
-re "(.)" {
send $interact_out(1,string)
lappend command $interact_out(1,string)
}
}
but I can't "expect" the backspace. I've tried 0x08.. etc nothing is working. in the end I'm not even sure this is the way to go simply because there are to many other buttons a user could push and mess up my string I'm building.
the real solution, I think, is to wait until "\r" is pressed, and then run a regex on that line. but I'm not sure how to do that.

mIRC Bot simulate keystrokes

I would like to program my mIRC bot so every time someone writes "W" in the chat, the bot simulates the W key on my keyboard.
I have tried:
on *:text:W:#:sendkeys {W}
alias sendkeys var %a = $ticks
.comopen %a WScript.Shell | if !$comerr {
.comclose %a $com(%a,SendKeys,3,bstr,$1-)
}
This doesn't seem to be working. Any advice?
The code is fine, the blocks in which you execute that code are incorrect. Due to a lack of brackets, your alias will only execute the var command, and be done after that.
Taken from the mIRC help files:
The { } brackets: You can create multi-line scripts by using the { } brackets. This allows you to create an alias which performs several commands.
alias sendkeys {
var %a = $ticks
.comopen %a WScript.Shell
if !$comerr {
.comclose %a $com(%a,SendKeys,3,bstr,$1-)
}
}

Powershell arguments list passing like -a <args list> -d <args list>

I want to write a powershell ps1 script, which needs 2 argument sets,(-a -d) and each can have upto n attributes. How to implement that?
example : DoTheTask -a <task name 1> <task name 2> ... -d <machine name 1> <machine name 2>...
You can do this:
param(
[string[]]$a,
[string[]]$d
)
write-host $a
write-host ----
write-host $d
Then you can call DoTheTask -a task1,task2 -d machine1,machine2
Can you organize your task names and machines names in such a way that they can be put in to a single string with delimiters.
In other words, could your -a argument be a string a comma-separated task names and your -d argument be a string of comma-separated machine names? If so, then all you need to do is parse the string into its components at the start of your script.
If you are passing these arguments to the script itself, you could leverage the $args internal variable, though key/value mapping will be a little trickier since PowerShell will interpret each statement as an argument. I suggest (like others) that you use another separator so that you can do the mappings easier.
Nonetheless, if you want to continue doing it this way, you can use a function like the below:
Function Parse-Arguments {
$_args = $script:args # set this to something other than $script:args if you want to use this inside of the script.
$_ret = #{}
foreach ($_arg in $_args) {
if ($_arg.substring(0,1) -eq '-') {
$_key = $_arg; [void]$foreach.moveNext() # set the key (i.e. -a, -b) and moves to the next element in $args, or the tasks to do for that switch
while ($_arg.substring(0,1) -ne '-') { # goes through each task until it hits another switch
$_val = $_arg
switch($_key) {
'-a' {
write-host "doing stuff for $_key"
$ret.add($_key,$_val) # puts the arg entered and tasks to do for that arg.
}
# put more conditionals here
}
}
}
}
}