jPowerShell and PowerShell Core (7.x) Issue - powershell-7.0

I am trying to invoke PowerShell cmdlets and scripts from a Java Application. I am using jPowerShell . It works as expected as expected with PowerShell version 6.0.x. However, when I am running PowerShell 7.x, the executeCommand() method times out. Just wanted to find out if anyone else have had this issue and how you resolved it. I'd appreciate if you can let me know. Thanks
Here is my sample code:
..
..
//Creates PowerShell session (we can execute several commands in the same session)
try (PowerShell powerShell = PowerShell.openSession()) {
//Execute a command in PowerShell session
PowerShell powerShell = PowerShell.openSession("pwsh"); // pwsh is the executable in Linux
Map<String, String> config = new HashMap<String, String>();
config.put("maxWait", "60000"); // wait for a minute
PowerShellResponse response = powerShell.executeCommand("Get-Process");
responseBody = response.getCommandOutput();
responseCode = response.isError() ? 1 : 0;
} catch(Exception e) {
StringBuffer sb = new StringBuffer(e.getMessage());
return toResponse(responseCode, sb.toString());
}
..
..
Please note that I am running the above inside a Docker container and I am able to see the "pwsh -nologo -noexit -Command -" process running in the container before it times out.
Jay
I tried to run a PowerShell cmdlet from Java code using jPowerShell and I was expecting the result of the PowerShell cmdlet (for example, Get-Date, Get-Process, etc)

Related

A passing problem with PSCustomObject when passing from PowerShell to Windows PowerShell

I'm trying to setup an IIS application pool via PowerShell 7.1.1.
I read configuration from a JSON file into the variable $configuration which is hand over to Windows Powershell because of WebAdministration module which isn't natively supported PS 7.1.1.
A script block is defined in the top level function, the configuration is injected as PSCustomObject into the script block and executed in Windows PowerShell.
function Set-AxisAppPool
{
Write-Message 'Setting up a resource pool for Axis...'
$executeInWindowsPowerShellForCompatibilityReasons = {
param (
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[PSCustomObject]
$Configuration
)
Import-Module WebAdministration
Remove-WebAppPool -Name $Configuration.AppPool.Name -Confirm:$false -ErrorAction:SilentlyContinue
New-WebAppPool -Name $Configuration.AppPool.Name -Force | Write-Verbose
$params = #{
Path = "IIS:\AppPools\$($Configuration.AppPool.Name)"
Name = 'processModel'
Value = #{
userName = $Configuration.AxisUser.Name
password = $Configuration.AxisUser.Password
identitytype = 'SpecificUser'
}
}
Set-ItemProperty #params
}
powershell -NoLogo -NoProfile $executeInWindowsPowerShellForCompatibilityReasons -Args $configuration # This is a line 546
}
When the configuration JSON file exceeds a certain level, PowerShell can't pass through this deserialized JSON, the PSCustomObject, into Windows PowerShell.
Program 'powershell.exe' failed to run: The Process object must have the UseShellExecute property set to false in order to use environment
| variables.At C:\Users\JohnDoe\Desktop\Localhost automatization\Set-AxisEnvironment.ps1:546 char:5 + powershell -NoLogo -NoProfile
| $executeInWindowsPowerShellForCompa … +
It literally work with level n of objects in the JSON and it doesn't with n+1 level of objects in the configuration JSON. The JSON schema is validated, deserialization works as expected.
When I use Start-Process for invoking Windows PowerShell, I receive a different problem. Does anybody have any hint on this one?
Update
This seems to be a bug in PowerShell.
I suspect it is the size of the argument list overflowing into other fields, thus giving you weird error messages. From Start Process:
The length of the string assigned to the Arguments property must
be less than 32,699.
If you are passing a configuration that is larger than 32,699 characters (including spaces), then that likely may be your problem. It would likely take those first 32,699 characters then continue to the next field, -UseShellExecute which would receive a character which is not zero or false, and thus true. This would trip the "wrong", and misleading error message.

Trying to automate Tor to do something on a site and change identity each time. Need some guidance

I really need some help with automating Tor to do something on a site (in this case, check something on a poll) and then restart Tor with a new identity. I have never done anything remotely close to this. I only know HTML, CSS and JS fairly well.
Now, to sum up, I want to make a loop that repeatedly accesses a site on Tor, checks something on that site and then restarts Tor with a new identity.
If anyone could give me some guidance and tell me what I can use, it would be much appreciated. I have the time and patience to learn, so anything works really.
Here are examples using PHP and Python 3 to accomplish what you want. They're simple starting points for making requests over Tor and changing your identity on demand.
The PHP example uses TorUtils to communicate with the controller and wrap cURL through Tor.
The Python example uses stem to communicate with the controller and Requests for sending requests over Tor's SOCKS proxy.
The examples assume you have Tor working already and the SocksPort set to 9050, and the ControlPort set to 9051 with cookie authentication working, or a controller password of password.
PHP
Set Up
Install Composer to install the TorUtils package (you can also download the zipball and extract)
Once composer is working, run composer require dapphp/torutils from your project directory to download and install dependencies
Code
<?php
use Dapphp\TorUtils\ControlClient;
use Dapphp\TorUtils\TorCurlWrapper;
require_once 'vendor/autoload.php'; // composer autoloader
// include TorUtils/src/ControlClient.php and TorUtils/src/TorCurlWrapper.php if using without composer
$controller = new ControlClient; // get a new controller object
try {
$controller->connect('127.0.0.1', 9051); // connect to Tor controller on localhost:9051
$controller->authenticate('password'); // attempt to authenticate using "password" as password
} catch (\Exception $ex) {
die("Failed to open connection to Tor controller. Reason: " . $ex->getMessage() . "\n");
}
// issue 10 requests, changing identity after each request
for ($i = 0; $i < 10; ++$i) {
try {
$curl = new TorCurlWrapper('127.0.0.1', 9050); // connect to Tor SOCKS proxy on localhost:9050
$curl->httpGet('https://drew-phillips.com/ip-info/'); // issue request
$body = strip_tags($curl->getResponseBody());
if (preg_match('/Using Tor:\s*Yes/i', $body)) {
echo "You appear to be using Tor successfully. ";
} else {
echo "Proxy worked but this Tor IP is not known. ";
}
if (preg_match('/IP Address:\s*(\d+\.\d+\.\d+\.\d+)/i', $body, $ip)) {
echo "Source IP = {$ip[1]}\n";
} else {
echo "Couldn't determine IP!\n";
}
} catch (\Exception $ex) {
echo "HTTP request failed! " . $ex->getMessage() . "\n";
}
// TODO: issue more requests as needed here
echo "\n";
sleep(10);
try {
// send signal to controller to request new identity (IP)
$controller->signal(ControlClient::SIGNAL_NEWNYM);
} catch (\Exception $ex) {
echo "Failed to issue NEWNYM signal: " . $ex->getMessage() . "\n";
}
}
Python 3
Set Up
This example uses Python 3 and assumes you have the Python interpreter up and running and have the following packages installed: requests, requests[socks], socks, urllib3, stem.
On Debian/Ubuntu: sudo -H pip3 install requests requests[socks] socks urllib3 stem
Code
#!/usr/bin/env python3
import requests
from stem.control import Controller, Signal
import time
import sys
import re
# specify Tor's SOCKS proxy for http and https requests
proxies = {
'http': 'socks5h://127.0.0.1:9050',
'https': 'socks5h://127.0.0.1:9050',
}
try:
controller = Controller.from_port(9051) # try to connect to controller at localhost:9051
except stem.SocketError as exc:
print("Unable to connect to tor on port 9051: %s" % exc)
sys.exit(1)
try:
controller.authenticate('password') # try to authenticate with password "password"
except stem.connection.PasswordAuthFailed:
print("Unable to authenticate, password is incorrect")
sys.exit(1)
# issue 10 requests, changing identity after each request
for i in range(1,10):
# issue request, passing proxies to request
r = requests.get('https://drew-phillips.com/ip-info/', proxies=proxies)
#print(r.text)
m = re.search('<dt>Using Tor:</dt><dd><span[^>]*>Yes', r.text)
if m:
print("You appear to be using Tor successfully. ", end="")
else:
print("Proxy worked but this Tor IP is not known. ", end="")
m = re.search('<dt>IP Address:</dt><dd>(\d+\.\d+\.\d+\.\d+)</dd>', r.text)
if m:
print("Source IP = %s" % m.groups(1))
else:
print("Failed to scrape IP from page")
try:
# send signal to controller to request new identity (IP)
controller.signal(Signal.NEWNYM)
except Exception as ex:
print("NEWNYM failed: %s" % ex)
time.sleep(10)

Reuse parameterized (prepared) SQL Query

i've coded an ActiveDirectory logging system a couple of years ago...
it never become a status greater than beta but its still in use...
i got an issue reported and found out what happening...
they are serveral filds in such an ActiveDirectory Event witch are UserInputs, so i've to validate them! -- of course i didnt...
so after the first user got the brilliant idea to use singlequotes in a specific foldername it crashed my scripts - easy injection possible...
so id like to make an update using prepared statements like im using in PHP and others.
Now this is a Powershell Script.. id like to do something like this:
$MySQL-OBJ.CommandText = "INSERT INTO `table-name` (i1,i2,i3) VALUES (#k1,#k2,#k3)"
$MySQL-OBJ.Parameters.AddWithValue("#k1","value 1")
$MySQL-OBJ.Parameters.AddWithValue("#k2","value 2")
$MySQL-OBJ.Parameters.AddWithValue("#k3","value 3")
$MySQL-OBJ.ExecuteNonQuery()
This would work fine - 1 times.
My Script runs endless as a Service and loops all within a while($true) loop.
Powershell clams about the param is already set...
Exception calling "AddWithValue" with "2" argument(s): "Parameter
'#k1' has already been defined."
how i can reset this "bind" without closing the database connection?
id like the leave the connection open because the script is faster without closing and opening the connections when a event is fired (10+ / sec)
Example Code
(shortend and not tested)
##start
function db_prepare(){
$MySqlConnection = New-Object MySql.Data.MySqlClient.MySqlConnection
$MySqlConnection.ConnectionString = "server=$MySQLServerName;user id=$Username;password=$Password;database=$MySQLDatenbankName;pooling=false"
$MySqlConnection.Open()
$MySqlCommand = New-Object MySql.Data.MySqlClient.MySqlCommand
$MySqlCommand.Connection = $MySqlConnection
$MySqlCommand.CommandText = "INSERT INTO `whatever` (col1,col2...) VALUES (#va1,#va2...)"
}
while($true){
if($MySqlConnection.State -eq 'closed'){ db_prepare() }
## do the event reading and data formating stuff
## bild some variables to set as sql param values
$MySQLCommand.Parameters.AddWithValue("#va1",$variable_for_1)
$MySQLCommand.Parameters.AddWithValue("#va2",$variable_for_2)
.
.
.
Try{ $MySqlCommand.ExecuteNonQuery() | Out-Null }
Catch{ <# error handling #> }
}
Change your logic so that the db_prepare() method initializes a MySql connection and a MySql command with parameters. Set the parameter values for pre-declared parameter names in loop. Like so,
function db_prepare(){
# ...
# Add named parameters
$MySQLCommand.Parameters.Add("#val1", <datatype>)
$MySQLCommand.Parameters.Add("#val2", <datatype>)
}
while($true) {
# ...
# Set values for the named parameters
$MySQLCommand.Parameters.SetParameter("#val1", <value>)
$MySQLCommand.Parameters.SetParameter("#val2", <value>)
$MySqlCommand.ExecuteNonQuery()
# ...
}

Encrypt all existing Stored Procedures with PowerShell sql server

I want to encrypt all stored procedures in existing database
so i tried with shell scripts
$db = (new-Object Microsoft.SqlServer.Management.Smo.Server("SQL_instance")).Databases.Item("[DB_name]")
Foreach ($sp in $db.StoredProcedures){
if(!$sp.IsSystemObject){
if (!$sp.IsEncrypted){
$sp.TextMode = $false;
$sp.IsEncrypted = $true;
$sp.TextMode = $true;
try
{
$sp.Alter();
}
catch{
Write-Host "$sp.Name fail to encrypted."
}
}
}
}
it is working on one of my local server but not on client's server
Source for this
i am getting following error
You script works fine for me - so I would suspect that you may need to run powershell in administrator mode or elevate its privileges..

Perl's REST Client error when trying to use Crontab

Script works well when run manually, but when I schdule it in cronjob it shows :
malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before "<html>\r\n<head><tit...") at /usr/local/lib/perl5/site_perl/5.14.2/JSON.pm line 171.
script itself:
#rest config vaiables
$ENV{'PERL_LWP_SSL_VERIFY_NONE'} = 0;
print "test\n";
my $client = REST::Client->new();
$client->addHeader('Authorization', 'Basic YWRtaW46cmFyaXRhbg==');
$client->addHeader('content_type', 'application/json');
$client->addHeader('accept', 'application/json');
$client->setHost('http://10.10.10.10');
$client->setTimeout(1000);
$useragent = $client->getUseragent();
print "test\n";
#Getting racks by pod
$req = '/api/v2/racks?name_like=2t';
#print " rekvest {$req}\n";
$client->request('GET', qq($req));
$racks = from_json($client->responseContent());
$datadump = Dumper (from_json($client->responseContent()));
crontab -l
*/2 * * * * /usr/local/bin/perl /folder/api/2t.pl > /dmitry/api/damnitout 2>&1
Appreciate any suggestion
Thank you,
Dmitry
It is difficult to say what is really happening, but in my experience 99% issues of running stuff in crontab stems from differences in environment variables.
Typical way to debug this: in the beginning of your script add block like this:
foreach my $key (keys %ENV) {
print "$key = $ENV{$key}\n";
}
Run it in console, look at the output, save it in log file.
Now, repeat the same in crontab and save it into log file (you have already done that - this is good).
See if there is any difference in environment variables when trying to run it both ways and try to fix it. In Perl, probably easiest is to alter environment by changing %ENV. After all differences are sorted out, there is no reason for this to not work right.
Good luck!