Обновлено 07.12.2016
Всем привет, сегодня расскажу как изменить или сбросить пароль sa sql сервера. Напомню sa это логин пользователя в MS SQL, имеющий по умолчанию самые высокие привилегии, сама учетка локальная, зачастую даже выключенная, но тем не менее часто используемая. Может получиться такая ситуация, что вы забыли от нее пароль и тем самым потеряли доступ к базам данных, сегодня вы научитесь это обходить и восстанавливать доступ до ваших БД.
И так у вас есть MS SQL, как установить sql я уже рассказывал, кто не знает посмотрите. У вас задача сменить пароль для пользователя sa sql.
Пароль sa по умолчанию
Напомню пароль sa по умолчанию как ни странно sa
Единственное требование, вы везде должны быть локальным администратором
Сменить пароль sa в sql через графический интерфейс
Начнемс, откройте пуск и идите по пути Все программы > Microsoft SQL Server 2012 R2 > Среда SQL Server Management Studio
Либо вы можете открыть командную строку и ввести там ssms.
Не важно какой способ вы выбрали эффект будет один и тот же у вас откроется SQL Server Management Studio. Но второй способ явно быстрее.
По умолчанию стоит проверка подлинности Windows, что означает, что вы сможете войти только с локальной учетной записью Windows или доменной, главное чтобы были права.
Как видите, учетная запись sa по умолчанию отключена, но это не помешает вам сменить ей пароль.
ms sql позволяет сбросить пароль sa через ее свойства, для этого щелкаете правым кликом и выбираете свойства из контекстного меню.
На вкладке общие вы увидите, поле для ввода нового пароля, единственное учтите, что если стоит галка Требовать использование политики паролей, вам придется придумать стойкий пароль отвечающий требованиям безопасности, а именно
- Должна быть большая буква в пароле
- Должна быть маленькая буква в пароле
- Должен быть спецсимвол или цифра в пароле
Если галку снять, то можно задать что угодно, я задал например от 1 до 6. Как видите сменить пароль sa в sql, проще паренной репы.
Единственное, если вы хотите использовать учетную запись sa, то ее нужно включить, для этого перейдите в пункт состояние и укажите Имя входя Включено.
Еще нюанс, вы же помните, что у вас стоит проверка подлинности Windows, а это значит, что нам это не подходит для sa. Щелкнем правым кликом по названию сервера, вверху иерархии и выберем свойства.
На вкладке безопасность, выберем вариант Проверка подлинности SQL Server и Windows. Теперь вы можете заходить с помощью пользователя sa в sql.
Если при попытке войти Management Studio выдает ошибку 233, что подключение к серверу успешно установлено, но затем произошла ошибка при входе, то сделайте следующее.
Откройте Пуск > Панель управления > Администрирование > Службы и перезапустите службу SQL Server.
Как видите, теперь я успешно залогинился.
Сменить пароль sa в sql через командную строку
Чтобы в sql сбросить пароль sa через командную строку воспользуйтесь вот такими командами.
Данной командой вы увидите все доступные сервера MS SQL их SPN
Далее вводите команду
osql -S имя сервера-E
далее пишите
sp_password NULL, <вставьте_новый_пароль_тут>, ’sa’
GO
Если вылезет сообщение Password validation failed. The password does not meet Windows policy requirements because it is too short. То задайте более строгий пароль.
Все после этого вы сбросите пароль sa в sql.
Еще вариант использования osql это вот так
cd C:Program FilesMicrosoft SQL Server110ToolsBinn
затем мы пытаемся подключиться под доверенной учетной записей ОС
osql.exe» -S (local)имя вашего сервера -E
И последний рубеж
ALTER LOGIN SA WITH PASSWORD=‘new_password’
она заменит пароль на new_password
С помощью программы Asunsoft SQL Password Geeker
Есть утилита Asunsoft SQL Password Geeker, к сожалению платная, но способная выполнить поставленную задачу. Запускаем ее жмем Browse далее идем по пути C:Program FilesMicrosoft SQL ServerMSSQL11.MSSQLSERVERMSSQLDATA и открываем master.mdf
теперь, чтобы сбросить пароль sa в sql, выберите его и нажмите Reset.
Сменить пароль sa в монопольном режиме
Есть еще четвертый способ поменять пароль от sa, и заключается он в запуске MS SQL в однопользовательском режиме (single-user mode). Что нам потребуется.
Первое это останавливаем MS SQL Server, можно через службы, а можно и из командной строки
Далее открываете реестр Windows и переходите в ветку
HKEY_LOCAL_MACHINESYSTEMControlSet001Services MSSQLSERVER
Теперь вам нужно задать параметр в строке ImagePath -m как раз и будет говорить об однопользовательском режиме. У меня получилось вот так
«C:Program FilesMicrosoft SQL ServerMSSQL11.MSSQLSERVERMSSQLBinnsqlservr.exe» -m -s MSSQLSERVER
Теперь запускаете MS SQL командой
Теперь SQL запущен в однопользовательском режиме и позволяет любому члену локальной группы администраторов компьютера подсоединяться к экземпляру SQL Server с правами sysadmin, но нужно SQL об этом сказать. Посмотреть режим работы можно в свойствах службы.
В командной строке пишем
cd C:Program FilesMicrosoft SQL Server110ToolsBinn
sqlcmd.exe: EXEC sp_addsrvrolemember 'имя сервераимя пользователя', 'sysadmin'
GO
Перезапускаем службу и радуемся жизни, не забудьте потом убрать параметр -m в реестре. Вот так вот просто сбросить пароль sa в sql, как встроенными методами так и сторонними.
- Remove From My Forums
-
Question
-
hello.
iam using SqlServer 2008r2 and my pc is in the network (in an office)
how can change my login password which is created in SQl server authentication?
Answers
-
Hi Ehsan
- 1. Login into SQL server using Windows Authentication.
- 2. In Object Explorer, open Security folder, open Logins folder. Right Click on sa account and go to Properties.
- 3. Type a new SQL LOGIN password, and confirm it. Click OK to finish.
From A query Window you can try this
- Step 1. Open SQL Server Management Studio
- Step 2. Open a new query
-
Step 3. Type the follow commands and excute:
GO
ALTER LOGIN [LOGIN_NAME] WITH DEFAULT_DATABASE=[master]
GO
USE [master]
GO
ALTER LOGIN [LOGIN_NAME] WITH PASSWORD=N’NewPassword’ MUST_CHANGE
GO
Hope this helps you
-
Marked as answer by
Saturday, June 16, 2012 6:01 PM
-
Hi,
This should work
ALTER LOGIN yoursqllogin WITH PASSWORD = 'newpassword' OLD_PASSWORD = 'oldpassword'
-
Marked as answer by
great ehsan
Saturday, June 16, 2012 6:01 PM
-
Marked as answer by
-
Hi,
- 1. Login into SQL server using Windows Authentication.
2. In Object Explorer, open Security folder, open Logins folder. Right Click on sa account and go to Properties.
3. Type a new SQL sa password, and confirm it. Click OK to finish.
After restarting SQL Server and all its services, you can log into SQL Server by sa login with new SQL sa password.
To chainge through Query Analyser
- Change SQL Server Password with the Query Windows in Management Studio
Step 1. Open SQL Server Management Studio
Step 2. Open a new query
Step 3. Type the follow commands and excute:
GO
ALTER LOGIN [sa] WITH DEFAULT_DATABASE=[master]
GO
USE [master]
GO
ALTER LOGIN [sa] WITH PASSWORD=N’NewPassword’ MUST_CHANGE
GO
Then the new password is set for your SQL Server sa account.
Please click the Mark as Answer or Vote As Helpful button if a post solves your problem or is helpful!
-
Marked as answer by
great ehsan
Saturday, June 16, 2012 6:02 PM
- 1. Login into SQL server using Windows Authentication.
Download Article
Reset your SA password in SQL with this easy-to-follow guide
Download Article
This wikiHow teaches you how to reset a forgotten System Administrator (SA) password in Microsoft’s SQL Server. You can do this by logging in with Windows Authentication, using Command Prompt, or using Single-User Mode.
-
1
Understand how this method works. If Windows Authentication is enabled for your server, you can use it to log into your server without having to enter a password. After you’re logged in, you can easily change the SQL server’s password.[1]
- If Windows Authentication isn’t enabled, you’ll need to either use Single-User Mode or use Command Prompt to reset your password.
-
2
Make sure that SSMS is installed. SSMS is a user interface which allows you to change different aspects of your SQL Server settings in a window rather than in Command Prompt. If you don’t have SSMS installed, do the following:
- Go to the SSMS installation page in a browser.
- Click the Download SQL Server Management Studio 17.6 link.
- Double-click the downloaded SSMS setup file.
- Follow the on-screen prompts to install SSMS.
Advertisement
-
3
Open SSMS. Type sql server management studio into Start, then click Microsoft SQL Server Management Studio 17 at the top of the Start window.
-
4
Select the correct authentication. Click the «Authentication» drop-down box, then click Windows Authentication in the menu.
-
5
Click Connect. It’s at the bottom of the window. If Windows Authentication is allowed for your account, doing so will log you into your server’s dashboard.
-
6
Expand your server’s folder. If your server’s folder in the upper-left side of the window doesn’t have several options below it, click the + icon to the left of it to expand it.
-
7
Expand the «Security» folder. It’s below the server’s name.
-
8
Expand the «Logins» folder. You’ll find this in the group of options below the «Security» folder.
-
9
Double-click sa. It’s in the «Logins» group of options. Doing so opens your System Administrator properties window.
-
10
Enter a new password. Type your new password into both the «Password» and the «Confirm password» text fields near the top of the window.
-
11
Click OK. It’s at the bottom of the window. Doing so will change your password and close the properties window.
Advertisement
-
1
Understand how this method works. Even if you’ve locked out your only account, you can add a user and give them administrator permissions by using the Command Prompt. After doing this, you can use the new user’s credentials to log into your SQL Server page, from which point you can change the SA password.[2]
-
2
Make sure that SSMS is installed. SSMS is a user interface which allows you to change different aspects of your SQL Server settings in a window rather than in Command Prompt. If you don’t have SSMS installed, do the following:
- Go to the SSMS installation page in a browser.
- Click the Download SQL Server Management Studio 17.6 link.
- Double-click the downloaded SSMS setup file.
- Follow the on-screen prompts to install SSMS.
-
3
Open Command Prompt in administrator mode. Open Start
, then do the following:
- Type in command prompt
- Right-click
Command Prompt
- Click Run as administrator
- Click Yes when prompted.
-
4
Stop SQL Instance from running. Type in net stop MSSQLSERVER and press ↵ Enter. This will stop the currently running SQL services.
-
5
Restart SQL in Single-User Mode. Type in net start MSSQLSERVER -m"SQLCMD" and press ↵ Enter.
- You won’t see any indication that you’re running in Single-User Mode at this point, but you should see the phrase «The SQL Server <MSSQLSERVER> service was started successfully» appear.
-
6
Connect to SQL. Type in sqlcmd and press ↵ Enter. Doing so opens the SQL command line.
-
7
Create a new user and password. You’ll do this with typed commands in the SQL command line:
- Type in CREATE LOGIN name WITH PASSWORD=’password’ where «name» is the account name and «password» is the new password.
- Press ↵ Enter.
- Type in GO and press ↵ Enter.
-
8
Add the user to the System Administrator role. Type in SP_ADDSRVROLEMEMBER name,’SYSADMIN’ where «name» is the account name, press ↵ Enter, and then type in GO and press ↵ Enter.
-
9
Exit the SQLCMD command line. Type in exit and press ↵ Enter.
-
10
Restart SQL in regular mode. You can cancel Single-User Mode by typing in net stop MSSQLSERVER && net start MSSQLSERVER and pressing ↵ Enter.
- You should see the «The SQL Server <MSSQLSERVER> service was started successfully» phrase appear again; at this point, you can close Command Prompt.
-
11
Open SSMS. Type sql server management studio into Start, then click Microsoft SQL Server Management Studio 17 at the top of the Start window.
-
12
Select the correct authentication. Click the «Authentication» drop-down box, then click SQL Server Authentication in the menu.
-
13
Log in with the new user’s credentials. Click the «Login» drop-down box, then click the name of the user you just created.
-
14
Enter the password. Type the user’s password into the «Password» text box near the bottom of the window.
-
15
Click Connect. It’s at the bottom of the window. As long as you adequately entered your username and password, this will open your server’s dashboard.
-
16
Expand your server’s folder. If your server’s folder in the upper-left side of the window doesn’t have several options below it, click the + icon to the left of it to expand it.
-
17
Expand the «Security» folder. It’s below the server’s name.
-
18
Expand the «Logins» folder. You’ll find this in the group of options below the «Security» folder.
-
19
Double-click sa. It’s in the «Logins» group of options. Doing so opens your System Administrator properties window.
-
20
Enter a new password. Type your new password into both the «Password» and the «Confirm password» text fields near the top of the window.
-
21
Click OK. It’s at the bottom of the window. Doing so will change your password and close the properties window.
Advertisement
-
1
Open Start
. Click the Windows logo in the bottom-left corner of the screen. This will open the Start menu.
-
2
Search for Command Prompt. Type in command prompt, then wait for Command Prompt to appear at the top of the Start menu.
-
3
Right-click
Command Prompt. Doing so will prompt a drop-down menu.
-
4
Click Run as administrator. It’s in the drop-down menu.
-
5
Click Yes when prompted. This will confirm your decision to open Command Prompt in administrator mode. The Command Prompt window should open.
-
6
Enter the first command. Type in osql -L and press ↵ Enter.[3]
-
7
Enter the second command with your server’s name. Type in OSQL -S server -E where «server» is replaced by your server’s name, then press ↵ Enter.
-
8
Create a new password. Type in EXEC sp_password NULL, ‘password’, ’sa' where «password» is replaced by the password that you want to use, then press ↵ Enter.
- For example, to set your password as «rutabaga123», you would type EXEC sp_password NULL, 'rutabaga123', 'sa' into Command Prompt.
-
9
Execute the command. Type in GO, then press ↵ Enter. Type exit, then press ↵ Enter to exit OSQL.
-
10
Attempt to log into SQL Server. Do so by using your administrator credentials and your new password. If you’re able to log into SQL Server, your password was successfully changed.
Advertisement
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
-
Should none of these methods work for your situation, there are several paid SQL Server password recovery programs available online.
Thanks for submitting a tip for review!
Advertisement
-
You cannot reset your SA password remotely.
Advertisement
About This Article
Article SummaryX
1. Open SSMS.
2. Connect to the server.
3. Expand the server’s folder.
4. Expand the Security folder.
5. Expand the Logins folder.
6. Double-click sa.
7. Enter and confirm a new password.
8. Click OK.
Did this summary help you?
Thanks to all authors for creating a page that has been read 1,065,107 times.
Is this article up to date?
Download Article
Reset your SA password in SQL with this easy-to-follow guide
Download Article
This wikiHow teaches you how to reset a forgotten System Administrator (SA) password in Microsoft’s SQL Server. You can do this by logging in with Windows Authentication, using Command Prompt, or using Single-User Mode.
-
1
Understand how this method works. If Windows Authentication is enabled for your server, you can use it to log into your server without having to enter a password. After you’re logged in, you can easily change the SQL server’s password.[1]
- If Windows Authentication isn’t enabled, you’ll need to either use Single-User Mode or use Command Prompt to reset your password.
-
2
Make sure that SSMS is installed. SSMS is a user interface which allows you to change different aspects of your SQL Server settings in a window rather than in Command Prompt. If you don’t have SSMS installed, do the following:
- Go to the SSMS installation page in a browser.
- Click the Download SQL Server Management Studio 17.6 link.
- Double-click the downloaded SSMS setup file.
- Follow the on-screen prompts to install SSMS.
Advertisement
-
3
Open SSMS. Type sql server management studio into Start, then click Microsoft SQL Server Management Studio 17 at the top of the Start window.
-
4
Select the correct authentication. Click the «Authentication» drop-down box, then click Windows Authentication in the menu.
-
5
Click Connect. It’s at the bottom of the window. If Windows Authentication is allowed for your account, doing so will log you into your server’s dashboard.
-
6
Expand your server’s folder. If your server’s folder in the upper-left side of the window doesn’t have several options below it, click the + icon to the left of it to expand it.
-
7
Expand the «Security» folder. It’s below the server’s name.
-
8
Expand the «Logins» folder. You’ll find this in the group of options below the «Security» folder.
-
9
Double-click sa. It’s in the «Logins» group of options. Doing so opens your System Administrator properties window.
-
10
Enter a new password. Type your new password into both the «Password» and the «Confirm password» text fields near the top of the window.
-
11
Click OK. It’s at the bottom of the window. Doing so will change your password and close the properties window.
Advertisement
-
1
Understand how this method works. Even if you’ve locked out your only account, you can add a user and give them administrator permissions by using the Command Prompt. After doing this, you can use the new user’s credentials to log into your SQL Server page, from which point you can change the SA password.[2]
-
2
Make sure that SSMS is installed. SSMS is a user interface which allows you to change different aspects of your SQL Server settings in a window rather than in Command Prompt. If you don’t have SSMS installed, do the following:
- Go to the SSMS installation page in a browser.
- Click the Download SQL Server Management Studio 17.6 link.
- Double-click the downloaded SSMS setup file.
- Follow the on-screen prompts to install SSMS.
-
3
Open Command Prompt in administrator mode. Open Start
, then do the following:
- Type in command prompt
- Right-click
Command Prompt
- Click Run as administrator
- Click Yes when prompted.
-
4
Stop SQL Instance from running. Type in net stop MSSQLSERVER and press ↵ Enter. This will stop the currently running SQL services.
-
5
Restart SQL in Single-User Mode. Type in net start MSSQLSERVER -m"SQLCMD" and press ↵ Enter.
- You won’t see any indication that you’re running in Single-User Mode at this point, but you should see the phrase «The SQL Server <MSSQLSERVER> service was started successfully» appear.
-
6
Connect to SQL. Type in sqlcmd and press ↵ Enter. Doing so opens the SQL command line.
-
7
Create a new user and password. You’ll do this with typed commands in the SQL command line:
- Type in CREATE LOGIN name WITH PASSWORD=’password’ where «name» is the account name and «password» is the new password.
- Press ↵ Enter.
- Type in GO and press ↵ Enter.
-
8
Add the user to the System Administrator role. Type in SP_ADDSRVROLEMEMBER name,’SYSADMIN’ where «name» is the account name, press ↵ Enter, and then type in GO and press ↵ Enter.
-
9
Exit the SQLCMD command line. Type in exit and press ↵ Enter.
-
10
Restart SQL in regular mode. You can cancel Single-User Mode by typing in net stop MSSQLSERVER && net start MSSQLSERVER and pressing ↵ Enter.
- You should see the «The SQL Server <MSSQLSERVER> service was started successfully» phrase appear again; at this point, you can close Command Prompt.
-
11
Open SSMS. Type sql server management studio into Start, then click Microsoft SQL Server Management Studio 17 at the top of the Start window.
-
12
Select the correct authentication. Click the «Authentication» drop-down box, then click SQL Server Authentication in the menu.
-
13
Log in with the new user’s credentials. Click the «Login» drop-down box, then click the name of the user you just created.
-
14
Enter the password. Type the user’s password into the «Password» text box near the bottom of the window.
-
15
Click Connect. It’s at the bottom of the window. As long as you adequately entered your username and password, this will open your server’s dashboard.
-
16
Expand your server’s folder. If your server’s folder in the upper-left side of the window doesn’t have several options below it, click the + icon to the left of it to expand it.
-
17
Expand the «Security» folder. It’s below the server’s name.
-
18
Expand the «Logins» folder. You’ll find this in the group of options below the «Security» folder.
-
19
Double-click sa. It’s in the «Logins» group of options. Doing so opens your System Administrator properties window.
-
20
Enter a new password. Type your new password into both the «Password» and the «Confirm password» text fields near the top of the window.
-
21
Click OK. It’s at the bottom of the window. Doing so will change your password and close the properties window.
Advertisement
-
1
Open Start
. Click the Windows logo in the bottom-left corner of the screen. This will open the Start menu.
-
2
Search for Command Prompt. Type in command prompt, then wait for Command Prompt to appear at the top of the Start menu.
-
3
Right-click
Command Prompt. Doing so will prompt a drop-down menu.
-
4
Click Run as administrator. It’s in the drop-down menu.
-
5
Click Yes when prompted. This will confirm your decision to open Command Prompt in administrator mode. The Command Prompt window should open.
-
6
Enter the first command. Type in osql -L and press ↵ Enter.[3]
-
7
Enter the second command with your server’s name. Type in OSQL -S server -E where «server» is replaced by your server’s name, then press ↵ Enter.
-
8
Create a new password. Type in EXEC sp_password NULL, ‘password’, ’sa' where «password» is replaced by the password that you want to use, then press ↵ Enter.
- For example, to set your password as «rutabaga123», you would type EXEC sp_password NULL, 'rutabaga123', 'sa' into Command Prompt.
-
9
Execute the command. Type in GO, then press ↵ Enter. Type exit, then press ↵ Enter to exit OSQL.
-
10
Attempt to log into SQL Server. Do so by using your administrator credentials and your new password. If you’re able to log into SQL Server, your password was successfully changed.
Advertisement
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
-
Should none of these methods work for your situation, there are several paid SQL Server password recovery programs available online.
Thanks for submitting a tip for review!
Advertisement
-
You cannot reset your SA password remotely.
Advertisement
About This Article
Article SummaryX
1. Open SSMS.
2. Connect to the server.
3. Expand the server’s folder.
4. Expand the Security folder.
5. Expand the Logins folder.
6. Double-click sa.
7. Enter and confirm a new password.
8. Click OK.
Did this summary help you?
Thanks to all authors for creating a page that has been read 1,065,107 times.
Is this article up to date?
В этой статье мы рассмотрим, как сбросить пароль SA (system administrator) в базе данных Microsoft SQL Server 2019/2017/2014/2011. Данная инструкция поможет вам восстановить доступ к базе данных MSSQL, если вы не можете аутентифицироваться с помощью учетной записи sa (пароль sa был забыт/утерян/учетка отключена) или под пользователем Windows (в настройках доступа отсутствуют пользователи с правами администратора MS SQL).
Локальная учетная запись sa имеет максимальные привилегии в MS SQL. В большинстве случаев она отключена, но вы можете включить ее, задать нужный пароль и восстановить доступ к SQL Server.
Для восстановления доступа к базе данных без полной переустановки экземпляра MS SQL (и с потерей базы master), нужно запустить SQL Server в однопользовательском режиме (single-user mode). В этом однопользовательском режиме вы сможете авторизоваться на SQL Server под любой учетной записью с правами локального администратора на компьютере, на котором установлен MS SQL Server. После этого можно сбросить пароль учетной записи sa и/или предоставить административные права нужной ученой записи Windows.
Совет. Напомним, что, начиная с MS SQL Server 2008, роль sysadmin на SQL сервере по-умолчанию не назначается локальной группе администраторов Windows.
Чтобы запустить MS SQL Server в single-user mode, подключитесь к хосту MSSQL под любой учетной записью с правами локального администратора Windows.
- Остановите инстанс SQL Server (в нашем примере имя инстанса MSSQL — MSSQLSERVER) из командной строки
net stop MSSQLSERVER
или с помощью PowerShell:
Get-Service MSSQLSERVER| stop-service
- Откройте редактор реестра (
regedit.exe
) и перейдите в раздел параметров запуска сервиса SQL: HKEY_LOCAL_MACHINESYSTEMControlSet001ServicesMSSQLSERVER; - Измените значение параметра ImagePath, добавив в качестве аргумента sqlservr.exe ключ -m. В нашем примере получилось такое значение:
"C:Program FilesMicrosoft SQL ServerMSSQL15.MSSQLSERVERMSSQLBinnsqlservr.exe" -sMSSQLSERVER -m
- Запустите службу SQL Server:
net start MSSQLSERVER
- Теперь ваш SQL Server запущен в однопользовательском режиме и позволяет любому члену локальной группы администраторов (или встроенному администратору Windows) подключаться к экземпляру SQL Server с правами sysadmin.
- Запустите SQL Server Management Studio (SSMS) и подключитесь к Database Engine под учетной записью администратора компьютера;
- Перейдите в раздел Security -> Logins и найдите пользователя sa. По умолчанию пользователь sa отключен;
- Откройте его свойства и на вкладке General задайте новый пароль SA. Затем на вкладке Status включите данного пользователя (Login -> Enabled);
- Чтобы разрешить подключаться к MSSQL с помощью локальных учетных записей SQL (в том числе sa), нужно в свойствах сервера на вкладке Security включить режим аутентификации SQL Server and Windows Authentication mode. Иначе при подключении под локальной учетной записью sa будет появляться ошибка:
Login failed for user 'sa'. (Microsoft SQL Server, Error: 18456)
- Также в разделе Logins можно добавить нужных пользователей Windows (локальных или доменных) и предоставить им права Server roles -> Sysadmin. Можно предоставить пользователю роль из командной строки sqlcmd:
EXEC sp_addsrvrolemember 'DOMAINUsername', 'sysadmin';)
GO
- Осталось еще раз остановить службу MSSQL, вернуть начальное значение параметра реестра ImagePart, убрав “-m” (
C:Program FilesMicrosoft SQL ServerMSSQL15.MSSQLSERVERMSSQLBinnsqlservr.exe" -sMSSQLSERVER
); - Запустите службу SQL Server в обычном режиме;
- Теперь вы можете подключиться к SQL серверу под учетной записью sa в режиме SQL Server Authentication или под учетной записью Windows, которой вы предоставили права sysadmin в SQL Server.
Совет. Также вы можете запустить SQL Server в однопользовательском режиме с помощью SQL Server Configuration Manager. Для этого нужно в свойствах нужного инстанса перейти на вкладку Startup Parameters и добавить опцию запуска –m.
Также вы можете использовать командную строку sqlcmd для сброса пароля SA и предоставления доступа к SQL Server.
- Запустите SQL Server в однопользовательском режиме как описано выше;
- Откройте командную строку и подключитесь к серверу SQL:
sqlcmd –S localhost
- Чтобы изменить пароль пользователя SA и включить его, выполните следующие команды T-SQL:
ALTER LOGIN sa enable
GO
ALTER LOGIN sa WITH PASSWORD = 'newsa_pa$$w0rdd1'
GO - Чтобы предоставить права sysadmin в MSSQL для учетной записи Windows (локальной в этом примере), используйте команды:
CREATE LOGIN [sql-srv01user1] FROM WINDOWS
GO
ALTER SERVER ROLE sysadmin ADD MEMBER [sql-srv01user1]
GO
В этой статье мы показали, как восстановить доступ к SQL Server в single user mode. В этом режиме вы можете сбросить пароль sa (и других пользователей SQL), или предоставить права администратора SQL учетным записям Windows. Однопользовательский режим также можно использовать для восстановления базы temdb в MSSql Server.
Comments
-
19 Jul 2012 10:41 AM
Nice Tool Woniety….
I like to add one more method os changing password in «forgotten SQL Server password «.
Its a article given over : technet.microsoft.com/…/dd207004(v=sql.105).aspx
This topic describes how you can regain access to the SQL Server Database Engine as a system administrator. A system administrator can lose access to an instance of SQL Server because of one of the following reasons:
• All logins that are members of the sysadmin fixed server role have been removed by mistake.
• All Windows Groups that are members of the sysadmin fixed server role have been removed by mistake.
• The logins that are members of the sysadmin fixed server role are for individuals who have left the company or who are not available.
• The sa account is disabled or no one knows the password.
One way in which you can regain access is to reinstall SQL Server and attach all the databases to the new instance. This solution is time-consuming; and, to recover the logins, it might require restoring the master database from a backup. If the backup of the master database is older, it might not have all the information. If the backup of the master database is more recent, it might have the same logins as the previous instance; therefore, administrators will still be locked out.
Start the instance of SQL Server in single-user mode by using either the -m or -f options. Any member of the computer’s local Administrators group can then connect to the instance of SQL Server as a member of the sysadmin fixed server role.
When you start an instance of SQL Server in single-user mode, first stop the SQL Server Agent service. Otherwise, SQL Server Agent might connect first and prevent you from connecting as a second user.
When you use the -m option with sqlcmd or SQL Server Management Studio, you can limit the connections to a specified client application. For example, -m»sqlcmd» limits connections to a single connection and that connection must identify itself as the sqlcmd client program. Use this option when you are starting SQL Server in single-user mode and an unknown client application is taking the only available connection. To connect through the Query Editor in Management Studio, use -m»Microsoft SQL Server Management Studio — Query».
-
31 Jul 2013 4:52 AM
Nice article Woniety… can we recover «forgotten» password of windows logins using SQL Password Recovery tool?
-
31 Jul 2013 4:56 AM
Nice article Woniety… can we recover / change password of windows logins using SQL Password Recovery tool?
-
31 Jul 2013 5:00 AM
Nice article Woniety…
can we recover «forgotten» password of windows logins using SQL Password Recovery tool?
-
16 Nov 2013 7:29 AM
Very good. Simple, quick and secure.
«sa» — это логин пользователя в MS SQL, имеющий по умолчанию самые высокие привилегии, сама учетка локальная, зачастую даже выключенная, но тем не менее часто используемая. Если вы потеряли или забыли пароль от этой учетки «sa», то у вас не будет доступа к управлению вашими БД.
Пароль sa по умолчанию
Напомню пароль sa по умолчанию как ни странно sa
Единственное требование, вы везде должны быть локальным администратором
Сменить пароль sa в sql через графический интерфейс
Начнемс, откройте пуск и идите по пути Все программы > Microsoft SQL Server 2012 R2 > Среда SQL Server Management Studio
Либо вы можете открыть командную строку и ввести там ssms.
У вас откроется SQL Server Management Studio.
По умолчанию стоит проверка подлинности Windows, что означает, что вы сможете войти только с локальной учетной записью Windows или доменной, главное чтобы были права.
Учетная запись sa по умолчанию отключена, но это не помешает вам сменить ей пароль.
ms sql позволяет сбросить пароль sa через ее свойства, для этого щелкаете правым кликом и выбираете свойства из контекстного меню.
На вкладке общие вы увидите, поле для ввода нового пароля, единственное учтите, что если стоит галка Требовать использование политики паролей, вам придется придумать стойкий пароль отвечающий требованиям безопасности, а именно
- Должна быть большая буква в пароле
- Должна быть маленькая буква в пароле
- Должен быть спецсимвол или цифра в пароле
Если галку снять, то можно задать новый пароль и сохранить. Пароль на пользователя sa в sql изменен.
Единственное, если вы хотите использовать учетную запись sa, то ее нужно включить, для этого перейдите в пункт состояние и укажите Имя входя Включено.
Еще нюанс, вы же помните, что у вас стоит проверка подлинности Windows, а это значит, что нам это не подходит для sa. Щелкнем правым кликом по названию сервера, вверху иерархии и выберем свойства.
На вкладке безопасность, выберем вариант Проверка подлинности SQL Server и Windows. Теперь вы можете заходить с помощью пользователя sa в sql.
Если при попытке войти Management Studio выдает ошибку 233, что подключение к серверу успешно установлено, но затем произошла ошибка при входе, то сделайте следующее.
Откройте Пуск > Панель управления > Администрирование > Службы и перезапустите службу SQL Server.
Тогда подключение проходит успешно и без ошибок.
Сменить пароль sa в sql через командную строку
Чтобы в sql сбросить пароль sa через командную строку воспользуйтесь командами.
Данной командой вы увидите все доступные сервера MS SQL их SPN
Далее вводите команду
osql -S имя сервера-Eдалее пишите
sp_password NULL, <вставьте_новый_пароль_тут>, ’sa’
GO
Если вылезет сообщение Password validation failed. The password does not meet Windows policy requirements because it is too short. То задайте более строгий пароль.
Все после этого вы сбросите пароль sa в sql.
Еще вариант использования osql это вот так
cd C:Program FilesMicrosoft SQL Server110ToolsBinnзатем мы пытаемся подключиться под доверенной учетной записей ОС
osql.exe» -S (local)имя вашего сервера -E
И последний рубеж
ALTER LOGIN SA WITH PASSWORD=‘new_password’
она заменит пароль на new_password
С помощью программы Asunsoft SQL Password Geeker
Есть утилита Asunsoft SQL Password Geeker, она платная, но способная выполнить поставленную задачу. Запускаем ее жмем Browse далее идем по пути C:Program FilesMicrosoft SQL ServerMSSQL11.MSSQLSERVERMSSQLDATA и открываем master.mdf
теперь, чтобы сбросить пароль sa в sql, выберите его и нажмите Reset.
Сменить пароль sa в монопольном режиме
Есть еще четвертый способ поменять пароль от sa, и заключается он в запуске MS SQL в однопользовательском режиме (single-user mode).
Первое это останавливаем MS SQL Server, можно через службы, а можно и из командной строки
Далее открываете реестр Windows и переходите в ветку
HKEY_LOCAL_MACHINESYSTEMControlSet001Services MSSQLSERVER
Теперь вам нужно задать параметр в строке ImagePath -m как раз и будет говорить об однопользовательском режиме. У меня получилось вот так
«C:Program FilesMicrosoft SQL ServerMSSQL11.MSSQLSERVERMSSQLBinnsqlservr.exe» -m -s MSSQLSERVER
Теперь запускаете MS SQL командой
Теперь SQL запущен в однопользовательском режиме и позволяет любому члену локальной группы администраторов компьютера подсоединяться к экземпляру SQL Server с правами sysadmin, но нужно SQL об этом сказать. Посмотреть режим работы можно в свойствах службы.
В командной строке пишем
cd C:Program FilesMicrosoft SQL Server110ToolsBinnsqlcmd.exe: EXEC sp_addsrvrolemember 'имя сервераимя пользователя', 'sysadmin'
GO
Перезапускаем службу, не забудьте потом убрать параметр -m в реестре. Пароль сброшен на пользователя sa в sql.
Оригинал статьи
В SQL Server пароль связан с входом в SQL Server. Затем логин сопоставляется с пользователем базы данных.
Описание
Чтобы изменить пароль в SQL Server, вам необходимо выполнить оператор ALTER LOGIN.
Синтаксис
Синтаксис изменения пароля в SQL Server (Transact-SQL) с помощью оператора ALTER LOGIN:
ALTER LOGIN login_name
WITH PASSWORD = ‘password’ | hashed_password HASHED
[ OLD_PASSWORD = ‘old_password’ ]
| MUST_CHANGE
| UNLOCK
[ CHECK_EXPIRATION = ON ];
Параметры или аргументы
login_name – логин, пароль которого вы хотите изменить. Этот Логин будет связан с пользователем базы данных, пароль которого вы хотите изменить.
password – новый назначенный пароль.
hashed_password – новое хэшированное значение пароля назначенное для логина.
old_password — старый пароль.
MUST_CHANGE — он используется, когда вы хотите, чтобы пароль был изменен при первом входе в систему после оператора ALTER LOGIN.
UNLOCK — разблокирует логин, который был заблокирован.
CHECK_EXPIRATION — по умолчанию установлено значение OFF. Этот параметр определяет, будет ли применяться политика истечения срока действия пароля. Вы должны указать CHECK_EXPIRATION = ON, когда вы используете опцию MUST_CHANGE.
Пример смены пароля
Рассмотрим, как сменить пароль, используя оператор ALTER LOGIN в SQL Server (Transact-SQL).
Например:
ALTER LOGIN admin WITH PASSWORD = ‘mypass’; |
Этот пример ALTER LOGIN изменил бы Login, называемый admin, и изменил бы пароль входа на ’mypass’.
Пример изменение пароля и принудительного изменение
Рассмотрим, как изменить пароль и принудительно изменить пароль после первого входа с помощью оператора ALTER LOGIN в SQL Server (Transact-SQL).
Например:
ALTER LOGIN admin WITH PASSWORD = ‘mypass’ MUST_CHANGE, CHECK_EXPIRATION = ON; |
Этот пример ALTER LOGIN изменил бы Login, называемый admin, и изменил бы пароль для входа на ‘mypass’. Но поскольку мы указали опцию MUST_CHANGE и установите CHECK_EXPIRATION в положение ON, пароль должен быть снова изменен в SQL Server после первого входа (после оператора ALTER LOGIN). Таким образом, это похоже на сброс пароля на временный пароль для входа.