?
Solved

Authentication failing when using Powershell to connect to DB2 database

Posted on 2016-11-02
6
Medium Priority
?
224 Views
Last Modified: 2016-11-04
I have a PowerShell script that am using to connect to a DB2 database.

The script has the credentials hard coded at this point, and everything works fine.

I am trying to encrypt the password and call the encrypted password from a file, using get-content in PowerShell and converting to a secure string. Then sending the secure string to the database.

When I try with the encrypted method it gives me an authentication error.

 "ERROR [08001] [IBM][CLI Driver] SQL30082N  Security processing failed
ith reason "24" ("USERNAME AND/OR PASSWORD INVALID").  SQLSTATE=08001"

Can someone please advise how to properly authenticate to a database using this or a similar method to call the plain text encrypted password, to a secure string, and then to the database.

---------EXAMPLE--------------------

Before with plain text password, which works.


$datasource = "database server"
$user = "username"
$pwd = "plaintextpassword"
$connectionString = "Server=$dataSource;uid=$user; pwd=$pwd;Database=$database;Integrated Security=False;"

$query  = "random database query"


$connection = New-Object System.Data.odbc.odbcconnection
$connection.ConnectionString = "DSN=$dataSource;Uid=$user;Pwd=$pwd"
$connection.Open()
$command = $connection.CreateCommand()
$command.CommandText = $query

$result = $command.ExecuteReader()

$table = new-object "System.Data.DataTable"
$table.Load($result)

$format = @{Expression={random table data}
}

$table | Export-CSV C:\folder\output.csv -notype

$connection.Close()



After using encrypted password, which does not work.

$datasource = "database server"
$user = "username"
$pwd = Get-Content "C:\folder\encrypted.txt | ConvertTo-SecureString
$database = "Database_name"
$connectionString = "Server=$dataSource;uid=$user; pwd=$pwd;Database=$database;Integrated Security=False;"

$query  = "random database query"


$connection = New-Object System.Data.odbc.odbcconnection
$connection.ConnectionString = "DSN=$dataSource;Uid=$user;Pwd=$pwd"
$connection.Open()
$command = $connection.CreateCommand()
$command.CommandText = $query

$result = $command.ExecuteReader()

$table = new-object "System.Data.DataTable"
$table.Load($result)

$format = @{Expression=random table data}

$table | Export-CSV C:\folder\output.csv -notype

$connection.Close()
0
Comment
Question by:cmoerbe
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
6 Comments
 
LVL 85

Accepted Solution

by:
oBdA earned 2000 total points
ID: 41871073
This allows you to save the password directly in the script itself, as "Alternate Data Stream".
The password can only be retrieved on the machine where it was saved, and only from the user who saved it.
Call the script with the argument -SaveCredential to save the credentials.
It's currently in test mode (lines 40-43) and will only display the logon information, then exit.
Note that some Editors (like Notepad++) remove ADS on saving, others do not (like Notepad).
The ADS will be copied as long as the target is NTFS, and will be lost otherwise.

[CmdletBinding()]
Param(
	[switch]$SaveCredential
)
$DataSource = "database server"
$DefaultUser = "username"

$ScriptItem = Get-Item -Path $MyInvocation.MyCommand.Path
$StreamName = 'MetaData'
If ($SaveCredential) {
	$gcArgs = @{'Message' = "ODBC logon information for $($DataSource)"}
	$gcArgs['User'] = Try {([Management.Automation.PSSerializer]::Deserialize((Get-Content -Path $ScriptItem.FullName -Stream $StreamName -ErrorAction SilentlyContinue))).UserName} Catch {$DefaultUser}
	If ($Credential = Get-Credential @gcArgs) {
		Try {
			$LastWriteTimeUtc = $ScriptItem.LastWriteTimeUtc
			Set-Content -Path $ScriptItem.FullName -Value ([Management.Automation.PSSerializer]::Serialize($Credential)) -Stream $StreamName -ErrorAction Stop
			$ScriptItem.LastWriteTimeUtc = $LastWriteTimeUtc
		} Catch {
			Throw "Could not save credentials: $($_.Exception.Message)"
		}
	} Else {
		"No credentials were entered, logon information was not saved!" | Write-Warning
	}
	Exit
} Else {
	If ($StreamData = (Get-Content -Path $ScriptItem.FullName -Stream $StreamName -ErrorAction SilentlyContinue)) {
		Try {
			$Credential = [Management.Automation.PSSerializer]::Deserialize($StreamData)
		} Catch {
			Throw "You are not authorized to use this script."
		}
	} Else {
		Throw "File is corrupted, password information is not available."
	}
}

$Username = $Credential.UserName
$Password = $Credential.GetNetworkCredential().Password

##### REMOVE AFTER TESTING #########################
"Username '$($UserName)', password '$($Password)'" #
EXIT                                               #
##### REMOVE AFTER TESTING #########################

$connectionString = "Server=$dataSource;uid=$Username;pwd=$Password;Database=$database;Integrated Security=False;"

$query  = "random database query"


$connection = New-Object System.Data.odbc.odbcconnection
$connection.ConnectionString = "DSN=$dataSource;Uid=$Username;Pwd=$Password"
$connection.Open()
$command = $connection.CreateCommand()
$command.CommandText = $query

$result = $command.ExecuteReader()

$table = new-object "System.Data.DataTable"
$table.Load($result)

$format = @{Expression={random table data}
}

$table | Export-CSV C:\folder\output.csv -notype

$connection.Close()

Open in new window

0
 

Author Comment

by:cmoerbe
ID: 41871470
Thank you, very much!

Please allow me a moment to test this out.
0
 

Author Comment

by:cmoerbe
ID: 41874288
I tried commenting everything out below line 44 to just test storing and retrieving the credentials.

It prompts for the credentials and exits, but does not display them back before exit. No errors generated either. Unable to determine if it saved them or not. It is NTFS and only using notepad to work with the file before .ps1.

Any thoughts?
0
Python: Series & Data Frames With Pandas

Learn the basics of Python’s pandas library of series & data frames and how we can use these tools for data manipulation.

 
LVL 85

Assisted Solution

by:oBdA
oBdA earned 2000 total points
ID: 41874304
the EXIT in line 42 will currently prevent the rest of the script running, no need to uncomment it.
You call the script once with -SaveCredentials; it will prompt for the credentials and store them.
Then you call the script again without arguments, and it should print the stored username and password.
If you call the script without arguments while no credentials are stored, you'll get an error message.
0
 

Author Comment

by:cmoerbe
ID: 41874469
Works like a champ! Thanks for providing this alternate solution. I do prefer it to my original plan.

Best regards
0
 

Author Closing Comment

by:cmoerbe
ID: 41874471
Thank you again for the assistance
0

Featured Post

Simplifying Server Workload Migrations

This use case outlines the migration challenges that organizations face and how the Acronis AnyData Engine supports physical-to-physical (P2P), physical-to-virtual (P2V), virtual to physical (V2P), and cross-virtual (V2V) migration scenarios to address these challenges.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In the absence of a fully-fledged GPO Management product like AGPM, the script in this article will provide you with a simple way to watch the domain (or a select OU) for GPOs changes and automatically take backups when policies are added, removed o…
Check out the latest tech news, community articles, and expert highlights in August's newsletter.
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, just open a new email message. In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…

800 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question