How to authenticate a Firewall web page via Powershell / Selenium-Chrome Driver? - powershell

I developed several scripts in Powershell to automate the configuration of machines where I work, streamlining and avoiding the hard work of manually configuring a huge amount of stations. Basically they use disable UAC, autologon, and Task Scheduler.
Image: https://i.stack.imgur.com/pkuDl.png
The biggest problem is the use of the Fortinet Firewall that asks for authentication via browser, since much of the application uses files for installation that are on the server via SMB, it is necessary to do this authentication, because without it it is not possible for the algorithm to authenticate to the server, causing it to fail on the course.
Image: https://i.stack.imgur.com/bqZAR.png
Page URL: https://authenticator.mpms.mp.br/caplogin/?login&post=http://10.111.147.1:1000/fgtauth&magic=0202e294cb1c7073&usermac=10:e7:c6:c5:c3:61&apmac=00:00:00:00:00:00&apip=10.111.147.1&userip=10.111.147.22&ssid=PGJ-BANCADA&apname=FGT2KE3917900027&bssid=00:00:00:00:00:00&device_type=windows-pc
However, by testing this through Selenium it even authenticates, but after the computer restarts and runs the next script, it asks for authentication again.
Follow the code that I made to authenticate in Fortnet, followed after the login, to make a request in the globo.com site
############################################
######## Enable Fortinet Firewall ##########
############################################
$YourURL = "https://authenticator.mpms.mp.br/"
# Adds the path for ChromeDriver.exe to the environmental variable
$env:PATH += ";C:\Util\PSL\"
# Adding Selenium's .NET assembly (dll) to access it's classes in this PowerShell session
Add-Type -Path "C:\Util\PSL\WebDriver.dll"
$ChromeOptions = New-Object OpenQA.Selenium.Chrome.ChromeOptions
$ChromeDriver = New-Object OpenQA.Selenium.Chrome.ChromeDriver($ChromeOptions)
$ChromeDriver.Capabilities.BrowserName
# Browse to the specified website
$ChromeDriver.Navigate().GoToURL($YourURL)
# Methods to find the input textbox for google search and then to type something in it
$ChromeDriver.FindElementByName("username").SendKeys("username")
$ChromeDriver.FindElementByName("password").SendKeys("password")
$ChromeDriver.FindElementsByClassName("submit").Submit()
#### New page #####
$YourURL = "https://www.globo.com/"
$ChromeDriver.Navigate().GoToURL($YourURL)
Function Stop-ChromeDriver {Get-Process -Name chromedriver -ErrorAction SilentlyContinue | Stop-Process -ErrorAction SilentlyContinue}
# Close selenium browser session method
$ChromeDriver.Close()
# End ChromeDriver process method
$ChromeDriver.Quit()
# Function to make double sure the Chromedriver process is finito (double-tap!)
Stop-ChromeDriver
When we do this manually, the next steps will run normally, which by my conclusion makes the Selenium driver not really the Google Chrome browser, but rather its own one, which means that it does not recognize authentication. .
The question that remains is: Is it possible to add this option in the script so that we can authenticate to Fortinet Web and thus avoid manual steps and automate our work? I wish I could perform this task for Powershell, but I'm available with another alternative.
Thank you!

Why not use vbs in PowerShell` to send required authorizations?
$wshell = New-Object -ComObject wscript.shell; $obj = New-Object -com Wscript.Shell;
$wshell.AppActivate('Chrome');
pathping 127.0.0.1 -n -q 1 -p 300 >$null
$obj.SendKeys('paulogoncalves');
pathping 127.0.0.1 -n -q 1 -p 150 >$null
$obj.SendKeys("{TAB}")
pathping 127.0.0.1 -n -q 1 -p 150 >$null
$obj.SendKeys('senhasecreta')
pathping 127.0.0.1 -n -q 1 -p 150 >$null
$obj.SendKeys('{ENTER}');```

Related

Screenshot selenium : Web window and toolbars

My goal is the following : take a screenshot of a web page (opened with selenium) where the panel (toolbar) is present in order to see the time on it. This should be scheduled automatically.
I have : a linux VM and a windows computer
What I did :
Script myscript.ps1
Import-Module Selenium
Import-Module Scraping
# $url = "https://sanctionssearch.ofac.treas.gov/"
$url = "https://www.google.com/"
$driver = Start-SeChrome -Quiet -Incognito -Maximized
Enter-SeUrl $url -Driver $driver
waitdriver $driver
#############################################################################
# Capturing a screenshot
#############################################################################
scrot test.png
#############################################################################
$driver.Close()
$driver.Quit()
When I run this directly from my linux virtual machine, I get what I want (web window and panel):
But my goal is to schedule it, so I used an ssh connection from windows with the following command:
$commande='cd myfolderpath; export PATH=$PATH:/snap/bin;'+ "xvfb-run -a nice -n20 pwsh myscript.ps1"
ssh -i "${env:\userprofile}\.ssh\spinlinux2_key.pem" linuxvm#52.8.3.2 $commande
But now I don't get the toolbar in capture but only the web page:
Is there any other way to proceed? It can also be directly scheduled from windows without going through the linux machine.
Thanks for all your answers.

Connecting Exchange Online Fails when passing proxy and running in System PowerShell - TokenProvider Returns Object Reference Error

I was connecting Exchange Online using a PowerShell window that is opened with system access. I used PSExec on an elevated Command Prompt to open the System access PowerShell. Below is the command.
PSExec -i -s PowerShell
On the PowerShell, I imported the latest Exchange Online Management PowerShell module version 2.0.3. I use the app-based authentication described here: https://learn.microsoft.com/en-us/powershell/exchange/app-only-auth-powershell-v2?view=exchange-ps#setup-app-only-authentication.
There is one more website that shows how to connect with app-based authentication: https://o365reports.com/2020/07/04/modern-auth-and-unattended-scripts-in-exchange-online-powershell-v2.
Below are the commands used to connect to Exchange Online.
Import-Module .\ExchangeOnlineManagement
$sessopt = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck -ProxyAccessType IEConfig
$certkey = ConvertTo-SecureString "<EnterCertificateKeyHere>" -AsPlainText -Force
Connect-ExchangeOnline -CertificateFilePath "pfx Certificate Path" -AppId <EnterAppIdHere> -Organization "domain.onmicrosoft.com" -CertificatePassword $certkey -PSSessionOption $sessopt -verbose
When running the above, it returns Object Reference error. I got excited and went on to find what the error is by decompiling the DLL files and found that inside the 'ExoPowershellGalleryModule.dll -> NewExoPSSession.cs' of the Exchange module, the 'GetAccessToken' function which is called around line:308 causes this error. Any idea what makes the Object reference not set to an instance of an object. System.Management.Automation.RemoteException: Object reference not set to an instance of an object. error. Was the proxy not taken from IE?
I've set the proxy settings in IE using the below Powershell command-lets in system PowerShell.
Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings' -name ProxyServer -Value "ProxyServerAddress"
Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings' -name ProxyEnable -Value 1
Any help to resolve this is appreciated.
If your using
PSExec -i -s PowerShell
Then the proxy information your entering for the user will have no effect because the local system account will have its own profile information. Also if the proxy needs authentication you also won't be presenting any Network credentials.
If you really want to run under the system account you could try using netsh to configure the proxy https://learn.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/configure-proxy-internet but if you proxy need authentication this won't work.

PowerShell - File transfer from windows to unix

I am working on UIpath automation for which I need some files to be transferred back and forth between Windows and Unix machines (only through PowerShell). Kindly provide your inputs as I'm a newbie.
I am using plink in my PowerShell script to connect to a Unix server. Though it works fine, is there any other better way to connect to a Unix server (HP UX) from Windows (through a PowerShell script).
Struggling to find a good module and sample scripts to do a secure copy between the Unix and Windows servers. I came across Posh SSH /WinSCP, sftp etc. but I'm not able to implement any as I do not find the right sample scripts. Also Install-Module does not work (not recognized).
Your help on this would be much appreciated.
Thanks in advance!
If you want to use SFTP I am using the code below to upload some files automatically to an ftp site:
First of all you have to download the winscp SFTP powershell libraries.
https://winscp.net/eng/download.php
then extract the contents at the same location the script is located.
Then in your script you must add:
# Load WinSCP .NET assembly
# Give the path the dll file is located so powershell can call it.
Add-Type -Path "C:\Path where the dll file is located\WinSCPnet.dll"
# Setup session options
# Add all the properties the session needs to be established such as username password hostname and fingerprint.
# The username and password must be in plaintext.
$sessionOptions = New-Object WinSCP.SessionOptions -Property #{
Protocol = [WinSCP.Protocol]::Sftp
HostName = "HostName"
UserName = "UserName"
Password = "Password"
SshHostKeyFingerprint = "SSH fingerprint"
Then after the session with those credentials is up you must put your next step of copying the files.
# Open a session to the Host
# Try to connect to the Host with the credentials and information provided previously.
# Upload the file from a specific path to the path on the host.
# And then close the session and clean up the session trace data.
# $session.Dispose() -> If session was opened, closes it, terminates underlying WinSCP process, deletes XML log file and disposes object.
$session = New-Object WinSCP.Session
Try
{
# Connect to the SFTP site
$session.Open($sessionOptions)
# Upload the files from local disk to the destination
$session.PutFiles("Path of the file you want to upload", "/import/").Check()
}
Finally
{
# Disconnect, clean up
$session.Dispose()
}
Probably there is an easier way with Power Shell 6 that can do more with the Unix/Linux operating systems but at this point of answering I haven't used it.
Once you get Posh-SSH installed, something like this will probably get you down the road. There are ways to keep the password in plain text out of your script.
$SecurePassword = ConvertTo-SecureString -AsPlainText 'thepassword' -Force
$Credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList 'me',$SecurePassword
$Session = New-SFTPSession -ComputerName 'zenith' -Credential $Credentials -ConnectionTimeout 30
$r = Set-SFTPFile -Session $Session. -LocalFile 'C:\Users\me\t.txt' -RemotePath '/home/me' -Overwrite
Remove-SFTPSession -SFTPSession $session | Out-Null

How do I run Invoke-WebRequest cmdlet from third party program?

I have been trying to get this to work via a game control panel TCAdmin.
$ModPg1 = Invoke-WebRequest "http://steamcommunity.com/sharedfiles/filedetails/?id=731604991"
$ModVer1 = ($ModPg1.ParsedHtml.getElementsByTagName('div') | Where{ $_.className -eq 'detailsStatRight' } ).innerText | Select -Last 1
If I run this cmdlet via a program like TCAdmin (or task scheduler), I get the following error....
Invoke-WebRequest : The response content cannot be parsed because the Internet Explorer engine is not available, or Internet Explorer's first-launch configuration is not complete. Specify the UseBasicParsing parameter and try again.
Explorer is installed, and set up. The script works just fine if I run it manually.
My guess is there is a way to get TCAdmin to run the scripts the same way I would as a windows User.
Cant find a way nearly as simple to scrape the info 'm looking for.
As for this...
get TCAdmin to run the scripts the same way I would as a windows User.
For any app to run as a user, that users profile must be used on the host where the code is to be run. You cannot natively run PoSH on a host as another user context. This is not a PoSH issue, it is a Windows User Principal security boundary. There are tools that let you do this. For example SysInternal PSExec and AutoIT. Yet as stated that error is pretty specific. The user profile for Internet Explorer has not been created and that only happens when you use IE at least once.
So, as Adam points, out, use the setting the error message states to use or use your code to start IE at least once.
$SomeUrl = 'https://stackoverflow.com'
$ie = New-Object -com internetexplorer.application
$ie.visible = $true
$ie.navigate($SomeUrl)
while ($ie.Busy -eq $true) { Start-Sleep -Seconds 1 } # Wait for IE to settle.
Again, if trying to run this in the context of another user, the two above tools will get you there, but you still have to fire up IE to have a profile for it.

How to get telnet output on PowerShell?

I thought I could run the command as below on PowerShell.
$output = & echo quit | telnet localhost 22
echo $output
However,
$output has nothing in it.
I'm trying to verify ssh or telnet connection.
Could you please tell me how to get output from above command ?
It is not possible. MS telnet doesn't use stdin/out. See here: C# + telnet process w/ redirected standard streams quits immediately
For redirecting the output of a telnet session you can use the -f logfile argument and then importing it into a variable after you are done with it: $output = get-contents logfile
For sending keycommands to telnet you could use $wshell = new-object -com wscript.shell and then:
start-process telnet -argumentlist "-f w:\tmp\log.txt";
sleep 1;
$wshell.SendKeys("quit{ENTER}")
Yes I know... not what you would expect, but it is the only way afaik with the MS builtin telnet console. If you know any better way, I would be glad to hear about it.
If you only want to check open ports, then why not just query them instead of telnetting? See here.
try this script and add it at start and end of your command to capture every logs
$ipV4 = (Test-Connection -ComputerName (hostname) -Count 1).IPV4Address.IPAddressToString -- this
Start-Transcript -Path .\TraceLogs_$ipV4.txt
<**Add your code here**>
Stop-Transcript
Here $ipV4 will capture the source host and logs will be generated in as file name .\TraceLogs_$ipV4.txt
Trying to adapt this for collecting Telnet output from APC PDUs (reading current load). The specified keys are successfully entered and the output is generated in the telnet session window, but the window doesn't close once the telnet session is ended. It stays open with "Connection to host lost."
I can press any key to close the window, but PS script execution does not continue, so no code following the SendKeys statement is executed.
Am I missing something simple? Code below.
$wshell = new-object -com wscript.shell
start-process telnet -argumentlist "pdu1-a6.domain.local -f c:\temptelnet.log"
sleep 1
$wshell.SendKeys("username{ENTER}password{ENTER}current{ENTER}quit{ENTER}")
$telnetoutput = get-content c:\temptelnet.log
$telnetoutput