Azure SQL | PowerShell ISE vs PowerShell CLI - attempt was made to access a socket in a way forbidden by its access permissions - sql

I have a really frustrating situation here. There is a PowerShell script that logs into the Azure SQL, queries table, and saves results into the .csv file. Connection string looks like this:
$DatabaseUrl = "mycompany-***-***-dev-use4-01.database.windows.net"
$DatabaseName = "MyDataBase"
$conn = New-Object System.Data.SqlClient.SQLConnection
$conn.ConnectionString = "Data Source=$DatabaseUrl;Initial Catalog=$DatabaseName;Connect Timeout=20"
$conn.AccessToken = $token
$conn.Open
On $conn.Open line the script throws this error:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 0 - An
attempt was made to access a socket in a way forbidden by its access permissions
Now, the frustration comes when this script works perfectly fine in PowerShell ISE, but not in PowerShell CLI (command line). I have searched millions of posts probably by now, still not finding any solution. I tried to run CLI as an administrator, tried to Import-Module -SQLServer -Scope CurrentUser and others. Honestly, I have absolutely no idea why the script would work in ISE but not in CLI. Are those 2 different environments/scripting languages? Thank you for all your help

Related

Azure Release Pipelines: Azure SQL Database deployment error with not able to get to database server

We are seeing an error when trying to run a .SQL file on our Azure Dev Ops release pipeline:
Here is the error:
System.Management.Automation.RuntimeException: No resource found with serverName [the server], serverType Microsoft.Sql/servers in subscription [subscription id]. Specify the correct serverName/serverType and try again.Check out how to troubleshoot failures at https://aka.ms/sqlazuredeployreadme#troubleshooting-
We do have this set to checked on the networking tab of the sql server database:
I've checked the database server name and everything is correct.
It has something to do with the firewall rules though, but we can't figure out why we can't release our migration scripts to run auto.
Any other ideas of what else we can try?
Thanks.
UPDATE 1:
We have about 5 other instances that are set up the same way that seem to work fine.
Update 2:
Here is the Release step we are doing to push a .sql file to Azure Database which is failing:
Answer:
We removed the tcp: of of the server= part of the connection string and it worked.
Failed:
Server=tcp:server.database.azure.net,1433;Initial Catalog=[enter-db-nm];Persist Security Info=False;User ID=[enter-userid];Password=[enter-pw];MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;App={0}
Worked:
Server=server.database.azure.net,1433;Initial Catalog=[enter-db-nm];Persist Security Info=False;User ID=[enter-userid];Password=[enter-pw];MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;App={0}
We could leave the tcp: of of the server= and open up all ip addresses and it would work.
Suppose the tcp does something on the back side.
You can use the tcp: fine with logging into the database from SSMS.

How do I know what user my ADO pipeline is using?

I'm using Azure DevOps pipelines, and have a PowerShell task that runs stuff with Invoke-Sqlcmd. The PowerShell works fine when run from my computer, but when it runs through the pipeline it says it can't find or doesn't have access to the server. I don't see anything in the failed connection logs on my sql servers...
I assume whatever account the pipeline is attempting to connect under does not have access. How can I find out what that account is?
If you're curious, here's the simple PS, it just updates a table:
Invoke-Sqlcmd -ServerInstance "myremoteserver" -Query "--update the table"
You can add a powershell task to run below script to get the current user account that your pipeline is using
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name

Powershell script to execute DDL statements on linked servers - not working when run using SSIS

I have a Powershell script that loops through a list of SQL Servers and creates server logins and database users.
The script runs on a separate server, under the administrator credentials on that server, and connects to the other SQL Servers via linked servers.
#Get administrator credentials
$password = get-content C:\Powershell\General\password.txt | convertto-securestring;
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "DOMAIN\administrator",$password;
When this script is run manually (either directly through a Powershell window or using a batch file through a command prompt) it works perfectly well. I am logged onto the executing server as administrator when running the script manually.
I then tried to run this Powershell script using an SSIS package on the executing server, using the Execute Process Task to run a batch file. The package was executed from a SQL Agent Job. Although both the job and the package seemed to execute successfully, the DDL statements were not executed against the linked servers.
SQL Agent on the executing server is run under a designated Service Account. SSIS runs under the Network Service account.
Does anybody have any thoughts on what I might be doing wrong? I am happy to provide details of the script or anything else that is required.
Thanks
Ash
UPDATE: ok we have a little more information.
I took out the lines I posted above as I have discovered I don't actually need the administrator credentials I was retrieving.
I logged onto the server with the script on it using the service account. As per #ElecticLlama's suggestion I set a Profiler trace on the destination server. When running the script manually (or running a batch file manually that runs the Powershell script) everything works well and the Profiler shows the DDL actions, under the service account login.
When running a job through SQL Agent (either a CmdExec job or an SSIS package) that runs the same batch file, I get the following error:
'Login failed for user 'DOMAIN\ServiceAccount'. Reason: Token-based server access validation failed with an infrastructure error.'
Anybody have any further thoughts?
Thnaks to everyone for their help. Once I got that last error a quick search revealed I just had to restart SQL Agent and now everything works as it should. Thanks in particular to #ElecticLlama for pointing me in the right direction.
Ash

Perl DBI login fail:SQL Server does not exist or access denied

Description: I installed SQL Server 2012 on my local machine(Windows 7). At first I installed with Windows authentication. After searching on web, I change to SQL Server authentication and set as: In SQL Server Management Studio->object explorer->security->logins->sa->right click property, select SQL Server authen and set password as "!Abcd1234!" for example.
Then I tried that I can connect by SQL Server authentication with sa/password using Management Studio. But using Perl script I failed.
My simple Perl script as below:
use strict;
use warnings;
use dbi;
my $user = "sa";
my $password = "!Abcd1234!";
my $connect = DBI->connect("dbi:ODBC:Driver={SQL Server};Server=127.0.0.1;UID=$user;PWD=$password")or die "Error: $DBI::errstr\n";
I got error
Error: [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied. (SQL-08001) [state was 08001 now 01000]
[Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()). (SQL-01000)
May I get any help or trace method?
Yes, Mitch Wheat, I do enable "sa" account in the status tab. Sorry missing to mention that. I doubt whether my Perl script is correct? I think access locally should have no firewall issues right?
I have connected many a times from perl (running on linux) to the MSSQL server. and while doing so, I would create a DSN manualy on the my Linux box and then write below syntax to connect:
my $dbh = DBI->connect ('dbi:ODBC:odbc-test', 'sqluser_name', 'sqluser_password');
Where, odbc-test is the name of the DSN
And it always worked.
unfortunately I never done any perl DBI connection from windows.
So,
On your windows box, could you create a DSN manually first and then follow above mentioned syntax to connect to the MSSQL server .
You should using ODBC administrator to test the connection first.

bcp error while exporting data using management studio in sql 2005 express but not using DOS

i am using sql server 2005 express edition .
when i export data via bcp utility using dos prompt then there is no error ,
but when i created a stored procedure for the export process and use management studio express for exporting data then it gives the following error :
SQLState = S1000, NativeError = 0
Error = [Microsoft][SQL Server Native Client 10.0]Unable to open BCP host data-file
Please help.
I had the same issue, but the answer is that I was being less than bright.
As the command was being run on a server, not my local machine, it was trying to write to a non-existent folder on the server. It was executing successfully against the root of C: but not against my share folder, C:\share. The problem for me was that I was looking for the file in the root of my C Drive, not the servers.
When I changed the path to \mymachinename\share, everything worked.
When you run the bcp utility using the DOS command line you are using the logged in persons credentials (usually your own), but when running as a stored procedure you are using the credentials of the SQL server process, which usually is configured to have much less permissions than ordinary users in order to provide safety against various attacks.
Check in the Services list of which user is used for the SQL server database engine and check if that user has enough read/write permissions to the directories and files involved.