Discord Backup Codes: Learn Everything You Want to Know!
This essay from MiniTool official webpage tells everything related to Discord backup codes, including what are they, how to use Discord backup codes, how to generate Discord backup codes, what to do if lose Discord backup code, etc.
What Are Discord Backup Codes?
A discord backup code is an 8-digit code used to log into Discord account when you are locked out. It is the backup of the 6-digit two-factor authentication (2FA) code that is used for logging in Discord together with Discord username and password under the 2FA. The 2FA is a second step security measure when logging into Discord; it is not required but recommended for safety purposes.
The discord backup code is NOT the password of a Discord account.
![]()
[New] Discord Text Formatting: Color/Bold/Italics/Strikethrough
How to format Discord text? How to bold text in Discord? How to do strikethrough on Discord? How to create gray, cyan, orange, yellow, blue, green and red text?
How to Enable 2FA?
As a reliable security mechanism, 2FA has gained great popularity among Discord users. And many users want to make use of this service but do not know how to set up 2FA. So, this is the guide for them.
- Download an authentication app (Google Authenticator, Authy, 1 Password, etc.) on your phone.
- Launch Discord, go to User Settings and click Enable Two-Factor Auth under My Account tab.
- In the next pop up window, use your authentication app to scan the OR code. Or, just enter the 2FA Key into the authentication software.
- The authenticator will generate 6 digit-codes for you.
- Enter one code into the Discord popup window and click Active.

Once the 2FA is enabled, every time you when you log into Discord, you will be asked to enter your authentication code after the password.
Discord Backup Codes Generator
Then, how to generate discord backup codes? It is easy with Discord program. In case you can’t generate a 2FA code, Discord offers backup codes to you. You can quickly get your backup codes following the below steps.
Step 1. Log in to Discord.
Step 2. Go to User Settings.
Step 3. Under My Account, click View Backup Codes.

Each backup code only works once. Please DO NOT share your backup codes with anyone else. Also, it is recommended that you save them in a safe place in case you can’t access your authentication app.
Discord Backup Codes File Location
If you lock yourself out of your Discord and your smartphone is unavailable, you will rely on your backup code to get access to your Discord account. Where to find discord backup codes?
If you are currently logged into Discord on anywhere, desktop, mobile devices, web browser, etc., you can view your backup code with your current password.
Or, if you can find the “discord_backup_codes.txt” file on your computer, there is still a chance for recovering your Discord account.
When it talks about the discord backup codes txt file, there should be a premise that you have ever click Download Backup Codes in Discord. That is to say, if you haven’t manually saved your backup codes of Discord, there is no such a file.
Suppose you have saved your backup codes locally. You should be asked where to save your codes after clicking the “Download Backup Codes” option. Then, you should know where is the discord_backup_codes.txt file.

Discord Lost Backup Codes
If you don’t have a backup code at hand when you are completely locked out of your account, you will lose your account. Discord support cannot remove 2FA from your account, only you can. So, you have to create a new account to continue to use Discord.
How to Disable Discord 2FA?
If you can still access your Discord account or if you have your Discord backup codes, you can disable the 2-factor authentication in your account.
#1 Go to User Settings.
#2 Click Remove 2FA.

#3 Enter the 6-digit authentication code. Or, just input your 8-digit backup codes into the column.

Make sure there are no spaces or dashes within the backup codes when you enter them. Otherwise, you will receive an invalid Discord backup code error.
- Can New Discord Members See Old Messages? Yes or No?
- How Long Does It Take for a Discord Account to Delete or Disable?
- How to Change Age on Discord & Can You Do It Without Verification
- [7 Ways] Fix “Failed to Connect Spotify to Discord” PC/Phone/Web
- Discord Spotify Listen Along: How to Use & Fix It’s Not Working?
Discord Backup Codes – Where to Find Them?
DISCLOSURE: THIS POST MAY CONTAIN AFFILIATE LINKS, MEANING I GET A COMMISSION IF YOU DECIDE TO MAKE A PURCHASE THROUGH MY LINKS, AT NO COST TO YOU. PLEASE READ MY DISCLOSURE FOR MORE INFO.
Table of Contents
- Viewing Discord Authentication Code.
- Viewing Discord Backup Codes in your account?
- Where can I find Discord_backup_codes.txt file?
- Discord Account — login in with a Backup Code?
- What if my Backup Codes not working?
Having a copy of your Discord Backup Codes is critical in case you lose your authentication app.
With ten Backup Codes at your disposal, it is crucial to know where to find them and generate a new set if required.
You will find the Discord Backup Codes in the following location.
- Login to your Discord account.
- Click the Settings icon to view your Discord profile settings.
- Press View Backup Codes under the My Account Settings section.
- Confirm your Discord Account Password.
You can view your 8-digit Discord Backup Codes at any time in your account, but you must also make sure to keep a copy of them in a safe place.
You have ten backup codes at your disposal. A single code should be used in case you have lost access to your authenticator app.
A new set of Discord Backup Codes should be generated after all of them have been used.
By the way, did you know that you can store your backup codes in 1Password alongside your account login details?
And not only that, 1Password has an Authenticator application built into it that will automatically populate the 2FA codes for you on the login page both on your computer and the mobile browser. I have been using 1Password for over three years now, and I cannot overstate how much I like this Password Manager.
You can try 1Password for free for 14 days or visit the 1Password website for more information.
Viewing Discord Authentication Code.
- Login to your Discord account using the browser.
- Press a gear icon at the bottom left corner to access settings.
- Press Enable Two-Factor Authentication under the My Account section.
- Confirm your Password.
- Scan the QR using your preferred 2FA application or type the 2FA key manually.
- Type the code and press confirm to complete the process.
- Make sure to download the Backup Codes.
Viewing Discord Backup Codes in your account?
Login to your Discord account. Select User Settings followed by the My Account section.
Scroll down, press View Backup Codes, and confirm your password.
1) Select the User Settings icon.
On the desktop, the settings icon is located at the bottom left corner of the page.
If you are using your mobile phone, the icon is green and located at the bottom right.
![]()
2) The Backup Codes are located at the bottom of the My Account section.

3) Press the View Backup codes button and confirm your password.

4) Download your Backup Codes as discord_backup_codes.txt file.
You can download the discord_backup_codes.txt file to your drive. Make sure to keep that file in a safe location.


Save the discord_backup_codes.txt file in a safe location on your drive, or print them and keep them in a safe place.
If you save them on your drive, you may consider renaming the file with another phrase that will help you remember that these backup codes are for your Discord account, but it will not be so obvious to anyone else.
5) Generate a new set of Backup Codes.
You can generate a new set of Backup Codes anytime you like.
But make sure to generate a new set if you have used all of them.
Remember that a single code can only be used once to access your account.

Where can I find Discord_backup_codes.txt file?
You will find your discord_backup_codes.txt file under the C:\Users\Username\Downloads directory, which is the default download directory when downloading the files from the internet using your preferred browser.
If you have never moved the discord_backup_codes.txt file to a different location, the Downloads directory is the most likely place where you will find the file.
I will urge you, however, to move this file to a safe location, where no one apart from you can have access to it.
Discord Account – login in with a Backup Code?
You can log in to your Discord account using one of the ten Backup Codes.
Type your email or phone number and password as usual, and when you get prompted to type your 6-digit authentication code, paste one of the Backup Codes instead.

Keep in mind that each Backup Code can only be used once, so make sure to generate a new set before using all ten of them.

Otherwise, you will risk locking your account if you don’t have access to your authenticator app.
What if my Backup Codes not working?
Not working Backup Codes may indicate that you have used all of them before generating a new set.
It is easy to forget how many you have used.
However, your Backup Codes should not be treated as a replacement for Two-Factor Authentication.
They should only be used in an emergency when you can’t access your Authenticator app.
If you lost access to your 2FA app and your Backup Codes no longer work, your only option is to contact Discord Support and hope for the best.
My Favorite Software and Hardware.
I appreciate your visit to my blog. I trust that you found the information helpful. To help you further, I’d like to share the software and hardware that I personally use and find valuable. These links are affiliated, meaning that if you make a purchase, I will receive a small commission without any additional cost to you. For more details, please refer to my Disclosure. To be transparent, the software listed is what I have installed on my computer, and the hardware mentioned is what I use to secure my online accounts and store my passwords.
1Password Manager — After three years of use, I can confidently say that 1Password is the best password manager available. Its user-friendly design and robust security features make managing your passwords and personal information a breeze. If you’re interested in trying it, head to the 1Password website, where you can start a free trial or take advantage of the latest deals. I assure you, you won’t regret switching to 1Password.
YubiKey Security Key — Enhance the security of your digital assets with a hardware authentication device, and I suggest the Yubikey 5C NFC. This is the device I personally use, and it provides additional convenience through its NFC compatibility with your phone. If you’re an Apple user, the YubiKey 5Ci is a solid choice and my go-to recommendation.
Discord
Download Discord App for PC, Mac, Android, iOS & Linux
What to do if you lose access to Two-Factor Codes?
With Discord, you can easily communicate with your teammates or friends in the form of text, image, video, and audio. It is a really useful freeware app that is specially designed for video gaming communities.

When you create an account on Discord, then like most of the services it offers you to set up Two-Factor Authentication.
Two-Factor Authentication gives you an extra layer of security and in-case your account gets compromised, no one will be able to access your account unless they provide the Two-Factor Authentication codes.
Sometimes bad luck can hit you, and you get logged out of your Desktop app and also lose access to your phone. In that case, it may be impossible for you to provide two-factor authentication codes. So, what to do if you lose access to Two-Factor Codes?
What to do if you lose access to Two-Factor Codes?
- Double check that if you are logged into your Discord account from Desktop App or Browser. If you are logged in, luckily, you will be able to see all of your backup codes with your current password.
- If that isn’t the case, then you have only one option left and that is to search your computer for “discord_backup_codes.txt”. Search your PC for this file and if you happen to find it, then you are in luck!
These two are the only ways by which you can access your account if you ever lose access.
If you do not have access to your backup codes, then it will be impossible for you to access your account. Discord is unable to remove Two-Factor Authentication or provide you with new backup codes.
4.9/5 — (1101 votes)
58 thoughts on “ What to do if you lose access to Two-Factor Codes? ”
mhD says:
this is suck. it’s shame discord dont think about it!
Caetano says:
David gorels says:
What I can tell you never ever in your life of internet use Google’s authentication system as it does not even try to make another compromise to save your codes
Lori Mcclour says:
I saved my backup codes
, even wrote them down and back codes I wrote in 2 places but Im told they are wrong,! How can that be.
Bad luck comes by volume. I changes my Google pass word on the 3rd of this month but can’t read my own writing to recover my google account
MaverickII says:
Yall are wrong for not thinking of this. Ive used discord since just after launch in 2015. My account was created in 2015 and I had almost my entire internet ecosystem in that. This is awful. You guys dont care about customers apparently. I was a nitro member too and now I wasted money on an account I cant use anymore. Do something about this or Ill leave I dont care.
Cozzyx says:
Same ngl,i have 2018 account now i cant even use it,even tho i have authy codes on my phone for no reason i cant login in.
Aquaerick says:
Same ngl it’s hard for me too because i’m a fivem scripter and on that account i have some important scripts that i made but this happen all because i changed my phone and my pc’s motherboard and now i can’t use the old accoun it’s a shame that an app like this can make it’s customers/users lose all their information please remove it Thank you.
Sanicpoopyyork says:
Yeah I just lost my account yesterday at 8:21am, it’s just bogus these people can’t login to our accounts to just TELL us the codes. You clowns are devs, and we’ve spent money on your site, and just expect us to just go and move on? Luck y’all.
Enido allko says:
Ita bucks hard
William says:
I know right? Sometimes you phone have a Console, Phone, Android, But no PC! I’m just wishing that Discord can share backup codes to your e-Mail. It’s Unlucky how discord didn’t think of that.
Quandel single here says:
THIS SUCKS
Amy says:
Screw discord for doing this and then not having an option to recover the account. My phone was stolen and I lost everything
My discord was 5 years old and now I’m locked out of it.
I feel you 🙁 says:
Similar thing happened to me, blizzard, steam etc all have ways to recover one’s account in case they lose access to their phone number, but discord can’t do something as simple as that? this is just awful
Zoe says:
Actually makes no sense when literally most other social media have ways to recover your account this is unbelievable. My phone screen is completely broken and cant fix it this time. Have no way of turning off the two factor authentication this is so bad on their part
Jeff Brixhamite says:
A standard alternative would be to offer alternative authentication methods (hardware tokens, fido keys etc) to the second factor of choice so there are backup options available but I guess this might prove to expensive to be practical for most users.
Gigi says:
still same problem Dec2020, I mean it makes sense to be hard for a random person to get back your account if they have access to your e-mail etc etc but STILL..get the Discord account linked to your phone option for 2fa extreme recovery or many other things possible if you think about it Discord make it happen, so many people losing their phone or stolen with 2fa app on it means bye bye Discord server..
liam says:
My phone factory reset and I lost my discord account discord should and more than just one way to get your 2fa codes
Person says:
This is stupid, my computer got reset so now im locked out of my acc discord needs to fix it
DUCKDISCORD says:
muck discord, i have my email and password, none of my backupcodes works. And had my phone number connected to discord but when i activated 2FA there was like only 2 option, 1. SMS, 2. Discord Backupcodes, i choosed backupcodes but i dont get it that you cant have also the sms option to verify it with your phone number, nope discord doesnt care.And the ONLY responde discord got is this: “dIsCoRd iS uNaBlE tO rEmOvE tWo-FaCtOr AuThEnTiFCaTiOn Or PrOvIdE yOu WiTh NeW bAcKuPcOdEs”. You have my email and password and you cant say i can get my account back, ALL others sites like YT or lucking google send you a verification message with a code you can put and voila, you are logged in CUZ YOU HAD YOUR EMAIL AND PASSWORD, i wanted to try out 2FA just for fun to test it out and thats what i get for not have a bucking authentification app installed. DUCK DISCORD for being so useless in this subject area and not giving a sh*t for their users. I had this acc for like 5 Years and i wont make another acc, i will never use discord anymore. duck discord
person says:
same cuz I even don’t think this is fair and in result of this I also don’t think i m going to make another account cuz this really sucks
William says:
I gotta agree with him, Discord does not give a luck if they have your Mail and Password.
Tanzanite Wolf says:
I’ve been looking for my authenticator codes like 2 weeks and I’m really DISAPPOINTED ;-;
Alkareem says:
This is a big and major problem which must be solved somehow cause If we can’t recover our accounts then its too hard to make another account same as the first one. Also the thing in my case is that I had all grinding on my account of dank memer which is wasted now !!
M. says:
This is absolutely stupid! I don’t have those “backupcodes” anymore. Resetting Password doesn not work: you always need those codes in addition. And no way to get back my account. Discord: kill yourself.
NPcrafterYT says:
I am sad I lost my two factor f
Ibrahim says:
what the luck discord .
ŘΛΠGΞŘ〢ƉɆ⩔ƗⱠ ᴮᵀˣ says:
I lost my discord account and that had 2fa security and also I lost backup codes for it so please give my account.
Thank you
Rebecca Meadows says:
I have all my back-up codes …. none of the will work… so stupid. I have all the information needed to log into my account and it will not log me in. I what is the freaking time limit before it forgets your information and requires this back up code crap. I log in at home all the time – and it works. I log in sometimes at work or on phone and always have to use the back up code … which NEVER works.
Dan says:
Discord Mucks for this reason thanks for being ducks! I’m uninstalling this trash app and I hope others will do the same and avoid being locked out of their account, I’m spreading the word because no one should use an app that was created by retards.
gaurav says:
2021, and still discord haven’t put any alternative for backup codes. my mobile got stolen and i don’t have my account logged in on my computer. i’m trying to login but discord doesn’t let me because i don’t have backup codes or authentication app. why the hack i linked my number or email for? you can provide us with codes to log in our account but no what discord does? it says you have to make a new account, like anyone would! lost my 5 years old account and can’t recover it now. lukk discord!
Miisukii says:
i feel you dude same here i got hacked this bad guy changed everything in my Profile guess what the code from the Authentification App is always invalid-.-
what a waste of money time and more !
Name says:
Well this really did not, now i know the only thing i can do is make a new account
Pusi mi kurac says:
yeah, luck discord and their way of managing this…
Ole Kristian Dahlen says:
Take your time to read this!
My daughter lost her account because of this stupid solution:
“Note: If you do not have access to your backup codes, we are unable to remove 2FA and you will have to create a new account. Discord cannot remove 2FA or issue you new backup codes.”
There is only Discord that are able to come up with a stupid solution like this! I know there is lot of people that now have lost their accounts. Over 42000 individs have locked up this problem on Discords website. Only 6000 where happy after reading the solution! There you have over 36000 customers who unhappily lost their account! And this isn’t even close to the total numbers! And Discord don’t give a duck!
My bank, who has very high security, don’t have stupid solution like this: “If you do not have access to your backup codes, you will have to create a new account. You have lost all your money. We are very sorry for your loss.”
This is almost as stupid as Bitcoin security! The brain is there for a reason, use it.
Strobe says:
Name says:
shizzel 7 years gone
Tony says:
this is so stupid. It’s also bad for the environment because of the overload of the servers. Just give a chance to the people to change email or just to switch the data to another account. I can’t do nothing now because of these, i have to create another account from scratch, it’s painful and it’s for no reason. It’s just because they are buzy
Raven says:
And I thought this was a technology company… Thought wrong
Strobe says:
I had this amazing server with a bot that basically turns the server into Pokemon GO, but now I lost that account due to 2fa, and I am SUPER triggered at Discord because i had 2 MEWS! I really want Discord to remove 2fa altogether so I can get back on and be with my friends, my Pokemon, and my LIFE.
Jason Citron says:
Dear Discord Users! I am very sorry to give you bad news, but, unfortunately, for Discord company new user statistics is very important KPI and this way of blocking user is the only way we can get good stats.
Soon we will have a new investment round and investors must be happy. We cannot help you if your house is burned, or you have been robbed and don’t have access to your old phone now.
For us the only thing what matters is MONEY, not the users. Sincerely,
Jason Citron
Ron says:
I lost ma 2fa code of discord and i also don’t now my backup code plss help ne to recover
Goose says:
You sloppy slobby swine scum, screw you discord.
L. Krawczyk says:
I have the same problem, i never log out of my discord and now somehow i’ve be logged out on my pc and my phone, for no reason, i didn’t do it myself.
Try to change my password but they ask me to put in a 2FA recovery code, i dont have. Now years of infomation and projects gone. Becaus they did not provide me with the info that i had to export the back-up codes file to my computer, i have no acces on discord to my phone or another device. Yeah make a new account, is the answer i got from the support. Also they did sent me 2 times a sms code on my phone to verify last month. so why not sent me a recovery code on my phone. I can reset my password on my computer but i need that stupid recovery code to get access to my account and the support is not very helpfull. They say sorry if you do not have those codes we cannot help you. Yeah, then why did you sent me 2 sms verifcation codes to my phone last month. Can you not sent a recovery code to my phone then? I’m very dissapointend in discord and their costumer support.
K says:
Terrible system. Every other major company that uses two-factor has a way to recover if you lose it.
Beat says:
very bad Solution. A recent Google Authenticator App Update broke the app and I lost all Accounts.
SMS Recovery on discord is disabled and I don’t have the Backup Codes.
So i can’t never log in again.
Chilayoot Keoviengkham says:
it’s very shame, I felt you cuz I have the same problem like this
Luna says:
phone stolen…. discord can actually get dcked for this. lost friends, lost memories, absolutely devastated… go dck yourselves!
twatbreath says:
You are an embarassment
moha__ says:
No sense discord, dumb move, really stupid
— says:
This is crazy, I’ve never been so mad at a company for not being more helpful – I do know they can, and they have the possibility to help us recover accounts. There is multiple ways for them to get proof that you are the rightful owner. I’ve been dealing with discord to recover my account, but still no luck. I have been told they can delete my account – as long as im confirming it with the same email connected to the account. That makes no sense Discord, If I can reply from my email connected to my account why in hell shouldn’t I be able to retrieve it? Im laughing and crying at the same time. Cba gaming anymore as I’ve lost a 8 year old account. There is no way to get back to all my friends, server, server roles, etc.
It’s just stupid that they do not have any way to retrieve accounts, they must not know we are in 2023 and should have the technology to make this much easier than they do it.
Scott says:
lost my account of 12 years and i cant get it back? what the actual luck discord
Oleksandr says:
This is only question of time when thoose codes will be lost. In my case I even didn’t know they existing and critical. Just one day got logged out from all devices and found out that my account is lost forever now. Screw you discord, i will never be back.
Sherif Hikal says:
Well, so long Dis this I meant discord.Cordy is out. You guys make it almost impossible to have and maintain an account with you. How many new accounts a person needs to create? All because passwords not enough we must have those back up codes. Well for example I’m outside at work and need to access this discord account however only got my cellphone and desktop which the codes backup ones could be there but again I’m away from home and my desktop now what. Another way when I can or need to access my discord account and only got my cellphone and password but not my desktop. Well, create a new account again. No don’t need more nonsense to remember enough with all the passwords and pins and these backups codes too. Sorry but that’s just not worth the headaches another platform which I love and have been with Riddt no problem no issues. So you guys need to up your game. I really gave y’all fair ” Chances” look I’m one person but not everyone going to help you with a constructive criticism like myself they would just unplug from your site all together. Just saying guys you definitely can do much better.
Douglass Copeland says:
This is complete bullsh*t
memo says:
Tengo el mismo problema, no puede ser que en este epoca un no pueden solucionar esto. Alguien no esta haciendo su trabajo como debe
SW says:
Got a new phone, Autheticator never had 2FA set for discord. Now I am locked out. Had no idea I was meant to write down my code for 2fa. Now I have lost access to friends all around the world over the last 6 years. What a useless system. Most frustratingly, they absolutely could recover an account for you. They just decide not to.
jayjay says:
While I understand the importance of 2fa and backup codes and a bit of how those work, there should still be a way to recover an account. I’ve lost the damn codes thanks to a windows update that f’d up the drive and the mobile app logged me out, leaving my account basically stranded unless a ssd forensics can accomplish to recover the drive. Lessons learned:
Keep your data out of reach of windows update
Keep a copy of the backup codes
Keep a copy of a copy of the backup codes
Keep a copy of a copy of a copy of the backup codes
etc. …
Heatwave says:
A friend of mine just formatted his mobile phone, no back up codes worked for him and after tried everything then he just has to create a new account and lose all past experience… Now that is really a shame and unfortunately the discord 2FA structure idea is a disappointment (saying this when i love discord…).
Leave a Reply Cancel reply
Discord is a trademark of Discord, Inc (formally Hammer & Chisel, Inc). We are not affiliated with Discord Inc. in any ways.
This is an unofficial site created for general information/educational purpose only. Any content found in this website is our own personal opinion and should not be constructed as official statement, advise or recommendation of Discord, Inc. or any of its affiliates.
Установка и настройка сервера на VDS

Copyright ©
Автор: Nordic Warrior. (Telegram: @NordicWarrior)
Первоисточником считать: Репозиторий на GitHub
Данная статья написана лично мной с использованием моего личного опыта и открытых источников, ссылки на которые я предоставляю в конце каждого раздела.
Распространение данной статьи запрещено без указания ссылки на первоисточник и никнейма (контакта) автора.
Дата написания: октябрь-ноябрь 2021 г.
Пара слов от автора
На написание данной статьи меня сподвигло отсутствие таковых подробных статей и инструкций по установке сервера на конец 2021 года.
Всё, что мне удавалось найти либо устарело, либо не было достаточно подробным или рассматривало только какой-то один процесс в установке сервера. Я решил сделать единый гайд, с актуальными сведениями, полностью подробный и понятный даже для незнакомых с этой сферой людей.
Примечание: Я буду рассматривать только установку на ОС Linux, и даже более конкретно, Debian. Я привык работать с ней, а команды на других основных дистрибутивах различаются незначительно, поэтому нет смысла растягивать статью. Так же я буду использовать только скрипт LGSM, поскольку считаю его самым эффективным бесплатным инструментом для управления сервером Counter-strike 1.6.
- FTP клиент. Я пользуюсь FileZilla
- SSH клиент. Я пользуюсь PuTTY
- (Опционально) Хороший текстовый редактор. Я использую Notepad++ (notepad-plus-plus.org)
Выбор хостинга.
. я возлагаю на вас самих. Существует великое множество хостингов, разнящихся ценами, оборудованием, локацией и т.п. Рассматривать этот аспект здесь нет никакого смысла. Кто-то вообще содержит свой собственный домашний сервер.
- Процессор: рекомендую 2.5-3.5 ГГц, 1 ядро под каждый сервер. То есть если вы собираетесь держать два сервера, заказываете 2 ядра и т.д.
- Оперативная память: 2гб, если вы собираетесь устанавливать http сервер и базу данных MySQL, в противном случае хватит и 1гб.
- Жёсткий диск (или SSD): 10гб вполне хватит на 1-2 сервера.
Для начала, заходим в панель управления сервером и ищем там данные для подключения к нему. Нас интересует подключение по SSH и IP-адрес сервера.
После того как мы получили данные (рекомендую их записать куда-нибудь в надёжное место, например создать текстовый документ), открываем PuTTY и добавляем туда подключение к нашему серверу. Тип соединения ставим SSH, вводим IP и пароль нашего сервера. Подключиться!
Мы попадаем на страницу входа в аккаунт. Открываем данные, которые мы записали минуту назад и заходим.
Подготовка виртуальной машины
После того как мы вошли в учётную запись root, и перед тем, как мы приступим к первичной настройке виртуальной машины, необходимо обновить весь имеющийся у нас софт. Вводим в консоль:
apt update && apt full-upgrade
и дожидаемся окончания выполнения команд.
Примечание: Если на вашем хостинге недоступна последняя версия дистрибутива ОС, и стоит, например Debian 10, то apt update может выдать вам следующее:
E: Repository 'http://security.debian.org/debian-security buster/updates InRelease' changed its 'Suite' value from 'stable' to 'oldstable' N: This must be accepted explicitly before updates for this repository can be applied. See apt-secure(8) manpage for details.
Здесь система сообщает нам о том, что репозитории поменяли свою метку со stable на oldstable и предложит согласиться с изменениями: Do you want to accept these changes and continue updating from this repository? [y/N] . Соглашаемся, жмём enter, пока не начнётся установка.
Добавление пользователя
Теперь приступим к первичной настройке виртуальной машины.
Для начала, нам нужно создать нового пользователя и наделить его правами администратора, так как не рекомендуется работать из-под root пользователя в целях безопасности.
Вводим adduser имя_пользователя . Например:
adduser public_server
Система попросит нас ввести поочерёдно пароль для пользователя, затем подтверждение пароля. Дальше нас просят ввести информацию о пользователе, но это делать совершенно не обязательно. Нажимаем последовательно enter, дожидаясь вопроса Is the information correct? [Y/n] , и вводим Y, enter.
Установим пакет sudo, отвечающий за выполнение администраторских команд не от root юзера.
apt install sudo
Далее предоставим новоиспечённому пользователю права администратора.
Вписываем usermod -aG sudo имя_пользовтеля . У нас это:
usermod -aG sudo public_server
Настройка брандмауэра (UFW)
Следующим шагом выполним установку и базовую настройку брандмауэра.
Те, кто хочет использовать другие решения по защите сети, например iptables или защиту от хостинга, могут пропустить этот шаг.
Для начала установим пакет UFW . Вписываем в терминал:
apt install ufw
Это и есть наш брандмауэр. Переходим к его настройке.
Для начала запретим все входящие соединения и разрешим исходящие. Выполняем команду:
ufw default deny incoming && ufw default allow outgoing
Теперь нам надо разрешить те входящие соединения, которые потребуются нам для корректной работы сервера.
Прежде всего разрешим SSH, так как это, собственно, доступ к терминалу сервера. Вводим:
ufw allow ssh
Затем разрешим http соединения, которые понадобятся для быстрой загрузки (и работы веб-дополнений).
ufw allow http
Те, кто собирается организовывать, например, полноценный форум или сайт, скорее всего будут использовать протокол с шифрованием, так что им следует разрешить ещё и https:
ufw allow https
И конечно же, нам потребуется разрешить входящие соединения на порт, который будет использовать игровой сервер. У меня это стандарт — 27015. Выполняем:
ufw allow 27015
Теперь активируем брандмауэр командой:
ufw enable
- ufw disable — отключение.
- ufw reset — сброс.
- ufw status numbered — вывод списка активных правил и их номеров.
- ufw delete номер_правила — удаление определённого правила по его номеру.
- Настройка брандмауэра с UFW в Debian 9 | DigitalOcean
Установка зависимостей
Переходим в пользователя, которого мы создали на предыдущем этапе: su — public_server .
Для начала установим зависимости — пакеты, которые требуются для нормальной работы скрипта. Вводим в терминал:
sudo dpkg --add-architecture i386; sudo apt update; sudo apt install curl wget file tar bzip2 gzip unzip bsdmainutils python util-linux ca-certificates binutils bc jq tmux netcat lib32gcc1 lib32stdc++6
Вводим пароль пользователя для подтверждения и ждём завершения.
Примечание: на Debian 11 я получил предупреждение о том, что пакет lib32gcc1 в репозитории был заменён пакетом lib32gcc-s1 . Если вы получили такое же сообщение, просто замените название пакета в строке выше.
Далее выполняем команду, загружающую скрипт в текущую папку:
wget -O linuxgsm.sh https://linuxgsm.sh && chmod +x linuxgsm.sh && bash linuxgsm.sh csserver
Чтобы переименовать скрипт, воспользуйтесь командой mv :
mv csserver новое_имя
Например: mv csserver public .
Процесс установки
Запускаем автоматическую установку командой:
./csserver auto-install
Скрипт сам проверит, установлены ли все зависимые компоненты, и если нет, установит их.
Если установка скрипта и сервера прошла успешно, вы получите соответствующую надпись об этом.
Теперь можно попробовать запустить сервер для проверки.
Пишем в терминале:
./csserver start
Если всё успешно, можно попробовать подсоединиться к серверу.
Для подключения используйте IP VDS-сервера и стандартный порт 27015.
Примечание: на текущем этапе зайти на сервер можно только с лицензионной версии игры.
Важно: выходить из консоли следует только через сочетание клавиш CTRL + B , затем D . Если вы попытаетесь выйти из консоли нажав по обыкновению CTRL + C , это завершит процесс сервера.
Активация полных краш-логов
На этом этапе можно сразу же активировать создание полных краш-логов. Иначе если у вас будет падать сервер, вам никто не сможет помочь. Делается это быстро и просто.
Устанавливаем через терминал пакет gdb , пишем:
apt install gdb
Подключаемся к серверу через FileZilla, используя SFTP протокол. Для этого вводим в поле «Хост» адрес вашего сервера, логин и пароль в соответствующие поля (не забываем, что войти нам сейчас надо не за root, а за пользователя, у которого установлен наш скрипт), а в поле «Порт» пишем «22», что соответствует SFTP. Подключаемся.
Мы попадаем в домашнюю директорию пользователя, в примере я использовал public_server .
Далее переходим в папку serverfiles через FileZilla и находим здесь файл hlds_run .
Открываем его для редактирования. Поиском находим такую строку:
ulimit -c 2000
и заменяем 2000 на «unlimited», чтобы получилось так:
ulimit -c unlimited
На этом всё! Сохраняем и закрываем файл.
Настройки сервера и скрипта
Заходим через FTP-клиент в папку lgsm -> config-lgsm -> csserver . Здесь хранятся конфиги LGSM.
Нас интересует конфиг csserver.cfg , который отвечает за наш игровой сервер.
Открываем его и производим первичную настройку.
Все доступные параметры можно посмотреть в стандартном конфиге _default.cfg , который находится в этой же директории. Описания к ним можно прочитать по ссылкам, приведённым в конфиге.
Я приведу пример своих настроек.
################################## ####### Instance Settings ######## ################################## # PLACE INSTANCE SETTINGS HERE ## These settings will apply to a specific instance. #### Game Server Settings #### ## Predefined Parameters | https://docs.linuxgsm.com/configuration/start-parameters ip="0.0.0.0" port="27015" clientport="27005" defaultmap="de_dust2" maxplayers="16" ## Server Parameters | https://docs.linuxgsm.com/configuration/start-parameters#additional-parameters startparameters="-game cstrike -strictportbind +ip $ -port $ +clientport $ +map $ +servercfgfile $ -maxplayers $ -pingboost 3 -debug" #### LinuxGSM Settings #### ## Backup | https://docs.linuxgsm.com/commands/backup maxbackups="4" maxbackupdays="30" stoponbackup="on" ## Logging | https://docs.linuxgsm.com/features/logging consolelogging="on" logdays="7" #### Directories #### # Edit with care ## Game Server Directories systemdir="$/cstrike" executabledir="$" executable="./hlds_run" servercfgdir="$" servercfg="$" servercfgdefault="server.cfg" servercfgfullpath="$/$"
- ip — отвечает за IP сервера. Если на предыдущем шаге у вас получилось зайти на сервер, оставьте его в стандартном виде. 0.0.0.0 — обозначает автоматическое определение IP-адреса. В противном случае можно попробовать вставить сюда непосредственно IP сервера.
- port — желаемый порт сервера. Не забываем давать доступ к нему через UFW.
- clientport — клиентский порт. Не трогаем.
- defaultmap — карта, с которой будет стартовать сервер.
- maxplayers — кол-во слотов сервера.
- startparameters — параметры запуска сервера.
- maxbackups — максимальное кол-во хранимых бэкапов сервера.
- maxbackupdays — сколько дней будет храниться каждый бэкап.
- stoponbackup — останавливать ли сервер во время бэкапа. Лучше оставить включённым.
- consolelogging — лог всего происходящего в консоли сервера. На мой взгляд, очень удобная фича, которой не хватает на хостингах.
- logdays — сколько дней будут храниться логи.
- systemdir — директория, где находится корневая папка игрового сервера.
- executabledir — директория, где находится корневая папка самого скрипта.
- executable — название исполняемого файла скрипта. Не рекомендую трогать само название, но сюда можно приписать параметры запуска процесса сервера, например привязку к определённому ядру процессора.
- servercfgdir — директория, где находится конфиг игрового сервера (server.cfg).
- servercfg — название конфига игрового сервера.Здесь я изменил значение на «$», чтобы использовать более привычное для CS 1.6 название server.cfg. По стандарту здесь указано «$.cfg» — название конфига по имени скрипта ( csserver.cfg ).
- servercfgdefault — стандартное название конфига. Не меняем.
- servercfgfullpath — полный путь до конфига сервера.
Команды скрипта
Лучше всего сразу изучить команды, которыми располагает наш скрипт. Для этого введём ./csserver — тогда появится список всех команд с их описанием.
Я приведу с переводом здесь основные, которые могут нам понадобиться.
| Команда | Сокращение | Описание |
|---|---|---|
| start | st | Запускает сервер |
| stop | sp | Останавливает сервер |
| restart | r | Перезапускает сервер |
| monitor | m | Проверяет доступность сервера и перезапускает его в случае падения |
| test-alert | ta | Отправляет тестовое предупреждение (об этом позже) |
| details | dt | Показывает основную информацию о сервере |
| postdetails | pd | То же, что и предыдущее, только загружает информацию на сервис Termbin (аналог Pastebin) и выдаёт ссылку |
| update-lgsm | ul | Проверяет и производит обновление скрипта LGSM |
| backup | b | Делает бэкап сервера |
| console | c | Открывает консоль игрового сервера |
| send | sd | Даёт возможность отправить команду в консоль сервера, не заходя в неё |
- Перезагрузку виртуальной машины раз в месяц.
- Автоматический запуск сервера при включении виртуальной машины.
- Перезагрузку игрового сервера раз в сутки.
- Создание резервной копии сервера каждые две недели.
- «Мониторинг» сервера на предмет падений.
crontab -e
Если вы выполняете эту команду впервые на текущей виртуальной машине, система попросит выбрать вас, какой текстовый редактор вы предпочитаете использовать (и если в вашем дистрибутиве установлено несколько редакторов «из коробки»). В моём случае мне предложили Vim или nano. Всем новичкам я настоятельно рекомендую выбрать именно nano, поскольку Vim имеет весьма специфическое управление.
Итак, вы выбрали редактор и перед вами открылся файл, содержащий cron jobs (именно так они называются). По умолчанию он пуст (не считая «комментариев»).
Обратите внимание, что каждый cron job пишется с новой строки.
Стрелками на клавиатуре опускаем ввод в самый низ.
Устанавливаем перезагрузку виртуальной машины. Разумнее будет сделать её под утро, когда на сервере низкий онлайн. Я выбрал время 4 утра.
0 4 1 * * reboot
Нажимаем CTRL + X , система предложит сохранить наш файл с заданиями. Жмём Y .
Можно проверить, что мы всё сделали правильно, пишем следующую команду:
crontab -l
которая выведет на экран содержимое файла. Если вы видите в конце строчку, которую только что вписали, значит всё в порядке.
Далее, для работы с заданиями по игровому серверу, лучше всего использовать юзера, под которым работает наш скрипт. Можно перейти в учётную запись этого юзера и повторить действия выше, а можно просто отредактировать файл заданий того юзера, не выходя с root.
crontab -u имя_пользователя -e
Откроется такой же самый файл, только в дальнейшем он будет исполняться от нашего пользователя, запускающего LGSM.
Настроим автоматический запуск сервера после включения виртуальной машины:
@reboot ./csserver st > /dev/null 2>&1
Установим перезагрузку игрового сервера раз в сутки. Опять же, ранним утром:
0 4 * * * ./csserver r > /dev/null 2>&1
Далее зададим резервное копирование раз в две недели (в 04:05, после перезагрузки):
5 4 */14 * * ./csserver b > /dev/null 2>&1
И наконец, добавим мониторинг сервера на доступность.
Команда monitor , которая будет проверять сервер на предмет падений, например, каждые 5 минут:
*/5 * * * * ./csserver m > /dev/null 2>&1
Для справки: > /dev/null 2>&1 — используется для блокировки текстового вывода на экран от выполнения команды.
- Home — LinuxGSM_
- Crontab.guru — The cron schedule expression editor — неплохой сервис для настройки времени cron’ов.
Установка ReHLDS
Переходим по ссылке: Releases · dreamstalker/rehlds (github.com). Скачиваем и устанавливаем последний релиз.
Установка предельна проста: выключаем наш сервер командой ./csserver sp и просто загружаем файлы через FileZilla в корневую папку сервера (то есть /serverfiles), заменяя текущие. Включаем сервер, заходим в консоль и проверяем версию командой version .
На момент написания статьи я получаю такой вывод:
Protocol version 48 Exe version 1.1.2.7/Stdio (cstrike) ReHLDS version: 3.11.0.767-dev Build date: 03:13:55 Oct 25 2021 (2753) Build from: https://github.com/dreamstalker/rehlds/commit/471158b
Создание и настройка конфига
Поскольку ReHLDS не имеет собственного конфига, мы создадим его своими руками. Переходим в папку cstrike и создаем файл rehlds.cfg . Открываем его, и вписываем туда те квары, которые привносит в движок именно ReHLDS. И добавим строчку, которая будет выводиться в консоль при чтении конфига.
echo Executing ReHLDS Configuration File // Конфигурационный файл для ReHLDS // Автоматически подгружать звуки, используемые в v_* моделях sv_auto_precache_sounds_in_models "0" // Загружать пользовательские спреи после входа в игру, а не при подключении. Это увеличивает скорость загрузки sv_delayed_spray_upload "1" // Выводить в консоль попытки использования неизвестных команд sv_echo_unknown_cmd "1" // Позволяет отключить логирование пароля RCON sv_rcon_condebug "0" // Исправлять застревание на передвижной платформе/энтити. (Глобальная проблема на DeathrunMod и на картах с транспортом эвакуации) sv_force_ent_intersection "0" // Принудительно выставить клиентский квар cl_dlmax 1024. Позволяет избежать чрезмерной фрагментации пакетов sv_rehlds_force_dlmax "1" // Устанавливает размер энтити по центру sv_rehlds_hull_centering "0" // Отправлять mapcycle.txt в сообщении serverinfo (Не используется на клиенте) sv_rehlds_send_mapcycle "0" // Исправляет ошибку с анимациями модели игрока, когда игрок имеет присоединенные объекты (aiments). Может вызвать отставание анимации, когда cl_updaterate низка sv_rehlds_attachedentities_playeranimationspeed_fix "0" // Ограничить количество подключений с одного IP-адреса sv_rehlds_maxclients_from_single_ip "5" // Позволяет использовать свой список энтити для карт. Файл с энтити находится по адресу "maps/[map name].ent") // 0 - использовать исходные энтити. // 1 - использовать файлы .ent из каталога карт. // 2 - использовать файлы .ent из каталога карт и создать новый файл .ent, если он отсутствует. sv_use_entity_file "0" // Функция локального игрового времени, которая уменьшает лаги, если у вас долго запущена одна и та же карта sv_rehlds_local_gametime "0" // Максимальный средний уровень «move» команд для бана sv_rehlds_movecmdrate_max_avg "400" // Время в минутах, на которое игрок будет забанен (0 - навсегда, отрицательное число - кикнуть) sv_rehlds_movecmdrate_avg_punish "-1" // Максимальное отклонение уровня «move» команд для бана sv_rehlds_movecmdrate_max_burst "2500" // Время в минутах, на которое игрок будет забанен (0 - навсегда, отрицательное число - кикнуть) sv_rehlds_movecmdrate_burst_punish "-1" // Максимальный средний уровень «string» команд для бана sv_rehlds_stringcmdrate_max_avg "80" // Время в минутах, на которое игрок будет забанен (0 - навсегда, отрицательное число - кикнуть) sv_rehlds_stringcmdrate_avg_punish "-1" // Максимальное отклонение уровня «string» команд для бана sv_rehlds_stringcmdrate_max_burst "400" // Время в минутах, на которое игрок будет забанен (0 - навсегда, отрицательное число - кикнуть) sv_rehlds_stringcmdrate_burst_punish "-1" // setinfo поля которые будут переданы клиентам от сервера. // Если значение не установлено, то все поля будут переданы, за исключением приставки с подчеркиванием (к примеру _ah). Каждый ключ должен начинаться на слеш. // Например "/name/model/*sid/*hltv/bottomcolor/topcolor" // Больше информации: https://github.com/dreamstalker/rehlds/wiki/Userinfo-keys sv_rehlds_userinfo_transmitted_fields "" // Если включено, сервер будет устанавливать дополнительное случайное число независимо от клиента. Используется для того чтобы сломать norecoil в читах. sv_usercmd_custom_random_seed "0"
Теперь открываем server.cfg и добавляем в самый конец такие строки:
// Execute ReHLDS Config exec "rehlds.cfg"
Примечание:
Если вы будете устанавливать ReGameDLL (следующий шаг), чтение конфига ReHLDS лучше добавить в его конфиг — game.cfg .
Так же при обновлении ReGameDLL, если вы обновляете его конфиг, не забывайте и про строчки с конфигом ReHLDS.
Установка ReGameDLL
Далее поставим ReGameDLL.
Повторяем предыдущие действия, скачиваем последний релиз с GitHub: Releases · s1lentq/ReGameDLL_CS (github.com).
Выключаем сервер, заменяем файлы в корне сервера, включаем обратно. Проверяем свои действия командой в консоли game version .
На текущий момент увидим следующее:
ReGameDLL version: 5.21.0.540-dev Build date: 17:33:16 Oct 25 2021 Build from: https://github.com/s1lentq/ReGameDLL_CS/commit/b9cccc6
Сразу, не отходя от кассы, можно настроить под свой сервер конфиг game.cfg , отвечающий за геймплей на сервере.
Не стану разбирать его здесь, потому что, во-первых, это потребует целой отельной статьи, во-вторых, это слишком индивидуально от сервера к серверу и в-третьих, в нём уже имеются подписи к каждому квару.
Не забывайте добавить в game.cfg чтение конфига ReHLDS из предыдущего шага.
Установка Metamod
Мы будем использовать Metamod-r, поскольку эта версия содержит множество оптимизаций и исправлений, а так же полностью совместима с ReHLDS.
Переходим по ссылке: Releases · theAsmodai/metamod-r (github.com) и скачиваем последний доступный релиз.
Загружаем в папку cstrike папку addons из архива, и переходим в неё, а далее в папку /metamod . Удаляем файл metamod.dll , поскольку он предназначен для Windows.
Здесь же создаём файл plugins.ini — он понадобится нам для установки дополнений.
Теперь активируем Metamod, для этого вернёмся в папку cstrike, в которой ищем файл liblist.gam и открываем его вашим текстовым редактором.
Нас интересует параметр gamedll_linux .
Заменяем его значение на путь до .so-файла Metamod.
gamedll_linux «dlls/cs.so» -> gamedll_linux «addons/metamod/metamod_i386.so»
Перезагружаем сервер.
На этом установка Metamod завершена.
Заходим в консоль и убеждаемся в том, что он работает, введя команду meta version .
На момент написания статьи вы должны получить вот такой вывод:
Metamod-r v1.3.0.128, API (5:13) Metamod-r build: 17:47:54 Aug 24 2018 Metamod-r from: https://github.com/theAsmodai/metamod-r/commit/0cf2f70
Установка AmxModX
Здесь у вас есть выбор: ставить стабильную ветку разработки (версия 1.9.0) или же экспериментальную (1.10.0), куда вносится новый функционал.
Лично я рекомендую 1.9.0, поскольку если вы не знакомы со скриптингом под AmxModX, версия 1.10.0 не даст вам абсолютно никаких преимуществ.
Итак, переходим по ссылке: AMX Mod X — Half-Life Scripting for Pros!.
Находим самый последний билд, вверху таблицы, нажимаем на значок Linux, и скачиваем там Base Package, а так же Counter-Strike.
Открываем оба архива, и загружаем в папку cstrike папку addons из них, сначала из Base Package, потом из Counter-Strike, соглашаясь на замену файлов.
Открываем ранее созданный нами файл со списком плагинов для Metamod по пути: addons/metamod/plugins.ini и добавляем туда следующую строчку:
linux addons/amxmodx/dlls/amxmodx_mm_i386.so
Сохраняем и перезапускаем сервер.
Заходим в консоль и убеждаемся, в том что AmxModX работает, введя команду meta list. В списке должна быть такая надпись:
[ 1] AMX Mod X RUN - amxmodx_mm_i386.so v1.9.0.5293 ini Start ANY
Если она есть, значит мы всё сделали правильно, и можно переходить к следующему шагу.
(Опционально) Проверка дампов падений сервера
Здесь же можно сразу проверить, правильно ли мы настроили показ дампов падений сервера.
Создаём новый файл в любом месте у нас на компьютере и называем его, например, crash_test.sma . Открываем его текстовым редактором и копируем туда следующий код:
#include #include public plugin_init() < register_plugin("Crash", "1.0", "Dev-CS Team"); // Generate exception code 0xC0000005 set_task(1.0, "GenerateExceptionCode"); >public GenerateExceptionCode() < server_print("[Crash]: I call segmentation fault! Exception code: 0xC0000005"); // Put invalid pointer that will be generate access violation exception set_tr2(0xDEADBEEF, TR_InWater, true); >
Далее у нас есть два пути: скомпилировать файл на Windows или на Linux.
Те, кто умеет компилировать плагины на Windows, могут скомпилировать его и переходить к следующему шагу с установкой.
Для остальных я вкратце расскажу, как скомпилировать плагин на Linux.
Полная статья: Локальное компилирование плагинов | Dev-CS.ru
В FileZilla идём по пути serverfiles/cstrike/addons/amxmodx/scripting .
Загружаем сюда наш файл crash_test.sma .
Находим файл amxxpc , кликаем на него правой кнопкой мыши и выбираем пункт Права доступа к файлу. В поле для ввода вписываем права 754 -> OK.
Открываем PuTTY. Теперь нам надо убедиться, что мы в корневой папке пользователя, командой:
Далее переходим в папку, куда мы поместили исходник плагина с краш-тестом:
cd serverfiles/cstrike/addons/amxmodx/scripting
Запускаем компиляцию:
./amxxpc crash_test.sma
Если вы увидели такой вывод на экран, значит вы сделали всё правильно:
AMX Mod X Compiler 1.9.0.5293 Copyright (c) 1997-2006 ITB CompuPhase Copyright (c) 2004-2013 AMX Mod X Team Header size: 300 bytes Code size: 288 bytes Data size: 456 bytes Stack/heap size: 16384 bytes Total requirements: 17428 bytes Done.
Не забывайте снова вернуться в корневую папку пользователя командой cd .
Дальше разворачиваем опять FileZilla, находим в той же папке scripting наш новый файл crash_test.amxx (не .sma!) и перетаскиваем его на две точки вверху, чтобы переместить в директорию выше.
Следуем стандартной процедуре установки плагинов: перетаскиваем файл в папку plugins, переходим в папку configs, находим там файл plugins.ini и вставляем в самый конец: crash_test.amxx . Сохраняем.
Теперь перезагрузим наш сервер и посмотрим, что получилось. В терминале выполняем: ./csserver r .
Не забудьте сразу отключить плагин краш-теста сервера! Закомментируйте или удалите его название в plugins.ini .
Разворачиваем FTP и переходим в папку serverfiles. Здесь ищем файл debug.log и открываем его.
Если вы видите примерно такое содержание:
---------------------------------------------- CRASH: Sat 16 Oct 2021 07:27:08 AM MSK Start Line: ./hlds_linux -game cstrike -strictportbind +ip 0.0.0.0 -port 27015 +clientport 27005 +map de_dust2 +servercfgfile server.cfg -maxplayers 16 -pingboost 3 -debug -pidfile hlds.5833.pid [New LWP 5870] [New LWP 5871] [New LWP 5876] [New LWP 5877] [New LWP 5878] [New LWP 5879] [New LWP 5880] [New LWP 5881] [New LWP 5872] [Thread debugging using libthread_db enabled] Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1". Core was generated by `./hlds_linux -game cstrike -strictportbind +ip 0.0.0.0 -port 27015 +clientport'. Program terminated with signal SIGSEGV, Segmentation fault. #0 0xf265935b in set_tr2(tagAMX*, int*) () from cstrike/addons/amxmodx/modules/fakemeta_amxx_i386.so [Current thread is 1 (Thread 0xf7b8c700 (LWP 5870))] #0 0xf265935b in set_tr2(tagAMX*, int*) () from cstrike/addons/amxmodx/modules/fakemeta_amxx_i386.so #1 0xf293bb08 in CLog::LogError(char const*, . )::msg () from /home/cs/serverfiles/cstrike/addons/amxmodx/dlls/amxmodx_mm_i386.so #2 0xf24f9454 in ?? () Backtrace stopped: previous frame inner to this frame (corrupt stack?) No symbol table info available. From To Syms Read Shared Object Library 0xf7f5b130 0xf7f5c1c4 Yes (*) /lib/i386-linux-gnu/libdl.so.2 0xf7ecd914 0xf7f13c78 Yes ./libstdc++.so.6 0xf7d8b170 0xf7e4c4af Yes (*) /lib/i386-linux-gnu/libm.so.6 0xf7bbc0e0 0xf7d08d76 Yes (*) /lib/i386-linux-gnu/libc.so.6 0xf7f6f090 0xf7f8a50b Yes (*) /lib/ld-linux.so.2 0xf7b8fe04 0xf7b9f490 Yes ./libgcc_s.so.1 0xf74b02b0 0xf75a0660 Yes (*) /home/cs/serverfiles/engine_i486.so 0xf74733d0 0xf7476cb4 Yes (*) /lib/i386-linux-gnu/librt.so.1 0xf74605c0 0xf746ad74 Yes (*) ./libsteam_api.so 0xf74425e0 0xf7451eff Yes (*) /lib/i386-linux-gnu/libpthread.so.0 0xf7417e00 0xf7433838 Yes (*) /home/cs/serverfiles/filesystem_stdio.so 0xf567e000 0xf6bdb0c4 Yes (*) /home/cs/.steam/sdk32/steamclient.so 0xf2cfa6a0 0xf2d3cf70 Yes (*) /home/cs/serverfiles/./cstrike/addons/metamod/metamod_i386.so 0xf2a95280 0xf2c2c0b0 Yes (*) /home/cs/serverfiles/cstrike/dlls/cs.so 0xf2779a20 0xf27dcdb7 Yes (*) /home/cs/serverfiles/cstrike/addons/amxmodx/dlls/amxmodx_mm_i386.so 0xf2702b60 0xf274a624 Yes (*) cstrike/addons/amxmodx/modules/hamsandwich_amxx_i386.so 0xf2671120 0xf2677404 Yes (*) cstrike/addons/amxmodx/modules/csx_amxx_i386.so 0xf262f9d0 0xf265bd6c Yes (*) cstrike/addons/amxmodx/modules/fakemeta_amxx_i386.so 0xf0328000 0xf18468a4 Yes (*) ./steamclient.so 0xf2260670 0xf22d6020 Yes (*) ./crashhandler.so 0xf24db300 0xf24e1cd4 Yes (*) /lib/i386-linux-gnu/libnss_files.so.2 0xf24d21c0 0xf24d51f4 Yes (*) /lib/i386-linux-gnu/libnss_dns.so.2 0xf24ba3a0 0xf24c6014 Yes (*) /lib/i386-linux-gnu/libresolv.so.2 (*): Shared library is missing debugging information. Stack level 0, frame at 0xff9c4734: eip = 0xf265935b in set_tr2(tagAMX*, int*); saved eip = 0xf293bb08 called by frame at 0xff9c4738 Arglist at 0xff9c472c, args: Locals at 0xff9c472c, Previous frame's sp is 0xff9c4734 Saved registers: ebx at 0xff9c4728, ebp at 0xff9c472c, esi at 0xff9c4720, edi at 0xff9c4724, eip at 0xff9c4730 End of crash report ----------------------------------------------
Значит у вас всё получилось.
В противном случае вы увидите урезанный краш-лог:
---------------------------------------------- CRASH: Wed 13 Oct 2021 09:16:04 PM MSK Start Line: ./hlds_linux -game cstrike -strictportbind +ip 0.0.0.0 -port 27015 +clientport 27005 +map de_dust2 +servercfgfile server.cfg -maxplayers 16 -pingboost 3 -debug -pidfile hlds.20701.pid End of crash report ----------------------------------------------
Попробуйте перечитать и выполнить заново шаг с активацией полных краш-логов.
- Как получить Dump падения HLDS | Dev-CS.ru
- Локальное компилирование плагинов | Dev-CS.ru
Начнём с установки веб-сервера Nginx. Пишем:
sudo apt install nginx
После установки он автоматически начнёт свою работу. Проверить это можно зайдя на адрес нашего сервера в браузере. Если вы видите страницу с текстом: # Welcome to nginx! , значит всё прошло успешно.
Теперь перейдён к конфигурации Nginx под сервер быстрой загрузки.
Для этого заходим под root пользователем через FileZilla, и идём по следующему пути: /etc/nginx/sites-available . Здесь будет находиться файл конфига nginx по умолчанию ( default ).
Открываем его для редактирования. В разделе server, перед закрывающей скобкой ‘>’, вставляем следующее:
# Быстрая загрузка для Counter-Strike location /fastdl/ < alias /home/public_server/serverfiles/cstrike/; autoindex on; location ~* (\.wad$|(maps|sprites|models|gfx|sound|media|overviews)/.*(bsp|mdl|spr|wav|mp3|bmp|tga|txt|res)$) < allow all; >deny all; >
Где /home/public_server/serverfiles/cstrike/ — это путь до папки cstrike на нашем сервере. Проверьте его и исправьте на свой вариант, если он отличается.
Сохраняем этот файл и проверяем его на корректность. Для этого нам понадобится такая команда:
sudo nginx -t
Если мы получили сообщение, что все конфиги в порядке, перезагружаем Nginx:
sudo service nginx restart
Теперь можно проверить, что у нас получилось. Снова открываем браузер, заходим на наш веб сервер и пытаемся скачать какой-нибудь файл, например карту de_dust2.
http://адрес_сервера/fastdl/maps/de_dust2.bsp
Если она скачалась, значит вы всё сделали правильно!
Теперь откроем конфиг игрового сервера (server.cfg) и добавим туда следующие квары:
sv_allowdownload 1 sv_downloadurl "http://адрес_сервера/fastdl/"
На этом основная настройка сервера завершена!
- Как установить LEMP на Debian 9 – База знаний Timeweb Community
- Правильная настройка FastDL на VDS (c-s.net.ua)
Установка и настройка Reunion
Наиболее вероятно, к вам на сервер будут заходить игроки с пиратской копией игры (Non-steam). Возможно, даже вы сами. Однако, они не смогут подключиться к серверу без специального модуля, обеспечивающего игру на сервере для пиратских клиентов.
- CS.RIN.RU — Steam Underground Community • Просмотр темы — Reunion 0.1.92 — no-steam for ReHLDS
- addons Reunion | Dev-CS.ru
Помещаем бинарный файл reunion_mm_i386.so по пути addons/reunion/ , затем прописываем в файле Metamod-плагинов:
linux addons/reunion/reunion_mm_i386.so
После этого помещаем файл конфигурации reunion.cfg из архива в папку cstrike.
Важно:
Reunion должен быть на первом месте в списке meta плагинов.
Важно:
Даже если вы не собираетесь проводить глубокую настройку Reunion, настоятельно рекомендуется задать «соль». Это нужно, чтобы чтобы никто не мог взять SteamID другого игрока.
Находим в конфиге строку SteamIdHashSalt и вписываем туда набор из случайных символов длиной не менее 16-ти знаков.
Перезапускаем сервер, чтобы модуль начал свою работу.
Теперь убедимся, что он работает. В консоли сервера пишем уже знакомую нам команду meta list . Reunion должен иметь статус RUN:
Currently loaded plugins: description stat pend file vers src load unlod [ 1] Reunion RUN - reunion_mm_i386.so vX.X.X ini Start Never
Примечание:
По более тонкой настройке Reunion есть отличный гайд по этой ссылке: Подмена SteamID | Dev-CS.ru
Если вы собираетесь содержать выделенный сервер для всех, а не просто поиграть с друзьями или ботами, я рекомендую выполнить настройку по статье выше.
Установка компонентов веб-сервера
Большинство серверодержателей наверняка захотят установить CSBans или другие веб-дополнения. Я расскажу, как установить основные необходимые для этого инструменты: PHP и MySQL.
Установка MariaDB
Начнём мы с установки СУБД.
sudo apt install mariadb-server
После установки необходимо произвести конфигурацию командой:
sudo mysql_secure_installation
Сейчас нам предложат указать пароль для root пользователя MariaDB, если он был уже указан. Посльку мы только установили эту СУБД, оставляем поле пустым и жмём enter.
В некоторых случаях на текущем этапе система может предложить переключиться на unix_socket аутентификацию ( Switch to unix_socket authentication [Y/n] ). Отклоняем.
Теперь нам предложат сменить пароль для root пользователя ( Change the root password? [Y/n] ). Соглашаемся и задаём свой пароль.
В ином случае, если вам будет сразу предложено задать пароль для root пользователя ( Set root password? [Y/n] ), соглашайтесь и задайте его.
Далее идёт стандартная процедура настройки, система предложит удалить анонимных пользователей, отключить удалённый доступ к root пользователю, удалить тестовую базу данных и перезагрузить таблицу привелегий. Во всех вариантах можете выбрать Y.
На этом установка завершена.
Но теперь нам необходимо создать нового пользователя MySQL чтобы использовать его из-под игрового сервера.
Заходим в нашу базу данных под root пользователем:
mysql -u root -p
Теперь создадим пользователя (admin — логин и password — пароль укажите свои):
CREATE USER 'admin'@'localhost' IDENTIFIED BY 'password';
Затем выдадим этому пользователю все привилегии:
GRANT ALL PRIVILEGES ON * .* TO 'admin'@'localhost';
И пишем exit для выхода из БД.
На этом установка базы данных завершена!
apt install php-fpm php-mysql
На этом установка завершена.
Но на всякий случай проверим, всё ли в порядке.
Переходим в FileZilla по следующему пути: /var/www/html .
Здесь создаём файл info.php. Открываем его и вставляем туда следующее содержание:
В браузере переходим по адресу нашего файла, т.е.: http://адрес_сервера/info.php .
Если вы видите страницу с конфигурацией php, значит вы всё сделали правильно.
Для начала установим необходимые компоненты:
apt install php-mbstring mcrypt
Теперь приступим к установке самой утилиты:
apt install phpmyadmin
Сначала нам будет предложено выбрать сервер для работы с приложением. К сожалению, Nginx нет в списке, так что снимаем выбор с обеих строк и нажимаем ОК.
Следующим шагом будет автоматическое создание баз данных для phpmyadmin, соглашаемся.
После этого у нас попросят ввести пароль для пользователя phpmyadmin. Вводим.
Затем нам понадобится включить расширение mcrypt , что мы и делаем:
phpenmod mcrypt
И последний шаг. Открываем уже знакомый нам конфиг Nginx по пути /etc/nginx/sites-available .
Находим следующую строку:
# Add index.php to the list if you are using PHP index index.html index.htm index.nginx-debian.html;
Добавляем в этот список index.php . Должно получиться так:
# Add index.php to the list if you are using PHP index index.php index.html index.htm index.nginx-debian.html;
Затем вставляем в конец общего раздела конфигурацию для phpmyadmin:
# Конфигурация для phpmyadmin location /phpmyadmin < alias /usr/share/phpmyadmin/; location ~ \.php$ < fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $request_filename; include fastcgi_params; fastcgi_ignore_client_abort off; >location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ < access_log off; log_not_found off; expires 1M; >>
Сохраняем файл. Как обычно проверяем конфигурацию командой nginx -t , исправляем ошибки, если они есть. Перезагружаем Nginx.
На этом всё!
Теперь идём смотреть, что у нас получилось. В браузере переходим по ссылке: http://адрес_сервера/phpmyadmin . Если вы видите страницу входа в phpmyadmin, значит установка прошла успешно.
Воспользуемся инструментом mysqldump и уже знакомым нам crontab .
На мой взгляд, хранить резервные копии удобнее в директории сервера, поэтому надо перейти за того пользователя, у которого установлен сервер. У нас это public_server .
Открываем редактор crontab и самый конец файла вписываем такую строку:
0 12 */7 * * mysqldump -u admin -ppassword -A > db.sql
mysqldump -u [пользователь mysql] -p[его пароль] -A > [название базы данных].sql
Обратите внимание, что -p и последующий пароль пользователя пишутся слитно.
О том, как настроить время в crontab, было описано в разделе «Настройка расписаний».
Если расшифровать строку из примера, у нас получилось следующее: Каждый седьмой день месяца (раз в неделю) в 12 часов дня будет создан дамп за mysql пользователя admin с паролем password и будет помещён в корневую папку пользователя, за которого запущен crontab (у нас это public_server ), с названием db.sql.
Можно помещать файл в каталог, но в таком случае он должен быть заранее создан. Пример команды:
mysqldump -u admin -ppassword -A > mysql_backup/db.sql
Есть довольно большой список мессенджеров и служб для оповещения, но они больше популярны на западе, чем в странах СНГ.
Для нас можно выделить Email, Telegram и Discord. С полным списком можно ознакомиться здесь: Alerts — LinuxGSM_.
Здесь я рассмотрю подключение к Telegram.
Оповещения через Telegram
Итак, первое, что нам нужно сделать, это создать бота в телеграме.
Переходим по этой ссылке Telegram: Contact @BotFather или ищем в телеграме @BotFather, если он у вас не установлен на компьютере.
Запускаем этого бота и выполняем команду /newbot .
Следуя инструкциям, задаём боту имя и никнейм. В результате у нас появится токен бота, который нам надо будет указать в настройках скрипта.
Открываем конфиг LGSM по уже знакомому нам пути: lgsm/config-lgsm/csserver/csserver.cfg .
В самый конец добавляем:
## Notification Alerts # (on|off) # More info | https://docs.linuxgsm.com/alerts#more-info postalert="on" # Telegram Alerts | https://docs.linuxgsm.com/alerts/telegram # You can add a custom cURL string eg proxy (useful in Russia) in "curlcustomstring". # For example "--socks5 ipaddr:port" for socks5 proxy see more in "curl --help". telegramalert="on" telegramtoken="token" telegramchatid="chatid"
- postalert — позволяет получить дополнительную информацию о сервере на момент неисправности и загружает её на Termbin, аналогично команде ./csserver postdetails .
- telegramalert — собственно, включить или нет оповещения в Telegram.
- telegramtoken — сюда нужно вставить токен нашего нового бота.
- telegramchatid — здесь надо указать индекс вашего с ботом чата. Об этом ниже.
Затем в браузере переходим по следующему пути:
https://api.telegram.org/botXXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/getUpdates
Где XXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX — заменяем на токен бота. Например:
https://api.telegram.org/bot3104437352:AAE2XjHxOIBbfM2U1HStmcOkLdCTw5DJsjY/getUpdates
Оставляем вкладку открытой.
Теперь пишем боту любое сообщение, например LGSM test . Затем обновляем страницу, открытую ранее, и у нас должны появиться технические параметры сообщения.
Ищем наше сообщение в конце строки и двигаемся к её началу, чтобы найти данные примерно такого вида: «chat»: Число 845483018 — это и будет индекс чата, который нам нужен. Копируем его и вставляем в параметр telegramchatid .
Закрываем конфиг и сохраняем его. На этом настройка оповещений завершена.
Мы можем проверить их работоспособность. Для этого воспользуемся командой скрипта ./csserver test-alert .
В результате её выполнения нам в телеграм должен написать наш новый бот с тестовым оповещением.
- Telegram — LinuxGSM_
Примечание: здесь же можно найти инструкцию о том, как подключить бота к группе, а не только к личному чату.
На этом всё. Удачи в создании сервера!