Статьи

    Рецепты RegEx

    Переменные Формула RegEx, заключенная в скобки, становится переменной. Содержимое переменной можно при поиске/замене вставить в результат при помощи её номера. Так, например, если вам нужно найти в html-файле все нумерованные главы, которые заключены в тэги <p> и <strong> и заменить теги на <h1>, то содержимое строки поиска будет следующим: <p><strong>(Глава \d+)</strong></p> Код \d — это любая одна цифра от 0 до 9, а + обозначает последовательность цифр любой длины. Это может быть и 5, и 124, и 1000000.

    Desktop environment on Ubuntu Server

    Install Xfce Desktop on Ubuntu Server Xfce is a Fully featured lightweight desktop environment that requires less memory and processing power, therefore I will recommend to use Xfce as the graphical user interface for your Ubuntu server 18.04/16.04. To install Xfce desktop on Ubuntu server, Run the following commands: $ apt-get update $ apt-get install lightdm xfce4 After the installation is finished, Create a new file named lightdm.conf in /etc/lightdm directory:

    How to change ownership

    Changing File Permissions $ chmod NNN filename How to Change the Owner of a File $ chown username filename How to Change Group Ownership of a File $ chgrp group filename

    How to check open ports in Linux using the CLI

    The procedure to monitor and display open ports in Linux is as follows: Open a Linux terminal application Use ss command to display all open TCP and UDP ports in Linux. Another option is to use the netstat command to list all ports in Linux. Apart from ss/netstat one can use the lsof command to list open files and ports on Linux based system. Finally, one can use nmap command to check TCP and UDP ports too.

    How to find zombie process?

    To kill a zombie (process) you have to kill its parent process (just like real zombies!), but the question was how to find it. Find the zombie (The question answered this part): a@SERVER:~$ ps aux | grep -e '[zZ]' What you get is Zombies and anything else with a Z in it, so you will also get the grep: USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND usera 13572 0.

    How To Secure Apache with Let's Encrypt on Ubuntu 20.04

    Introduction Let’s Encrypt is a Certificate Authority (CA) that facilitates obtaining and installing free TLS/SSL certificates, thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this guide, we’ll use Certbot to obtain a free SSL certificate for Apache on Ubuntu 20.

    How To Set or Change Timezone on Ubuntu 20.04

    Using the correct timezone is essential for many systems related tasks and processes. For example, the cron daemon uses the system’s timezone for executing cron jobs, and the timestamps in the log files are based on the same system’s timezone. On Ubuntu, the system’s timezone is set during the install, but it can be easily changed at a later time. This article describes how to set or change the timezone on Ubuntu 20.

    How to Start Linux Command in Background and Detach Process in Terminal

    Помни про tmux и screen! In this guide, we shall bring to light a simple yet important concept in process handling in a Linux system, that is how to completely detach a process from its controlling terminal. When a process is associated with a terminal, two problems might occur: your controlling terminal is filled with so much output data and error/diagnostic messages. in the event that the terminal is closed, the process together with its child processes will be terminated.

    How to use the journalctl Linux command

    Learn about the Linux command which can help you troubleshoot why apps and services fail to start. Boot entries If you want to list out only the boot process and how services fared during the booting of the system, issue the command: $ journalctl -b Say you want to see the journal output of the previous boot. If the current boot is 0, the previous boot would be -1. That command would be:

    Mac terminal commands

    Update software If you want to update your Mac remotely via SSH, or you don’t want to go through the steps to open System Preferences and perform the updates, your Mac can also be updated directly through the Terminal. To do this, I’ll utilize a command called softwareupdate. This command, when passed two options, both downloads and installs the updates. Open Terminal and type the following command to check for, download, and install any available updates for your system:

    Run Docker without Docker Desktop on macOS

    Preface Docker Inc. recently announced that Docker Desktop would no longer remain a free product for large organizations. It will remain free for personal and open-source projects and for organizations smaller than a certain size. Usually this is not a cause for concern as a company with revenue greater than $10 million would be able to afford Docker Desktop’s $5 per user/month starter pricing. This post does in no way discourages organizations in paying and I believe that Docker Inc.

    Show Linux Version

    You need to use the following two commands or files: uname command – Print kernel and system information. lsb_release command – Show Linux distribution-specific information. /proc/version file – Get running Linux kernel information. How to check linux kernel version number? Open a shell prompt (or a terminal) and type the following command to see your current Linux kernel version: $ uname -r Sample outputs: 2.6.32-23-generic-pae Or type the following command:

    SUDO без пароля

    sudo visudo запуск редактора параметров sudo myuser ALL=(ALL) NOPASSWD: ALL для пользователя, или %sudo ALL=(ALL) NOPASSWD: ALL для группы.

    Горячие клавиши для Терминала на Mac (macOS)

    Если вы пользуетесь на своем Mac программой «Терминал» для запуска тех или иных команд, то наверняка знаете насколько удобным может стать использование сочетания клавиш. Это значительно ускоряет работу. Комбинации клавиш позволяют настроить окно, переходить ко вкладкам, а уж команды редактирования, поиска текста и его выделения известны многим. Мы приведем довольно большой список сочетаний клавиш, которые помогут вам лучше работать с «Терминалом». Окно терминала и его вкладки Благодаря этим сочетаниям клавиш вы сможете перемещаться по терминалу и выполнять определенные действия с самим окном и его вкладками.

    Как проверить скорость в локальной сети

    Чтобы проверить скорость в локальной сети, можно передать с одного компьютера на другой большой объем информации. Замерив время передачи, легко определить и скорость. Однако эффективнее для измерения скорости воспользоваться специальной программой. Инструкция Для проведения теста скорости ЛС с помощью iperf понадобятся: 2 компьютера (один сервер, другой клиент), подключенные к сети и с укзанными IP-адресами; сама, iperf (Linux, Windows версии) на каждом компьютере, причем, они должны пинговться; для тестирования определенного порта (TCP или UDP), необходимо открыть доступ на этот порт.

    Краткая шпаргалка по tmux (менеджеру терминалов)

    tmux — это менеджер терминалов, к которому удобно подключаться и отключаться, не теряя при этом процессы и историю. Как screen, только лучше (в первую очередь потому, что использует модель клиент—сервер). Вашему вниманию предлагается минималистическая шпаргалка, позволяющая быстро начать использовать tmux, а уж тонкую настройку, продвинутые команды и бесконечные хот-кеи желающие найдут, набрав man tmux. Очень хороший способ запустить tmux: tmux attach || tmux new — делая так, вы сперва пытаетесь подключиться к уже существующему серверу tmux, если он существует; если такого ещё нет — создаёте новый.

    Настраиваем Debian/Ubuntu как Mac хранилище

    Уже давно являюсь пользователем продукции Apple. Старенький макбук полностью справляется с теми задачами, что на него возлагаются. В основном конечно развлекательные. Но в последнее время стало не хватать места на 40 гиговом жестком диске. И вот наконец у меня зачесались руки настроить свой домашний сервер, как хранилище. Некоторое время работал по ftp, но это было не удобно. Было принято решение настроить наконец Appletalk, не зря же он есть и заодно приручить к нему TimeMachine:-)

    Размеры папок и дисков в Linux. Команды df и du

    Размеры папок и дисков в Linux. Команды df и du Рассмотрим, как используя команды df и du просматривать свободное место на дисках и размеры папок в Linux. Свободное место на диске (df) Для просмотра свободного и занятого места на разделах диска в Linux можно воспользоваться командой df. Первым делом можно просто ввести команду df без каких-либо аргументов и получить занятое и свободное место на дисках. Но по умолчанию вывод команды не очень наглядный — например, размеры выводятся в КБайтах (1К-блоках).

    Удивительная командная строка macOS

    Общие команды Составленный список команд оболочки и инструментов, специфичных для macOS. “Вам не нужно знать все. Вам просто нужно знать, где найти это, когда это необходимо.” (Джон Браннер) Личная заметка Не вся информация, представленная в этом списке, всегда актуальна для последних версий операционных систем. Apple действительно поддерживает устройства в продолжительный период времени, но их покупка также обходится дорого. В настоящее время у меня нет возможности заменить свой ноутбук MacBook Pro Mid-2014 15", и он не поддерживает версию Monterey и выше.

    Шпаргалка по распаковке tar архивов

    Для распаковки tar-архивов через командную строку используется утилита tar. Полезно знать, что архивы в формате tar имеют расширение файлов .tar. Также в Linux распространены архивы, которые имеют дополнительное сжатие другими программами. Например, архивы .tar.bz2, .tar.gz и другие. Все эти архивы можно распаковать утилитой tar. Распаковка tar Для распаковки архива в формате .tar в текущую директорию выполните команду: tar xvf archive.tar Распаковка tar.bz2, tar.bzip2, tbz2, tb2, tbz tar xvjf archive.tar.bz2 Распаковка tar.

    Console commands

    How do I find the width & height of a terminal window? echo -e "lines\ncols"|tput -S Размеры папок и дисков в Linux. Команды df и du Рассмотрим, как используя команды df и du просматривать свободное место на дисках и размеры папок в Linux. Свободное место на диске (df) Для просмотра свободного и занятого места на разделах диска в Linux можно воспользоваться командой df. Первым делом можно просто ввести команду df без каких-либо аргументов и получить занятое и свободное место на дисках.

    Desktop environment on Ubuntu Server

    Install Xfce Desktop on Ubuntu Server Xfce is a Fully featured lightweight desktop environment that requires less memory and processing power, therefore I will recommend to use Xfce as the graphical user interface for your Ubuntu server 18.04/16.04. To install Xfce desktop on Ubuntu server, Run the following commands: apt-get update apt-get install lightdm xfce4 After the installation is finished, Create a new file named lightdm.conf in /etc/lightdm directory: sudo nano /etc/lightdm/lightdm.

    Find Out RAM Speed, Make, Form Factor, Type and Other Information

    You need to use the dmidecode command: sudo dmidecode --type memory Result is # dmidecode 3.2 Getting SMBIOS data from sysfs. SMBIOS 2.7 present. Handle 0x0007, DMI type 16, 23 bytes Physical Memory Array Location: System Board Or Motherboard Use: System Memory Error Correction Type: None Maximum Capacity: 32 GB Error Information Handle: Not Provided Number Of Devices: 4 Handle 0x0040, DMI type 17, 34 bytes Memory Device Array Handle: 0x0007 Error Information Handle: Not Provided Total Width: 64 bits Data Width: 64 bits Size: 4096 MB Form Factor: DIMM Set: None Locator: ChannelB-DIMM1 Bank Locator: BANK 3 Type: DDR3 Type Detail: Synchronous Speed: 1600 MT/s Manufacturer: Kingston Serial Number: A3265F9A Asset Tag: 9876543210 Part Number: 9905430-400.

    GRUB2

    Ни в коем случае не стоит редактировать grub.cfg Достаточно удалить раздел с windows, после чего в консоли sudo update-grub Если надо изменить порядок загрузки или удалить винду из списка — редактируем /etc/default/grub: `GRUB_DEFAULT=n` — пункт меню по умолчанию (начинается с 0), `GRUB_DEFAULT=saved` — загружаем последний использовавшийся загрузчик, `GRUB_DEFAULT="ххххххх"` — точное название пункта меню, например «Windows 7 (loader) (on /dev/sda1)» `GRUB_DISABLE_OS_PROBER="true"` — не добавлять в загрузчик windows и прочие системы (скрипт /etc/grub.

    ZSH

    Install and set up zsh as default With the package manager of your choice, e.g. sudo apt install zsh or brew install zsh for macOS Verify installation by running zsh --version. Expected result: zsh 5.0.8 or more recent. Make it your default shell: chsh -s $(which zsh) Log out and log back in again to use your new default shell. Test that it worked with echo $SHELL. Expected result: /bin/zsh or similar.