Welcome to our step-by-step guide on creating a .SSH folder in Windows! If you’re someone who wants to connect to SSH servers, manage SSH keys, or simply enhance security in your digital interactions, you’ve come to the right place. In this blog post, we will cover everything you need to know about creating the .SSH folder in order to effectively utilize SSH on your Windows system.
From understanding the importance of SSH keys and their configuration to finding the location of the .SSH folder in Windows, we’ve got you covered. Along the way, we will explore topics like starting an ssh-agent, generating public and private RSA key pairs, installing your public key in Windows, and much more. So, let’s dive into the world of SSH and discover how to create a .SSH folder in Windows like a pro!
Keywords: How do I connect to a SSH server in Windows, How do I start an ssh-agent, What permission should .SSH be, How do I open an ssh file in Windows, How do I get to .ssh folder, How do I SSH, How do I use SSH keys, How do I install a public key in Windows, How do I create a .ssh file in Windows, How do I create a config file in Windows 10, How do I create a private and public key in Windows, Where do I put ssh public key, How do I find my SSH key in Windows 11, How do I change the default directory in SSH, Where is the .ssh folder in Windows, How configure ssh config in Windows, How do I create a private and public key, What is SSH public key, How do I generate a public and private RSA key, How do I set up an SSH key, How do I login using SSH key, How do I find my SSH key, How do I create a .ssh file, What is the .ssh directory.
Step 1: Navigate to your User Directory
To create a .SSH folder on your Windows computer, you’ll first need to navigate to your user directory. Don’t worry, it’s easier than navigating through a corn maze! Open any file explorer window and click on “This PC” or “My Computer.” From there, find your username and double-click on it. Voila! You’re in your user directory.
Step 2: Create a New Folder
Once you’re in your user directory, it’s time to take the plunge and create a .SSH folder. Right-click anywhere in the directory window, hover over “New,” and select “Folder” from the menu that pops up. Don’t worry, this folder won’t be as empty as your social calendar on a Friday night!
Step 3: Name the Folder
Now that you’ve created the folder, it’s time to give it the official .SSH title. Right-click on the newly created folder and select “Rename” from the menu. Type “.SSH” (without the quotes, of course) as the folder name and press Enter. Don’t worry, you won’t accidentally summon a ghost!
Step 4: Enable File Extensions
By default, Windows likes to hide file extensions, and we need to change that to ensure our .SSH folder has the right name. Click on the “View” tab at the top of your file explorer window and tick the checkbox that says “File name extensions.” Now you’ll be able to see that beautiful, dot-laden .SSH folder!
Step 5: Add Some Pizzazz
Creating a .SSH folder is pretty straightforward, but it’s not complete without some pizzazz! Navigate inside your shiny new folder and create a file called “config.” Trust me, this isn’t your regular office paperwork. Right-click within the folder, select “New,” and choose “Text Document.” Rename the file to “config,” ensuring it doesn’t have a .txt extension. We’re not here for a boring office memo, after all!
Step 6: Customize Your Config
Now that you have your config file, it’s time to give it some personality. Double-click on it to open it in any text editor (Notepad will do just fine). This is where you’ll enter all the secret codes and mystical incantations to configure your .SSH folder. But don’t worry, you won’t need a magic wand—just some simple text editing skills!
Step 7: Save and Secure
Before you call it a day, you need to save your changes and ensure they’re secure. If your text editor hasn’t already auto-saved your config file, go ahead and click “File” at the top left, then choose “Save.” To keep this world-class secret secure, make sure you don’t save any sensitive information like passwords in this file. We wouldn’t want your .SSH folder to become an open book for the cat!
Step 8: Celebrate!
Congratulations, you’ve created your very own .SSH folder in Windows! Now you can take a moment to celebrate, do a little happy dance, or even treat yourself to a slice of cake. Just don’t let the cake near your computer—that might create a different kind of folder!
Now that you know how to create a .SSH folder in Windows, you’re ready to embark on exciting adventures in the world of secure file transfers and remote access. So go forth, fearless explorer, and conquer the digital realm with your newfound folder-fu!
FAQ: How to Create a .SSH Folder in Windows
Welcome to our comprehensive FAQ-style guide on creating a .SSH folder in Windows. If you’re new to the world of SSH or simply need a refresher, you’ve come to the right place. We’ll walk you through the process step by step and answer all your burning questions along the way.
How do I Connect to an SSH Server in Windows
To connect to an SSH server in Windows, you can use a variety of tools like PuTTY or OpenSSH. These tools allow you to establish a secure and encrypted connection to a remote server. You’ll need the server’s IP address, username, and password (or SSH key) to complete the connection. Once connected, you can remotely manage the server and perform various tasks.
How do I Start an SSH-Agent
Starting an SSH-agent in Windows is a breeze. Open your command prompt or PowerShell and enter the following command:
ssh-agent
This will start the SSH-agent, which acts as a middleman between your local machine and the remote server. It helps securely manage your SSH keys, making authentication smoother and more secure.
What Permission Should .SSH Be
For optimal security, the .SSH folder should have the correct permissions. In Windows, you’ll want to ensure that only the owner has read, write, and execute permissions, while others have no permissions. This can be achieved by right-clicking the .SSH folder, selecting “Properties,” and adjusting the permissions under the “Security” tab. Remember, security is no laughing matter!
How do I Open an SSH File in Windows
Opening an SSH file in Windows requires a text editor. You can use any text editor of your choice, such as Notepad or Visual Studio Code. Simply right-click the file, select “Open with,” and choose your preferred text editor. From there, you can view and modify the contents of the SSH file as needed.
How do I Get to the .SSH Folder
Finding the elusive .SSH folder in Windows is like searching for a needle in a haystack. Fear not, as we’re here to guide you. The .SSH folder is usually located in your user directory, which you can access by following this path: C:\Users\\.SSH
. Remember to replace with your actual username. Voilà, you’ve found the hidden treasure!
How do I SSH
Ah, the age-old question – “How do I SSH?” SSH, short for Secure Shell, allows you to securely access remote servers and execute commands. To SSH, open your preferred terminal or command prompt and use the following command:
ssh username@server_ip
Replace username
with your actual username and server_ip
with the IP address or domain name of the server you wish to connect to. Enter your password (or SSH key passphrase), and you’re in!
How do I Use SSH Keys
Using SSH keys makes logging into remote servers a breeze. To generate an SSH key pair, use the following command in your terminal:
ssh-keygen -t rsa -b 4096
This will create a public key (id_rsa.pub
) and a private key (id_rsa
) in the default .SSH
folder. The public key is shared with the remote server, while the private key remains on your local machine. This asymmetric encryption ensures secure communication between you and the server.
How do I Install a Public Key in Windows
Installing a public key in Windows is as easy as pie. Follow these steps:
- Copy the contents of your public key (
id_rsa.pub
). - Open the file
authorized_keys
located in the.SSH
folder on the remote server. - Paste the copied public key into a new line in the
authorized_keys
file. - Save the file and exit.
Now, you can enjoy passwordless logins with SSH using your shiny new public key!
How do I Create a .SSH File in Windows
Creating a .SSH
file in Windows is more common than you might think. It’s actually a folder and not a file, but the naming convention might mislead some users. To create the .SSH
folder, follow these simple steps:
- Open your preferred file explorer.
- Navigate to your user directory (
C:\Users\
). - Right-click in the empty space and select “New Folder.”
- Name the folder
.SSH
(including the dot).
Congratulations! You’ve created a .SSH
folder in Windows. It’s time to fill it with SSH goodness.
How do I Create a Config File in Windows 10
Creating a config file in Windows 10 allows you to customize your SSH settings for different servers. Here’s how you do it:
- Navigate to your
.SSH
folder (C:\Users\\.SSH
). - Right-click in the folder, select “New,” and choose “Text Document.”
- Rename the file to
config
(without any file extension). - Open the
config
file with your preferred text editor. - Add your custom configuration settings for each server, following the format specified in the SSH documentation.
- Save the file and start enjoying personalized SSH configurations like a boss.
How do I Create a Private and Public Key in Windows
Creating a private and public key pair in Windows is a piece of cake. Follow these steps:
- Open your favorite terminal or command prompt.
- Use the following command to generate an RSA key pair:
ssh-keygen -t rsa -b 4096
- Choose a secure location for your keys (usually the
.SSH
folder). - Enter a passphrase to further protect your private key.
- Voilà! You now have a private key (
id_rsa
) and a public key (id_rsa.pub
). - Remember to keep your private key safe and secure, like a hidden treasure chest.
Where do I Put SSH Public Key
Your SSH public key (id_rsa.pub
) belongs in the authorized_keys
file on the remote server. This file resides in the .SSH
folder on the server. By placing your public key in the authorized_keys
file, you grant access to your SSH key pair, allowing you to log in without a password. It’s like a VIP pass to SSH!
How do I Find my SSH Key in Windows 11
Finding your SSH key in Windows 11 is not rocket science. Simply follow these steps:
- Open your preferred file explorer.
- Navigate to your user directory (
C:\Users\
). - Go to the
.SSH
folder. - Voilà! Your SSH key pair is waiting for you.
Remember, keys are small and can hide in plain sight, so keep your eyes peeled!
How do I Change the Default Directory in SSH
Tired of landing in the same directory every time you SSH into a server? Fear not, for we have a solution! To change the default directory in SSH, modify your config
file in the .SSH
folder and add the following line:
cd /path/to/desired/directory/
Replace /path/to/desired/directory/
with the actual path of your desired directory. Save the config
file, and on your next SSH session, you’ll be greeted with the directory of your dreams. Easy peasy!
Where is the .SSH Folder in Windows
Ah, the ever-elusive .SSH
folder in Windows. We’ve all been there! Rest easy, fellow traveler, and let us show you the way. By default, the .SSH
folder is located in your user directory, which you can access via this path: C:\Users\\.SSH
. Just remember to replace with your actual username. Happy exploring!
How Configure SSH Config in Windows
Configuring your SSH config in Windows is like a custom-tailored suit for your SSH experience. Here’s how you do it:
- Open your preferred text editor.
- Navigate to your
.SSH
folder (C:\Users\\.SSH
). - Edit the
config
file. - Follow the SSH documentation to add your desired configurations for different hosts.
- Save the file and marvel at your personalized SSH setup.
With a little bit of customization, your SSH config will make you the envy of all sysadmins!
How do I Create a Private and Public Key
Creating a private and public key is a crucial step in the SSH world. Fear not, as we’re here to guide you through the process:
- Open your trusty terminal or command prompt.
- Type the following:
ssh-keygen -t rsa -b 4096
- Choose a secure location for your keys (perhaps the
.SSH
folder). - Set a strong passphrase to safeguard your private key.
- Bravo! You now possess a shiny new key pair – a private key (
id_rsa
) and a public key (id_rsa.pub
). - Remember to guard your private key with your life. It’s your golden ticket to secure communication.
What is SSH Public Key
Ah, the SSH public key – the socialite of the key pair. In simple terms, the public key is like a lock that matches your private key. It’s shared with the remote server, allowing you to prove your identity and establish a secure connection. So, treat your public key like a VIP guest list!
How do I Generate a Public and Private RSA Key
Generating a public and private RSA key pair is a breeze. Just follow these steps:
- Launch your favorite terminal or command prompt.
- Enter the following command:
ssh-keygen -t rsa -b 4096
- Choose a location to store your keys (typically the
.SSH
folder). - Set a passphrase to protect your private key from prying eyes.
- Voilà! You now possess a public key (
id_rsa.pub
) and a private key (id_rsa
). - Guard your private key like a dragon guards its treasure!
How do I Set up an SSH Key
Setting up an SSH key is a rite of passage for every aspiring sysadmin. Follow these steps to achieve key enlightenment:
- Generate an SSH key pair using the
ssh-keygen
command (e.g.,ssh-keygen -t rsa -b 4096
). - Choose a secure location for your keys.
- Optionally, set a passphrase for an extra layer of security.
- Copy the contents of your public key (
id_rsa.pub
). - On the remote server, navigate to the
.SSH
folder and open theauthorized_keys
file. - Paste your public key into a new line, save the file, and close it.
- Bask in the glory of passwordless logins and the convenience of SSH key authentication!
How do I Login Using SSH Key
Logging in using an SSH key takes the stress out of remembering passwords. Simply follow these steps:
- Make sure you have your private and public key pair handy.
- Open your preferred terminal or command prompt.
- Type the following:
ssh -i /path/to/private_key username@server_ip
- Replace
/path/to/private_key
with the actual path to your private key. - Substitute
username
with your username andserver_ip
with the server’s IP address. - Enter your passphrase if you set one.
- Congratulations! You’ve successfully logged in using your SSH key. Revel in the power of key-based authentication!
How do I Find my SSH Key
Misplaced your SSH key? Don’t panic just yet. Here’s how you can find it:
- Open your trusty file explorer.
- Navigate to your user directory (
C:\Users\
). - Locate the
.SSH
folder in all its glory. - Ahoy! Your SSH key pair awaits within this hallowed directory.
Security tip: Make sure to keep your keys safe, sound, and away from any curious minds!
How do I Create a .SSH File
Creating a .SSH
file is more fiction than fact. In reality, it’s a folder! To create it, follow these steps:
- Open your favorite file explorer.
- Navigate to your user directory (
C:\Users\
). - Right-click in the empty space and choose “New Folder.”
- Name the folder
.SSH
(including the dot). - Ta-da! You’ve successfully created a
.SSH
folder to house your SSH treasures.
Now you can store your SSH key pair and embark on a secure remote journey!
What is the .SSH Directory
The .SSH directory is like a cozy home for all your SSH goodness. It typically resides in your user directory (e.g., C:\Users\\.SSH
). Within this directory, you’ll find your SSH key pair, configuration files, and other essentials for secure connections. Treat it like a sacred place, worthy of the utmost respect!
Congratulations! You’ve reached the end of our comprehensive FAQ-style guide. We hope this has shed light on the process of creating a .SSH folder in Windows and answered all your burning questions. Remember to keep your SSH keys safe, your configurations clever, and your connections secure. Happy SSH-ing in the wonderful year of 2023!
Prerequisites
- Windows Subsystem for Linux (WSL) is installed
- For this example we will use the Ubuntu Linux distro/distribution.
- Visit this link to rocket academy to find out more about WSL
Step 1: Understand how to access Linux On Windows
Method 1: Using the file explorer
-
Type
\\wsl$\
into the file explorer. This will direct you to the location of the Ubuntu folder. -
Navigate to your linux folder.
Ubuntu -> Home -> <LINUX USERNAME>
Method 2: Using the WSL terminal
# This command navigates to the linux folder
cd ~/
Enter fullscreen mode
Exit fullscreen mode
# This command lists the files that are in the linux folder
ls -a ~
Enter fullscreen mode
Exit fullscreen mode
Step 2: Create .ssh folder (this is where we’ll put the ssh key)
Notes: If this is your first time accessing this folder, you probably do not have a folder for ssh files and will have to create your own.
Method 1: Using the file explorer
- Create a folder in your linux folder and name it «.ssh»
- Done! Now you can put the key pairs in this folder
Method 2: Using the WSL terminal
# 1. Check if you have a .ssh folder. If you don't have an ssh folder it'll return "No such file or directory"
ls ~/.ssh
Enter fullscreen mode
Exit fullscreen mode
# 2. Create a folder called .ssh
mkdir ~/.ssh
Enter fullscreen mode
Exit fullscreen mode
# 3. Copy any key pairs you need into this folder
# Note: You have to be in the same directory as the file you want to copy
# syntax: cp <FILENAME> ~/.ssh
cp my-aws-ec2-keypair.pem ~/.ssh
Enter fullscreen mode
Exit fullscreen mode
You can create new directories and files through SSH with the commands mkdir and touch respectively.
To make a new folder type the command mkdir followed by a space and the name of the directory. For example:
mkdir example_folder
will create a folder called example_dir in the current working directory. You can also use the full path to the new directory, if you don’t want to change the current working directory and you want the new folder to be created somewhere else (e.g. mkdir /home/username/public_html/example_folder). If you want to make a folder that has spaces in its name, put the name in quotation marks (e.g. mkdir «example folder»). As with other commands, you can create many directories by executing one command and listing the directories after the command (e.g. mkdir folder folder2 folder3).
To create new files use the touch command followed by a space and the file name including its extension type. For example:
touch example.txt
will create a text file example.txt in the current working directory. As with the mkdir command, you can use the full path to the new file; if there are spaces in the name, you should put the file name in quotations; you can create many files with one command.
Of course, the newly created files and directories will be empty.
Also Read
SSH — сетевой протокол, разработанный в 1995 году с целью установления стабильного и безопасного соединения с удаленными серверами. В наши дни технология получила наибольшее распространение при работе с VPS/VDS и выделенными серверами. Благодаря передаче данных по защищенным криптографическими методами каналам достигается беспрецедентно высокий уровень информационной безопасности.
Для дистанционного управления сервером, работы с текстовыми файлами, медиа-материалами и другими форматами администраторы используют специальные SSH-клиенты и ряд команд. Для чего нужны SSH-команды, какие они бывают и как ими пользоваться — разберем в этой статье.
Для лучшего понимания термина представим отвлеченную ситуацию: вы живете в Москве, а у вашего заказчика из Екатеринбурга «полетел» интернет-магазин, размещенный на локальном сервере. Вариантов дальнейшего развития ситуации может быть несколько:
- Вы всё бросайте и ближайшим рейсом вылетаете в другой город, чтобы решить проблему на месте.
- Или же отбрасываете в сторону эмоции, удаленно подключаетесь к серверу по SSH, находите и устраняете ошибки, не покидая удобного кресла в московском бизнес-центре.
Отправка команд и пакетов данных выполняется по защищенному SSH-протоколу.
Если с удаленным сервером или ПК удастся связаться таким образом, это можно сравнить с тем, словно вы подсоединили к нему свою клавиатуру. С этого момента можно запускать и выполнять на нём различные программы, проводить любые операции и действия, предусмотренные командной строкой.
Что можно делать с помощью SSH-команд
Команды по SSH можно использовать для:
- настройки серверного оборудования;
- программирования;
- установки WordPress, Bitrix, OpenCart и других CMS;
- выявления и устранения ошибок на сайте;
- запуска и остановки ПО, в том числе зависшего;
- копирования, вставки и перемещения файлов;
- настройки параметров безопасности ПК и файлов;
- перезагрузки сервера;
- удаления списка файлов, форматирования жесткого диска;
- дистанционного запуска файлов.
Конечно, этот список далеко не полный, но позволяет оценить открывающиеся возможности по удаленной работе с сервером.
Кратко о подключении и работе по SSH
Взаимодействие с виртуальными и выделенными серверами по SSH-протоколу выполняется в несколько этапов с помощью достаточно простых команд. Рассмотрим их более детально.
Запуск SSH-клиента
Если вы используйте MacOS, Linux или другие Unix-системы, значит, ничего скачивать и устанавливать не нужно — у этих ОС уже есть SSH-клиент (Terminal). Чтобы его запустить, нажмите Ctrl+Alt+T.
Далее для подключения к удаленному серверу введите в командную строку команду:
ssh root@11.44.45.66
Где:
- root — имя суперпользователя (чаще всего подключаются через этот аккаунту). Если вы используете другое имя пользователя, впишите его вместо рута.
- 11.44.45.66 — IP-адрес удаленного сервера.
По умолчанию для подключения по SSH-протоколу используется 22-й порт. Порт — это что-то типа номера рейсового автобуса, курсирующего по маршруту. И все вокруг уже знают, что «попасть» на остановку SSH можно на автобусе-порте под номером 22. Но, всё течет, всё меняется, и иногда на маршрут вместо привычного автобуса выходит, например, маршрутка №320.
Так и стандартный 22-й порт можно заменить на другой, что ещё больше обезопасит подключение. Для этого используется команда:
ssh -p номер_порта имя_пользователя@IP_сервера
У ОС Windows собственного SSH-клиента нет, его придется скачивать дополнительно. Одним из самых популярных вариантов является PuTTY с графической оболочкой, рассчитанной на более удобную и простую настройку параметров удаленного соединения.
SSH-соединение
Установление соединения выполняется в соответствии со следующим алгоритмом:
- SSH-клиент запрашивает подключение к серверу.
- Участники соединения проводят взаимную идентификацию, решают вопросы относительно используемых протоколов шифрования.
- Создается защищенный и стабильно функционирующий канал отправки команд.
В роли сервера в рамках SSH-подключения могут выступать в том числе удаленные компьютеры или ноутбуки.
Обмен ключами шифрования
После запуска SSH-клиента:
- Удаленный сервер направляет клиенту перечень протоколов шифрования, с которыми он готов работать.
- Если клиент также готов работать с этими протоколами, между ним и сервером криптографическими инструментами создается защищенное и надежное соединение. Внести в него изменения или взломать практически невозможно.
- Каждая сторона подключения получает специальный ключ, с помощью которого производится шифрование и дешифрование команд.
Если подключение прошло в штатном режиме, при первом сеансе связи сервер попросит подтвердить соединение:
Are you sure you want to continue connecting (yes/no)?
Завершаем операцию и вводим yes. Таким образом, мы выполнили уникальное подключение. В дальнейшем при изменении настроек и/или параметров работы соединения его участники поймут, что что-то идет не так и нужно бить тревогу.
В дальнейшем можно скопировать ключ на сервер, что позволит получать к нему доступ без ввода логина и пароля. Сделать это можно так:
ssh-copy-id -i путь_до_ключа root@IP_сервера
Фактически на этом всё. Защищенное соединение по SSH-протоколу установлено. Теперь вы можете без каких-либо проблем управлять удаленным сервером практически из любой точки планеты.
Root-доступ
По умолчанию при использовании SSH root-доступ разрешен, однако такой подход ставит под угрозу безопасность соединения. Поэтому после подключения рекомендуется раскомментировать строчку:
PermitRootLogin no
Дополнительно, чтобы разрешить доступ только определенным пользователям (одному или нескольким), воспользуйтесь следующей командой:
AllowUsers User1, User2, User3
Где User 1, 2, 3 — это пользователи, которым разрешен доступ.
Список SSH-команд и основы работы с командной строкой
Разберем основные команды и базовые навыки для работы по SSH-протоколу.
Командная строка, горячие клавиши и дополнительные символы
При подключении к удаленному серверу посредством SSH вы не увидите привычный для большинства пользователей рабочий стол или графический интерфейс с различными кнопками. Перед вами окажется черный экран с текстовыми строками. Именно он и называется командной строкой, которая является текстовым интерфейсом ПО.
Для взаимодействия с утилитой необходимо прописать определенную команду SSH в командную строку в виде текста, а программа выполнит поставленные перед ней задачи.
Помимо команд допускается использование дополнительных символов:
- ; — выполняет функцию разделителя, позволяющего прописывать и активировать сразу несколько команд:
cd ~/Documents; mkdir Pervaya_papka
- && — еще один разделитель. От предыдущего его отличает один важный момент — запуск команд, разделенных &&, осуществляется последовательно, при этом новая команда выполняется, только если успешно завершилась предыдущая:
cd ~/Documents && mkdir Pervaya_papka
- | — одновременно запускает две разные команды.
- ~ — символ является сокращенным написанием /home/имя_учетной_записи/.
Также упростить работу с SSH в консоли можно с помощью горячих клавиш:
- ↑ — открывает выполненную ранее команду;
- Ctrl+C — останавливает запущенный процесс;
- Ctrl+D — аналогична Ctrl+C, только интерпритируется как желание выйти из программы;
- Ctrl+A — отправляет курсор в начало текущей строки;
- Ctrl+E — отправляет курсор в конец текущей строки;
- Ctrl+W — удалить слово в текущей строчке;
- Ctrl+U — удалить всю строчку;
- Ctrl+Shift+C — копировать;
- Ctrl+Shift+V — вставить.
Базовые команды
Рассмотрим наиболее часто используемые SSH-команды:
- sudo — выдаёт права суперпользователя на использование последующей команды, если её нужно выполнить от имени администратора.
- Is — отображает содержимое вокруг вас, то есть все директории и файлы. При этом не обязательно переходить в интересующую папку, можно указать её путь:
ls ~/Desktop/adminvps
- cd — используется для перехода в любую выбранную папку:
cd ~/Desktop/ctomserver
- mkdir — позволяет создавать новую папку:
mkdir ~/Desktop/shared_hosting
- rm — команда для удаления папок и их содержимого (документов, медиа, фото) без возможности восстановления:
rm ~/Desktop/trash
- cp — применяется для создания копии указанного файла в выбранном каталоге:
cp ~/Documents/adminvps.txt /home/adminvps/Desktop/important
- mv — команда для перемещения файлов:
mv ~/Desktop/adminvps.txt ~/Documents
Также может использоваться для переименования файла:mv ~/Desktop/adminvps.txt adminvps-42.txt
- find — поиск файлов и папок в файловой системе по типу или названию. Например, такая команда будет искать папки с именем adminvps:
find -type d -name adminvps
- history — по умолчанию отображает 10 последних использованных инструментов или приложений. Чтобы изменить это количество любое число:
history 20
- clear — удаляет из текущей сессии консоли все ранее введенные данные, историю выполненных команд, а также содержимое открытых файлов.
Команды для работы с папками и файлами
- ls -lia — отобразит перечень содержимого каталого (всех файлов и папок, в том числе скрытых) в алфавитном порядке с указанием текущего размера.
- pwd — отобразит полный путь до текущей папки.
- cd / && du -hs * — полезная команда, если нужно быстро очистить забитый до отказа жесткий диск, используется для поиска директории с самым большим количеством файлов.
- df — показывает объем свободного дискового пространства сервера.
- cp -r Papka1 Papka 2 — скопирует первую папку вместе со всем содержимым во вторую директорию.
- du -sh — отобразит, сколько места занимает текущая папка и её подпапки.
- du -sh* — показывает, сколько весит каждый файл в текущей папке.
- touch — создаёт файл заданного формата в выбранной директории:
touch ~/Desktop/adminvps.txt
- fsck -y — автопроверка с последующим исправлением ошибок файловой системы.
Команды для работы с архивами
- tar cf Archive.tar adminvps.txt — создать архив в формате .tar, содержащий указанный файл.
- tar xf Archive.tar — выполнить распаковку архива.
- tar czf Archive.tar.gz adminvps.txt — создать архив с использованием сжатия Gzip.
- tar xzf Archive.tar.gz — распаковать такой архив.
- gzip adminvps.txt— сжать документ.
- zip -r Archive.zip /home/adminvps/Desktop/Papka/ — добавить в архив содержимое указанной директории.
- unzip — распакует архив (синтаксис строится по такому же принципу).
Команды для управления процессами
- ps -e — отображает на экране все активные в настоящий момент процессы.
- top — выводит запущенные пользователем процессы с информацией о нагрузке каждого на процессор, занимаемой оперативной памяти, времени работы. Чем-то похожа на диспетчер задач в Windows.
- kill PID — достаточно специфическая команда, позволяющая завершить текущий процесс с заданным PID-кодом (вместо PID вводится число).
- killall — позволяет завершить процесс, зная только его название. PID-код здесь не нужен.
- bg — выводит на экран перечень остановленных и фоновых задач.
- fg — отображает последние задачи.
Команды для работы с системной информацией
- reboot либо shutdown -r — выполняет перезагрузку сервера.
- free — выводит информацию об использовании оперативной памяти (сколько занято и сколько свободно);
- vmstat — отображает информацию о памяти, процессах, степени загрузки процессора и многом другом. Позволяет мониторить состояние и производительность сервера.
- uptime — функциональная и часто используемая системными администраторами команда, показывающая время беспрерывной работы сервера без перезагрузки.
- date — сегодняшняя дата.
- cal — команда выводит на экран календарь на текущий месяц.
- cat /proc/cpuinfo или meminfo — показывает характеристики процессоре или оперативной памяти соответственно.
Команды для работы с сетевыми настройками
- ifconfig — отображает текущие сетевые интерфейсы.
- ifconfig -a — позволяет получить доступ к полному списку интерфейсов, в том числе к тем, которые не активны в настоящий момент.
- ifconfig eth1 down — отключает интерфейс eth1.
- ifconfig eth1 up — включает интерфейс eth1.
- ping adminvps.ru — пинг указанного сайта, проверка соединения в сетях TCP/IP.
- dig adminvps.ru — отображает информацию о DNS-серверах сайта.
- wgеt адрес_ссылки — позволяет скачать файл по указанному адресу. Можно указывать сразу несколько URL-адресов.
- wgеt -c адрес_ссылки — продолжает остановленное скачивание.
Команды для разграничения прав доступа
- chown — нужная команда, которая позволяет назначить владельца для папок и любых файлов системе:
chown adminVPS (имя учетной записи) ~/Desktop/file.jpg
- chmod — используется для смены прав доступа к папке или файлу. Например, для назначения прав на чтение и перезапись файла:
chmod 777 ~/Desktop/photo22.png
Подводим итоги
С помощью SSH-команд вы можете удаленно работать с любыми файлами, настраивать сетевые функции и параметры работы сервера и многое другое. В любом случае, SSH-соединение отличается предельно простым и лаконичным интерфейсом и высокой безопасностью передачи любых видов данных.