Sql ошибка входа пользователя гость

  • Remove From My Forums
  • Общие обсуждения

  • Настроил порт, firewall и т.п. Проверил через telnet порт, все ОК. При подключении к базе с удаленного ПК по локальной сети, выдается ошибка, типа проблемы с пользователем «Гость» на сервере.

    Создать пользователя никак на сервере не получается. Все какие-то ошибки. Делал по инструкциям, типа таких:
    http://msdn.microsoft.com/ru-ru/library/aa337545.aspx

    В сервере я не силен. Мне бы хотя бы основы настроить, чтобы все работало.

    Какие действия нужно сделать, чтобы можно было подключиться удаленно к нужной базе и как правильно подключаться? База нужна для CRM, которая на других ПК. Сетка одноранговая, стоит и XP и 7.

    • Изменен тип

      3 июня 2011 г. 13:36

  • Remove From My Forums
  • Question

  • Good day to you.
    I try to attach a database mdf file to Microsoft SQL server 2014 on Amazon Elastic Computing Cloud, EC2, but fail with the following message, 
    «User ‘guest’ does not have permission to run DBCC checkprimaryfile. (Microsoft SQL Server, Error: 2571)»
    The ID I use to REMOTE login has administrator rights and I have chosen to «run as administrator»
    Please help, and thanks.

Answers

  • Hi go9189,

    According to your description, you come across the error that User ‘guest’ does not have permission to run DBCC checkprimaryfile. This issue could happen when the login account doesn’t have CREATE DATABASE, CREATE ANY DATABASE,
    or ALTER ANY DATABASE permission in SQL Server instance, or that the login account has no access to the mdf and ldf files when attaching database, so SQL Server recognize the login account as a «Guest».

    To solve the issue, you could pay attention to the points below.

    1. Ensure that the login account has at least CREATE DATABASE, CREATE ANY DATABASE, or ALTER ANY DATABASE permission. You could grant the fixed server role ‘dbcreator’ or ‘sysadmin’ to the login account following the steps below.

    a. Connect to SQL Server instance with the login account which has sysadmin fix server role.

    b. Expand the folder ‘Security’, right click the login, and select Properties.

    c. In the Server Roles tab, check the checkbox for ‘dbcreator’ or ‘sysadmin’.

    2. Make sure that the the login account has full control permission on the mdf and ldf files. For how to grant the login account with full control permission on the mdf and ldf files, please refer to the steps in the following article:
    http://msdn.microsoft.com/en-us/library/bb727008.aspx

    There is a similar thread for your reference:
    https://social.technet.microsoft.com/Forums/en-US/e463df4c-8d26-46cf-aa2e-bddd97c7a9b8/user-guest-does-not-have-permission-to-run-dbcc-checkprimaryfile?forum=sqlgetstarted

    Regards,
    Michelle Li

    • Edited by

      Tuesday, January 20, 2015 2:18 PM

    • Proposed as answer by
      Michelle Li
      Friday, January 23, 2015 1:47 AM
    • Marked as answer by
      Lydia ZhangMicrosoft contingent staff
      Tuesday, January 27, 2015 3:49 AM
  • Remove From My Forums
  • Question

  • Good day to you.
    I try to attach a database mdf file to Microsoft SQL server 2014 on Amazon Elastic Computing Cloud, EC2, but fail with the following message, 
    «User ‘guest’ does not have permission to run DBCC checkprimaryfile. (Microsoft SQL Server, Error: 2571)»
    The ID I use to REMOTE login has administrator rights and I have chosen to «run as administrator»
    Please help, and thanks.

Answers

  • Hi go9189,

    According to your description, you come across the error that User ‘guest’ does not have permission to run DBCC checkprimaryfile. This issue could happen when the login account doesn’t have CREATE DATABASE, CREATE ANY DATABASE,
    or ALTER ANY DATABASE permission in SQL Server instance, or that the login account has no access to the mdf and ldf files when attaching database, so SQL Server recognize the login account as a «Guest».

    To solve the issue, you could pay attention to the points below.

    1. Ensure that the login account has at least CREATE DATABASE, CREATE ANY DATABASE, or ALTER ANY DATABASE permission. You could grant the fixed server role ‘dbcreator’ or ‘sysadmin’ to the login account following the steps below.

    a. Connect to SQL Server instance with the login account which has sysadmin fix server role.

    b. Expand the folder ‘Security’, right click the login, and select Properties.

    c. In the Server Roles tab, check the checkbox for ‘dbcreator’ or ‘sysadmin’.

    2. Make sure that the the login account has full control permission on the mdf and ldf files. For how to grant the login account with full control permission on the mdf and ldf files, please refer to the steps in the following article:
    http://msdn.microsoft.com/en-us/library/bb727008.aspx

    There is a similar thread for your reference:
    https://social.technet.microsoft.com/Forums/en-US/e463df4c-8d26-46cf-aa2e-bddd97c7a9b8/user-guest-does-not-have-permission-to-run-dbcc-checkprimaryfile?forum=sqlgetstarted

    Regards,
    Michelle Li

    • Edited by

      Tuesday, January 20, 2015 2:18 PM

    • Proposed as answer by
      Michelle Li
      Friday, January 23, 2015 1:47 AM
    • Marked as answer by
      Lydia ZhangMicrosoft contingent staff
      Tuesday, January 27, 2015 3:49 AM

  

Devastator

08.12.13 — 14:06

Здравствуйте, срочно нужна помощь, я забыл пароль пользователя sa на сервере SQL 2008 и решил его поменять, для того чтобы создать новую базу 1с, но после его смены я утратил доступ к старой базе данных, как можно решить эту проблему, как теперь можно получить доступ к старой базе ? Вот само сообщение об ошибке

Ошибка при выполнении запроса POST к ресурсу /e1cib/login:

по причине:

Ошибка при выполнении операции с информационной базой

Ошибка СУБД:

Microsoft SQL Server Native Client 10.0: Ошибка входа пользователя «sa».

HRESULT=80040E4D, SQLSrvr: SQLSTATE=28000, state=1, Severity=E, native=18456, line=1

  

Armando

1 — 08.12.13 — 14:15

хз. может MSSQL переустановить и сделать новый пароль

  

Lionee

2 — 08.12.13 — 14:18

(0)ищи ответ на sql.ru

  

Devastator

3 — 08.12.13 — 14:27

Я думаю переустановка SQL не решит проблему так как сам sql я запускаю от имени sa, а вот 1с уже не запускается, потому что видимо пароль там остался в таблицах старый прописан и он не совпадает с нынешним и поэтому не заходит, как вот теперь его там поменять, вот это вопрос

  

ДенисЧ

4 — 08.12.13 — 14:29

грохни ссылку на базу и создай снова

  

Devastator

5 — 08.12.13 — 14:32

Денис можно чуть поподробнее, создать из 1с чтоли с таким же именем то есть ?

  

Devastator

6 — 08.12.13 — 14:32

Точно блин

  

Devastator

7 — 08.12.13 — 14:32

Сейчас попробую

  

Devastator

8 — 08.12.13 — 14:43

Нет не помогает

  

probably

9 — 08.12.13 — 14:59

Если ты можешь зайти в менеджмент сдудио с правами админа, создай пользователя 1с, например, дай ему права на базы.

Удали все базы из консоли сервера предприятия и подключи заново

  

Либерал

10 — 08.12.13 — 15:05

(8) значит не то делаешь. убей базу (это и есть ссылка) в консоле сервера 1С (не на sql-сервере!) и создай заново с новым паролем подключения к бд.

  

Либерал

11 — 08.12.13 — 15:07

и вообще, запускать базы 1с из под sa — ламерство какое-то.

наверное еще сами файлы баз в програмфайлс лежат? хаха

  

Devastator

12 — 08.12.13 — 15:48

Описываю свои действия. Я удаляю ссылку в 1с окне запуска, добавляю новую, все прописываю и не важно что я прописываю в поле логин и пароль, он все равно ругается на доступ пользователя SA. Я пробовал и админа туда писать, все равно ошибка входа пользователя SA

  

probably

13 — 08.12.13 — 15:51

(12) воскресный тупешь? Тебе черным по-русски написали, что в консоле сервера предприятия

  

Devastator

14 — 08.12.13 — 15:58

)))) Пардон, да, затупил малость, сейчас буду исправляться и пробовать ))

  

Devastator

15 — 08.12.13 — 16:43

Если я в консоле сервера, то сама база не удалится же, а то он мне тут вопросы задает удалить базу данных, очистить базу данных ? Я просто первый раз с консолью работаю

  

Devastator

16 — 08.12.13 — 16:43

Если я в консоле сервера удаляю

  

Devastator

17 — 08.12.13 — 17:29

Поменял пароль доступа к базе в консоле, теперь удалить не получается потому что пароль почему то стал спрашивать при доступе к базе из консоли и пароль который вводил почему то не подходит, блин что делать ?

  

Devastator

18 — 08.12.13 — 17:51

А, понял она требует пароли самих пользователей 1с

  

Devastator

19 — 08.12.13 — 18:09

Короче проблема решена, убивать базу в консоле сервера 1с нельзя, это приводит к физическому ее удалению, я поменял там пароль пользователя БД и прописал заного путь к базе в окне запуска 1с и все подключилось. Всем огромное спасибо! )

  

Lionee

20 — 08.12.13 — 18:25

песец

  

Devastator

21 — 08.12.13 — 18:32

)))) Я сам в шоке )))

  

fyn

22 — 08.12.13 — 18:59

(19) вам за такую работу еще и деньги наверное платят?

  

Devastator

23 — 08.12.13 — 22:11

Fyn, за что кому платят вас не касается, а вам походу платят за острый юмор, которым вы наверно только учитесь пользоваться. Если я здесь задал пару бестолковых вопросов это еще не значит что работа выполняется плохо. Умник тоже мне нашелся.

  

hhhh

24 — 08.12.13 — 23:02

(23) дык смешно, похоже вам с самого начала надо было ввести пароль к базе, а вы тут развели…

  

Devastator

25 — 09.12.13 — 22:32

Да, вышло конечно глуповато, и что дальше, на ошибках учатся, главное делать правильные выводы и больше их не повторять, здесь мне вообще советовали базу там грохнуть, грохнул бы я ее в консоле и похерилась бы вся инфа, пришлось бы восстанавливать. Дельный совет дали «убей базу да и все». Почему то этого «смешного» решения никто не заметил, просто я с самого начала совсем забыл про эту консоль, нужно было сразу там смотреть.

  

ДенисЧ

26 — 09.12.13 — 22:42

«убивать базу в консоле сервера 1с нельзя, это приводит к физическому ее удалению»

Какая чушь…. Оно же спрашивает, причём по-русски, что делать с базой…..

By default login failed error message is nothing but a client user connection has been refused by the server due to mismatch of login credentials. First task you might check is to see whether that user has relevant privileges on that SQL Server instance and relevant database too, thats good. Obviously if the necessary prvileges are not been set then you need to fix that issue by granting relevant privileges for that user login.

Althought if that user has relevant grants on database & server if the Server encounters any credential issues for that login then it will prevent in granting the authentication back to SQL Server, the client will get the following error message:

Msg 18456, Level 14, State 1, Server <ServerName>, Line 1
Login failed for user '<Name>'

Ok now what, by looking at the error message you feel like this is non-descriptive to understand the Level & state. By default the Operating System error will show ‘State’ as 1 regardless of nature of the issues in authenticating the login. So to investigate further you need to look at relevant SQL Server instance error log too for more information on Severity & state of this error. You might look into a corresponding entry in log as:

2007-05-17 00:12:00.34 Logon     Error: 18456, Severity: 14, State: 8.
or

2007-05-17 00:12:00.34 Logon     Login failed for user '<user name>'.

As defined above the Severity & State columns on the error are key to find the accurate reflection for the source of the problem. On the above error number 8 for state indicates authentication failure due to password mismatch. Books online refers: By default, user-defined messages of severity lower than 19 are not sent to the Microsoft Windows application log when they occur. User-defined messages of severity lower than 19 therefore do not trigger SQL Server Agent alerts.

Sung Lee, Program Manager in SQL Server Protocols (Dev.team) has outlined further information on Error state description:The common error states and their descriptions are provided in the following table:

ERROR STATE       ERROR DESCRIPTION
------------------------------------------------------------------------------
2 and 5           Invalid userid
6                 Attempt to use a Windows login name with SQL Authentication
7                 Login disabled and password mismatch
8                 Password mismatch
9                 Invalid password
11 and 12         Valid login but server access failure
13                SQL Server service paused
18                Change password required


Well I'm not finished yet, what would you do in case of error:

2007-05-17 00:12:00.34 Logon     Login failed for user '<user name>'.

You can see there is no severity or state level defined from that SQL Server instance’s error log. So the next troubleshooting option is to look at the Event Viewer’s security log [edit because screen shot is missing but you get the

idea, look in the event log for interesting events].

  • #1

Есть два SQL сервера с одинаковой базой — один дома, на котором делаю отладку, второй в сети на домене.
Создаю подключение и запрос к серверу MS SQL на локальном компе — все работает.
При подключении к сетевому двойнику выдает ошибку:
Warning: odbc_connect() [function.odbc-connect]: SQL error: [Microsoft][ODBC SQL Server Driver][SQL Server]Ошибка входа пользователя «COMP\Гость»., SQL state 28000 in SQLConnect inG:\home\localhost\www\644030.ru\info.php on line 8
Так подключаюсь по сети:

Код:

<?PHP
$server = "644030.ru";
$sql="select * from dano";
$UserName = 'sa';
$password = '555';
$database = 'tasty';

$con = odbc_connect("Driver={SQL Server}; Server=$server;Database=$database;",$username, $password);

$res = odbc_exec($con, $sql);
?>

Переношу тот же файл php на тот комп, который висит в сети, меняю строку с адресом $server = «644030.ru»; на имя SQL сервера $server = «comp» — и всё работает!

Пробовал записывать $server = «644030.ru/comp» и $server = «644030.ru\comp» — не помогает и ошибка уже другая
SQL-сервер не существует, или отсутствует доступ — что означает, что строка с именем сервера $server = «644030.ru»; правильная.

Ума не приложу, причем здесь Гость, если я под «sa» захожу? Может пароль в кодировке должен передаваться? Тогда не понятно, почему на локальной машине работает…

Вобщем, помогите, други, свои версии кончились.

Последнее редактирование:

  • #2

На компьютере включена гостевая политика авторизации удалённых пользователей…
Выключи, всё заработает.
gpedit.msc: Компьютер/Windows/Параметры безопасности/локальные политики/параметры безопасности

Сетевой доступ: модель совместного доступа и безопасности для локальных учетных записей
Поставить «Обычная»

  • #3

На компьютере включена гостевая политика авторизации удалённых пользователей…
Выключи, всё заработает.

Да, спасибо, проблема в этом. Но сервер работает на системе Windows7 домашняя и там запрещено устанавливать редактор групповой безопасности.
Gpedit.msc открывается с ошибкой: невозможно создать оснастку.
Можно ли как-то обойти эту проблему? Гуглю второй день, что-то не получается.

  • #4

Решено. Попробовал подключиться к удаленному серверу не через odbc, а через функции sqlsrv_connect и все заработало. Почему-то раньше не хотело через неё работать, и вот пожалуйста — получилось. AnrDaemon, спасибо за участие!

I’ve written a very simple JDBC login test program. And after all kinds of problems I’ve almost got it working. Almost, just can’t seem to get past this problem:

SQLServerException: Login failed for user xxxxx

I created a simple database PersonInfo then I created user user1 password1 (SQL authentication). And after trying everything was unable to connect to the database.

I am using SqlServer2008 on Win 7, I’ve got the latest JDBC driver from Microsoft.

My code is:

import java.sql.*;

public class hell {
public static void main(String[] args) {
    
    try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
Connection conn=  DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=PersonInfo;user=Sohaib;password=0000;");


System.out.println("connected");
       }

    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

Here’s the Exception

Exception: Unable to get connect
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'Sohaib'.
and all other supporting errors.

tshepang's user avatar

tshepang

12.1k21 gold badges91 silver badges136 bronze badges

asked Jun 28, 2013 at 19:51

The Code Geek's user avatar

2

Is your SQL Server in ‘mixed mode authentication’ ? This is necessary to login with a SQL server account instead of a Windows login.

You can verify this by checking the properties of the server and then SECURITY, it should be in ‘SQL Server and Windows Authentication Mode’

This problem occurs if the user tries to log in with credentials that cannot be validated. This problem can occur in the following scenarios:

Scenario 1: The login may be a SQL Server login but the server only accepts Windows Authentication.

Scenario 2: You are trying to connect by using SQL Server Authentication but the login used does not exist on SQL Server.

Scenario 3: The login may use Windows Authentication but the login is an unrecognized Windows principal. An unrecognized Windows principal means that Windows can’t verify the login. This might be because the Windows login is from an untrusted domain.

It’s also possible the user put in incorrect information.

http://support.microsoft.com/kb/555332

answered Jun 29, 2013 at 8:28

Bryan's user avatar

BryanBryan

3,2912 gold badges15 silver badges30 bronze badges

2

In my case, I had to activate the option «SQL Server and Windows Authentication mode», follow all steps below:

1 — Right-click on your server
enter image description here

2 — Go to option Security

3 — Check the option «SQL Server and Windows Authentication mode»

4 — Click on the Ok button
enter image description here

5 — Restart your SQL Express Service («Windows Key» on the keyboard and write «Services», and then Enter key)
enter image description here

After that, I could log in with user and password

Federico Navarrete's user avatar

answered Oct 10, 2019 at 18:40

Junior Grão's user avatar

Junior GrãoJunior Grão

1,3611 gold badge8 silver badges7 bronze badges

4

I ran into the same issue, and I fixed it by adding my windows username to SQL and then to my server, here is how I did:

First, create a new login with your Windows username:
enter image description here

Click Search, then type your name in the box and click check names.
enter image description here

Then add your that user to the server:

Right click on the Server > Permissions > Search > Browse > Select your user
(You will notice that now the user you created is available in the list)

enter image description here

I hope it helps ;-)

Federico Navarrete's user avatar

answered Apr 30, 2018 at 19:12

Roberto Rodriguez's user avatar

We got this error when reusing the ConnectionString from EntityFramework connection. We have Username and Password in the connection string but didn’t specify

«Persist Security Info=True».

Thus, the credentials were removed from the connection string after establishing the connection (so we reused an incomplete connection string). Of course, we always have to think twice when using this setting, but in this particular case, it was ok.

rene's user avatar

rene

41.5k78 gold badges114 silver badges152 bronze badges

answered Aug 19, 2019 at 15:13

Alexander's user avatar

AlexanderAlexander

6044 silver badges13 bronze badges

3

I got the same error message when trying to connect to my SQL DB in Azure (using sql-cli). The simple solution was to escape the password with single quotes like this:

mssql -s server.database.windows.net -u user@server -p 'your_password' -d your_db -e

answered Apr 19, 2017 at 15:19

Tobias's user avatar

TobiasTobias

8207 silver badges11 bronze badges

Also make sure that account is not locked out in user properties «Status» tab

answered Aug 16, 2017 at 7:55

irfandar's user avatar

irfandarirfandar

1,7001 gold badge23 silver badges24 bronze badges

I have also caught the same issue,But don’t worry the solution is so simple

We need to understand the basic terms first that this error “Login Failed for User (Microsoft SQL Server, Error: 18456)” means you entered invalid credentials when logging into SQL Server with specific server authentication type.
enter image description here

Where I have Selected the option of Windows Authentication mode in Server Authentication

and In my ConnectionString in appsettings.json file has the following connection string:

Server=DESKTOP-PK4BJF5;Database=lms;Trusted_Connection=false;MultipleActiveResultSets=true;TrustServerCertificate=true

In which the «trusted-connection» is a parameter used in database connection strings to specify the type of authentication to be used when connecting to a database server.

When «trusted-connection» is set to «true» or «SSPI» (Security Support Provider Interface), it means that the connection will use Windows Authentication to authenticate the user. This means that the credentials of the currently logged-in Windows user will be used to connect to the database server. This type of authentication is also sometimes referred to as «integrated security».

When «trusted-connection» is set to «false», it means that the connection will use SQL Server Authentication to authenticate the user. This means that the connection string will contain a user ID and password that are used to connect to the database server.

I am Updating the Connection String line and just write SSPI instead of /false

"Server=DESKTOP-PK4BJF5;Database=lms;Trusted_Connection=SSPI;MultipleActiveResultSets=true;TrustServerCertificate=true",

answered Apr 12 at 4:46

AYESHA JAVED's user avatar

For Can not connect to the SQL Server. The original error is: Login failed for user 'username'. error, port requirements on MSSQL server side need to be fulfilled.

There are other ports beyond default port 1433 needed to be configured on Windows Firewall.

https://stackoverflow.com/a/25147251/1608670

answered Oct 24, 2017 at 19:32

Ivan Chau's user avatar

Ivan ChauIvan Chau

1,4031 gold badge18 silver badges28 bronze badges

We solved our Linux/php hook to SQL Server problem by creating a new login account with SQL Server authentication instead of Windows authentication.

answered Jun 5, 2018 at 18:46

Charles Kuehn's user avatar

Just in case any one else is using creating test users with their automation….

We had this same error and it was because we had recreated the user (as part of the test process). This caused the underlying SID to change which meant that SQL couldn’t properly authenticate the user.

We fixed it by adding a drop login command to our testing scripts to ensure that a previously created user (with the same user name) was no longer present on the instance.

answered Aug 4, 2020 at 6:23

xenon8's user avatar

I faced with same problem. I’ve used Entity Framework and thought that DB will be created automatically. Please make sure your DB exists and has a correct name.

answered Oct 31, 2020 at 16:38

Сергей's user avatar

СергейСергей

7704 gold badges13 silver badges31 bronze badges

In my case I have configured as below in my springboot application.properties file then I am able to connect to the sqlserver database using service account:

url=jdbc:sqlserver://SERVER_NAME:PORT_NUMBER;databaseName=DATABASE_NAME;sendStringParametersAsUnicode=false;multiSubnetFailover=true;integratedSecurity=true
    jdbcUrl=${url}
    username=YourDomain\\$SERVICE-ACCOUNT-USER-NAME
    password=
    hikari.connection-timeout=60000
    hikari.maximum-pool-size=5
    driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver

answered Jan 11, 2021 at 22:44

Elias's user avatar

EliasElias

6742 gold badges11 silver badges23 bronze badges

try using this connection string

Server=ServerName;Database=DbName;Trusted_Connection=SSPI;MultipleActiveResultSets=true;TrustServerCertificate=true

answered Jan 3 at 16:04

Saeed RayatMoghadam's user avatar

You can try this method: add Trusted_Connection=True; to your connection string.

Brian Tompsett - 汤莱恩's user avatar

answered Apr 29 at 10:36

Huseyn Hemidov's user avatar

If you are using Windows Authentication, make sure to log-in to Windows at least once with that user.

answered Feb 18, 2019 at 7:33

Farkhod's user avatar

FarkhodFarkhod

1964 silver badges8 bronze badges

Previously I was using the Windows Authentication without problems, then occurred me the error below.

«Failed to generate SSPI context.»

Witch I resolve by changing my connection string from

Server=127.0.0.1;Database=[DB_NAME];Trusted_Connection=True;

to

Server=127.0.0.1;Database=[DB_NAME];Trusted_Connection=False;

Then the next error occurred me

«Login failed for user ».»

To solve this problem I used the sa user. Access the sa user to update de password if you need (on the SQL server Security > Logins > sa (right click) > Properties > General)) and then update the connection string to..

Server=127.0.0.1;Database=[DB_NAME];User Id=sa;Password=[YOUR_PASSWORD]

You can use another user of your choice.

answered Mar 30, 2021 at 9:26

Jéssica Machado's user avatar

1

Понравилась статья? Поделить с друзьями:
  • Sql ошибка 9694
  • Sql ошибка 42601
  • Sql ошибка 7416
  • Sql ошибка 5173
  • Sql ошибка 5058