From 65dfb21ce4bfd6c9b3d1628adeee0acfc423b2b5 Mon Sep 17 00:00:00 2001 From: Yaroslav Date: Sun, 12 Apr 2020 03:44:50 +0300 Subject: migrated all posts from 2018 --- content/weblog/2018-11-02_your-own-vpn/index.md | 541 +++++++++++++++++++++ .../weblog/2018-11-02_your-own-vpn/vpndialog.png | Bin 0 -> 22109 bytes .../2018-11-05_intro-to-linux-and-bash/index.md | 299 ++++++++++++ .../2018-11-05_intro-to-linux-and-bash/index.ru.md | 271 +++++++++++ .../index.md | 398 +++++++++++++++ .../index.ru.md | 404 +++++++++++++++ 6 files changed, 1913 insertions(+) create mode 100644 content/weblog/2018-11-02_your-own-vpn/index.md create mode 100644 content/weblog/2018-11-02_your-own-vpn/vpndialog.png create mode 100644 content/weblog/2018-11-05_intro-to-linux-and-bash/index.md create mode 100644 content/weblog/2018-11-05_intro-to-linux-and-bash/index.ru.md create mode 100644 content/weblog/2018-12-31_intro-to-linux-and-bash-pt2/index.md create mode 100644 content/weblog/2018-12-31_intro-to-linux-and-bash-pt2/index.ru.md (limited to 'content') diff --git a/content/weblog/2018-11-02_your-own-vpn/index.md b/content/weblog/2018-11-02_your-own-vpn/index.md new file mode 100644 index 0000000..e1140c6 --- /dev/null +++ b/content/weblog/2018-11-02_your-own-vpn/index.md @@ -0,0 +1,541 @@ ++++ +title = "Setting up your own VPN" +date = 2018-11-02T05:43:00Z ++++ + +There are many reasons why you would want to use a VPN, especially in this day +and age. The major one would be to securely and more privately surf the web, but +that is far from the only reason. I for one use it as well to be able to set up +a remote network with my desktop PC while I'm away from home, so that I can +access all of my files through SSH. There are a ton of other reasons as to why a +VPN could be useful, but that is not the topic of this post, rather I will be +writing here about to set up your own VPN (yes your own!) on a VPS, or any other +kind of linux server for that matter, using OpenVPN. + + + +I am in fact running my own VPN in the same server that I use to host this site +and other projects of mine. However due to certain circumstances I need to +migrate to another VPS, and so I decided to write this little guide to refresh +my memory on how to set up OpenVPN. + +Before we begin to set up our VPN, we need to install OpenVPN. I am using Debian +Stretch, so your install process may differ depending on your distro. + +```sh +# apt-get install openvpn easy-rsa +``` + +## Configuring OpenVPN + +After installing the necessary packages, we proceed to configure OpenVPN. First +we need to extract the sample OpenVPN server configuration file to /etc/openvpn + +```sh +# gunzip -c /usr/share/doc/openvpn/examples/sample-config-files/server.conf.gz > /etc/openvpn/server.conf +``` + +Next we proceed to edit it. + +```sh +# vim /etc/openvpn/server.conf +``` + +Inside we will make changes to basically use higher-level encryption, forward +web traffic to destination, prevent DNS leaking, and set up permissions. + +First we make sure that we are using 2048 bit-length keys instead of 1024. In my +case it was already set to 2048 bit by default, however, the first time that I +set up OpenVPN the default was 1024, so find this line + +``` +dh dh2048.pem +``` + +If instead you see "dh1024.pem" change it so that it is like in this example. + +Next we make sure to redirect all traffic to its proper destination. Find this +line + +``` +push "redirect-gateway def1 bypass-dhcp" +``` + +If it has a semicolon (;) at the beginning, remove it so that it is uncommented. + +Now we will tell OpenVPN to use OpenDNS for DNS resolution. This will help +prevent DNS requests from leaking outside of the VPN connection. + +Immediately after the previous setting, you will see a block of comments +followed by two commented lines + +``` +push "dhcp-option DNS 208.67.222.222" +push "dhcp-option DNS 208.67.220.220" +``` + +As previously, just remove the semicolon character from the beginning of the +line. + +Next we should comment the next line with a # or ; character. It is supposed to +be used as an extra security measure especially against DoS attacks, however, we +don't really need it + +``` +tls-auth ta.key 0 # This file is secret +``` + +If you really want to leave that on, you will need to generate it + +```sh +openvpn --genkey --secret ta.key +``` + +And last but not least in our server.conf file, we need to adjust permissions. +Find and uncomment these lines + +``` +user nobody +group nogroup +``` + +This way OpenVPN doesn't run as the root user. And we don't want any random +program wildly running as root, especially ones that are exposed to the +interwebz, no sir we don't ( ͡° ͜ʖ ͡°). + +After having made all the needed changes, just write them and close the editor. + +## Configuring network and firewall + +We need to enable packet forwarding, otherwise our traffic will not leave the +server. + +So that we don't have to reboot our server (let's leave all that rebooting to +windows systems), we can enable it on runtime by running the following command + +```sh +# sysctl net.ipv4.ip_forward=1 +``` + +However, we need to make this change permanent as well, so we open the following +file + +```sh +# vim /etc/sysctl.conf +``` + +And uncomment the following line by removing the hash character (#) at the +beginning of the line + +```sh +net.ipv4.ip_forward=1 +``` + +Save your changes and close the editor. + +Now we need to properly set up our firewall. Personally I use ufw as front-end +to iptables, since it is pretty easy to set up and use (as its name suggests, +uncomplicated firewall). If you don't have it installed yet, you can go ahead +and run + +```sh +# apt-get install ufw +``` + +By default ufw denies all incoming connections and allow all outgoing. Those +defaults are fine for my case, some might prefer to deny all outgoing +connections by default, some riskier guys (or gals) might prefer to allow all by +default (however, you wouldn't have unprotected fun time with just any partner, +now would you?( ͡° ͜ʖ ͡°)), however explaining all the details about ufw is out of +the scope of this tutorial, but I invite you use your duckduckgo-fu if you're +interested in learning more about ufw. + +Now, as ufw denies all incoming connections by default, we need to configure it +so that we don't get locked out of our server. If you use the standard ssh port, +just run the following command + +```sh +# ufw allow ssh +``` + +ufw comes with some presets for the most common services, so that in fact allows +connections from port 22 over tcp. If you, like me, prefer to use another port +for SSH, you need to specify the port and protocol manually, so, if say, you +connect to SSH over port 3333, you would run + +```sh +# ufw allow 3333/tcp +``` + +(Of course that is not the actual port I myself use for ssh, so don't even try +(That is however not an open invitation to try and guess my SSH port and hack +yourself into my server (seriously, please don't hack me ´༎ຶ ͜ʖ ༎ຶ ))). + +In this tutorial we will be using OpenVPN on port 1194 over UDP, so we must +allow it + +```sh +# ufw allow 1194/udp +``` + +Next we need to set ufw's forwarding policy, so we open the primary +configuration file + +```sh +# vim /etc/default/ufw +``` + +Modify the following line + +``` +DEFAULT_FORWARD_POLICY="DROP" +``` + +So that it looks like this + +``` +DEFAULT_FORWARD_POLICY="ACCEPT" +``` + +Save and exit. + +Open this file + +```sh +# vim /etc/ufw/before.rules +``` + +And add the rules for OpenVPN somewhere after the first block of comments + +``` +# START OPENVPN RULES +# NAT table rules +*nat +:POSTROUTING ACCEPT [0:0] +# Allow traffic from OpenVPN client to eth0 +-A POSTROUTING -s 10.8.0.0/8 -o eth0 -j MASQUERADE +COMMIT +# END OPENVPN RULES +``` + +Once more, save and exit. + +Now we can safely enable ufw + +```sh +# ufw enable +``` + +It will say something about disrupting current SSH connections, however, since +we just added the needed rules for SSH we can go ahead and answer y. + +## Configuring the Certificate Authority + +Now we are going to setup our own CA. This is crucial since OpenVPN encrypts +traffic (what use is a VPN that doesn't encrypt traffic?) + +First we need to copy the RSA generation scripts + +```sh +# cp -r /usr/share/easy-rsa/ /etc/openvpn +``` + +Next, we create a directory to house our keys + +```sh +# mkdir /etc/openvpn/easy-rsa/keys +``` + +Now we open the variables files + +```sh +# vim /etc/openvpn/easy-rsa/vars +``` + +And modify these lines according to our needs/preferences (they are not that +really important) + +```sh +# These are the default values for fields +# which will be placed in the certificate. +# Don't leave any of these fields blank. +export KEY_COUNTRY="US" +export KEY_PROVINCE="CA" +export KEY_CITY="SanFrancisco" +export KEY_ORG="Fort-Funston" +export KEY_EMAIL="me@myhost.mydomain" +export KEY_OU="MyOrganizationalUnit" +``` + +Then, in the same file, we need to change the name of the key. For simplicity's +sake we will use the name "server", since that's the name that OpenVPN uses to +reference the .key and .crt files by default. If you decide to use a different +name, you will need to modify the OpenVPN configuration files that reference the +aformentioned files. + +So change this + +```sh +# X509 Subject Field +export KEY_NAME="EasyRSA" +``` + +Into this + +```sh +# X509 Subject Field +export KEY_NAME="server" +``` + +Save and exit. + +Next we will use OpenSSL to generate the Diffie-Helman parameters. Grab a cup of +tea, take a seat, it might take some minutes + +```sh +# openssl dhparam -out /etc/openvpn/dh2048.pem 2048 +``` + +Now that our certificate is ready, it's time to generate a key. For that, we +first switch into the easy-rsa folder + +```sh +# cd /etc/openvpn/easy-rsa +``` + +Now we start setting up the CA. We first, need to initialize the Public Key +Infrastructure (PKI). For that we need to source the vars file + +```sh +# . ./var +``` + +If you get something like this in your output + +``` + No /etc/openvpn/easy-rsa/openssl.cnf file could be found + Further invocations will fail +``` + +Your .cnf might have a different name (due to differing versions of OpenSSL). +Just copy it like this + +```sh +# cp openssl-*.cnf openssl.cnf +``` + +And source the vars file one more time. + +After sourcing the vars file, it will give us a warning about removing some +files. Don't sweat it, it's fine, since right now that folder is empty. So we go +ahead and clear any and all keys that might interfere with out setup + +```sh +# ./clean-all +``` + +Finally, we can go ahead and build our CA using the following command + +```sh +# ./build-ca +``` + +We can skip through each prompt since we set up that info previously inside the +vars file. The CA is now ready to go. + +## Generating a certificate and key for our server + +Now we can proceed to actually setting up and launching OpenVPN. + +While still on the easy-rsa folder, we input this command + +```sh +# ./build-key-server server +``` + +server is the name of the key that we set up earlier in the vars file. We can go +ahead, and as earlier leave the defaults which we configured in the vars file. + +Upon reaching these prompts + +``` +A challenge password []: +An optional company name []: +``` + +Just press enter for both. We won't be needing them for this setup. + +The last two entries require a y answer + +``` +Sign the certificate? [y/n] +1 out of 1 certificate requests certified, commit? [y/n] +``` + +Now that our server certificate and key are ready, we need to copy them over to +/etc/openvpn, since that the directory in which OpenVPN will be looking for them + +```sh +# cp /etc/openvpn/easy-rsa/keys/{server.crt,server.key,ca.crt} /etc/openvpn +``` + +Now we can start OpenVPN + +```sh +# systemctl start openvpn +``` + +You can check if it launched correctly by running + +```sh +# systemctl status openvpn +``` + +It should say something like "Active: active (exited) since..." then, +congratulations! OpenVPN is now running in your server. If it says otherwise, +maybe something like "inactive (dead)...", you might to check the log file +"/var/log/syslog" for errors. + +If all is fine and dandy, you can enable the OpenVPN service so that it +automatically starts on each reboot + +```sh +# systemctl enable openvpn +``` + +## Generating certificates keys for clients + +Ideally each client that needs to connect to the VPN should have their own +unique certificate and key. Actually, by default, OpenVPN doesn't allow +simultaneous connections using the same certificate. + +Because of that you will need to repeat the steps in this section for each +device that you wish to allow to connect to your VPN, just changing the name +"desktop" below, to something different like "laptop" or "phone". This way you +can also later deactivate a specific device/client from accessing if needed be. + +I will start by building the key and certificate for my desktop computer, so I +will be using the "desktop" name as an example. We still should be in our +easy-rsa directory + +```sh +# ./build-key desktop +``` + +Once more, as with the server's cert and key, we will asked about some info +which we set on the vars, so we should skip all that by pressing enter +(including setting the passwords). Just press y both times at the end to +confirm. + +Now we need the sample profile to the keys folder. We need to change its +extension to ovpn, since that will be the file that OpenVPN will use on each +device to automatically set the profile to connect to our VPN server + +```sh +# cp /usr/share/doc/openvpn/examples/sample-config-files/client.conf /etc/openvpn/easy-rsa/keys/client.ovpn +``` + +The name of this file doesn't need to be related to our client's cert and key +filenames, we can actually name to something that will describe our VPN, since +that will be the name that OpenVPN will be pick up by default in our client +device for our profile. So you can name it "work.ovpn" or maybe something more +rich like "muhfreedumbs.ovpn" + +```sh +# mv keys/client.ovpn keys/muhfreedumbs.ovpn +``` + +After that we need to make some modifications to our ovpn file, so open it up + +```sh +# vim keys/muhfreedumbs.ovpn +``` + +And edit the line starting with remote with your server's ip address + +``` +remote your.ip.address.here 1194 +``` + +And if you chose to leave out the "ta.key" file protection option, don't forget +to comment this line + +``` +tls-auth ta.key 0 +``` + +Next we find these two lines and uncomment them (remove the ; character at the +beginning of each line) + +``` +user nobody +group nogroup +``` + +That's it. All that's left is to copy the client key and certificate, and the +ovpn file over to our device. First we need to copy them to another folder that +is available to our standard (non-root) user on the server for reading, since it +is not a good idea to have root login enabled on SSH. For example, we could +create a "vpnkeys" folder in our user's home directory + +```sh +$ mkdir /home/yaroslav/vpnkeys +``` + +And then copy the need files over to that folder + +```sh +# cp /etc/openvpn/easy-rsa/keys/{desktop.key,desktop.crt,muhfreedumbs.ovpn} /home/yaroslav/vpnkeys/ +``` + +There is one more file that we need to copy, the server's certificate + +```sh +# cp /etc/openvpn/ca.crt /home/yaroslav/vpnkeys/ +``` + +If you previously also left the secret "ta.key" file enabled and generated it, +you should copy that too. + +Note that the "ca.crt" and the ovpn files will be the same for all devices. If +you wish to create a new key/cert pair for another device/client, you DO NOT +need to create a new ovpn file, just run the "./build-key clientkeyname" command +as before and copy the same old ovpn and ca.crt file along with client key and +cert to your other device. + +Now we need to actually copy the keys to our device. You can use rsync or scp +for that. For example, I will be using scp to copy them to my Keys folder + +```sh +$ scp -P portno -r yaroslav@ipaddressorurl:/home/yaroslav/vpnkeys ~/Keys/ +``` + +If you need to use your VPN on your mobile device, just copy them first to your +computer through SSH, and then transfer them over to your mobile device. + +After transferring them to the device, you should delete the keys from the home +directory. + +## Conclusion + +Now that all is setup on the server side of things, you can go ahead and add +your VPN profile on your device. This process will vary greatly from device to +device. + +On most Linux distros/DEs, for example, you would go to your network manager, +and select "Configure VPN..." or something like that. Then, a window with a list +of (VPN) connections will appear, and you should be able to add your profile by +clicking on the plus (+) button. After another window like this should pop up + +![VPN dialog](vpndialog.png) + +You should select the option that says "Import a saved VPN configuration..." + +Note that the "openvpn" and "networkmanager-openvpn" packages should be +installed in your (client) system. + +Once you have connected to your VPN, you can head over to +[https://dnsleaktest.com/](https://dnsleaktest.com/) to check your connectivity. + +Now you can more safely and securely browse the interwebz, and be sure that no +third-party VPN company is logging your activity. diff --git a/content/weblog/2018-11-02_your-own-vpn/vpndialog.png b/content/weblog/2018-11-02_your-own-vpn/vpndialog.png new file mode 100644 index 0000000..6ba56cc Binary files /dev/null and b/content/weblog/2018-11-02_your-own-vpn/vpndialog.png differ diff --git a/content/weblog/2018-11-05_intro-to-linux-and-bash/index.md b/content/weblog/2018-11-05_intro-to-linux-and-bash/index.md new file mode 100644 index 0000000..28db692 --- /dev/null +++ b/content/weblog/2018-11-05_intro-to-linux-and-bash/index.md @@ -0,0 +1,299 @@ ++++ +title = "Intro to Linux and the Bash command line" +date = 2018-11-05T23:53:00Z ++++ + +Recently I decided to introduce a friend of mine to the wonderful world of +Linux, and like when someone moves to a completely new town, you have to help +that friend get around town and learn about how things work in this new town, +where are all the places of interest, etc. And so it is, in someway, when +someone decides to make the move to a new OS, they have to get used to the new +environment and make new habits, especially regarding Linux. Therefore, I +decided to write this tutorial for my friend, and anybody who decided to try +Linux, and want to learn to use more effectively, that is, with a higher level +of skill than an average user. + + + +Most probably you already know, but Linux is not actually the OS itself, but +rather the kernel that is used in conjuction with a collection of programs and +packages called GNU (insert here jokes and memes about GNU/Linux (or +GNU+Linux)), and there are many different distributions (over 9000) of said +GNU/Linux. + +If you're just about to install Linux, and haven't decided yet on a distro, here +I wrote a small list of distros that might start with: + +* Manjaro - I personally use this distro. This one has different releases, with + different Desktop Environments (or DEs), like KDE or GNOME. This is a "rolling + release", what that means, is that instead of the classical update to version + x.x of the OS system, updates for each package are being rolled out + constantly, and sepparatly for each package. That is, you get basically the + latest packages, with the latest updates, at the cost of maybe some stability. + It is quite easy to get installed, and get started with (If you choose an + official release like Manjaro KDE or Manjaro GNOME). +* Ubuntu - The most know Linux distribution. It is one of the most + "user-friendly" distros out there. It is more stable than Manjaro (although + not always, unless you're using the Long-Term Support versions). If you just + want to install an OS where everything just works, and is already configured + for you, and you don't want to choose from a list of DEs (or you don't know + what a Desktop Environment is), this will most probably suit your needs. +* Debian - One the most stable distributions. It is not as easy to install as + Ubuntu or Manjaro due to large ammount of choice given during installation, + but it's not really hard to either. Actually, Ubuntu is derived from Debian. + You must probably will have to configure it to your needs and likings + (personally, I dislike the default settings of GNOME), but if you want real + stability, and distro that has been around almost as long as the kernel + itself, then this might be the distro for you. One downside of Debian, is that + because of its focus on stability, many packages on the main (stable) + branch/version are quite old/outdated. Another con of Debian, is that it + doesn't include "non-free" packages in the main repository (that is, there are + no proprietary packages by default), so if need a proprietary program or + package, like nvidia's drivers, you will have to add the corresponding + repositories by yourself. +* Fedora - It is similar to Ubuntu regarding stability and ease of use (i.e. + quite simple to use). I can't say much about Fedora, because I haven't used it + that much myself, but it is a very popular distribution. It has the same con + as Debian, in that it doesn't include "non-free" software in its main + repository. + +If you found "Desktop Environment" to be a unfamiliar term, in a nutshell, it is +the collection of programs and packages that present with the Graphical User +Interface for interaction with the system. How your OS/distribution is going to +look like doesn't depend as much on the distro itself, as on the DE that you +choose to install or comes with the distro. + +Do you have Linux installed? Excellent, now we can get started. + +## File structure + +If you are used to working with Windows systems, the the first thing that you +might notice is the difference in how files are handled/organized. In Windows, +because of its DOS legacy, drive letters are used to represent different drives, +partitions and file systems. In Linux, like in other Unix-like systems (e.g. +macOS, BSD) this differs somewhat. + +In Linux, everything is a file, including the devices that are connected to your +computer. From your keyboard (which is a read-only file) to your drives. +Directories are also files. + +Different disks or drives are mounted in a specific directory, and from this +directory, every file from that drive will be accessible. You can mount and +unmount drives yourself, but if you installed a distro with any of the most +popular desktop environments, then there's nothing to worry about, the system is +going to take care of mounting your pendrive for you, and creating a shortcut in +your file explorer and/or desktop each time you insert it. + +Linux has what is called a "root" directory + +``` +/ +``` + +In there are the files and subdirectories in your system are located, including +drives mounted in a specific subdirectory as mentioned before. + +Each user in Linux has its own "home" directory. Inside your home directory your +personal documents/files and subdirectories are going to be stored. All the home +directories of each user are usually going to be stored inside the "/home/" +directory. For example, for user "user", their home directory is going to be + +``` +/home/user +``` + +However, you can also move to your home directory by using the symbol ~. For +example, in your terminal, if you input + +```sh +$ cd ~ +``` + +You are going to be taken to your home directory (e.g. "/home/user/"). + +## The command-line - Bash + +Arguably the most useful program in Linux and any *nix system is the terminal. +Yes, maybe the average user won't have to use it, but it is the most flexible, +effective and useful instrument in your computer. A lot of work can be done +faster and more effectively in the terminal, rather than in a GUI. Obviously, it +is faster to learn to use a graphical interface, than a text-based or +command-line one, however, once you learn to properly use the terminal, you will +be able to use computer more efficiently than ever. + +Your command-line, if you haven't changed any defaults, will most probably look +something like this + +```sh +user@host:~$ +``` + +The first part before the "@" symbol, is the user with whom you have logged in. +After the "@" symbol is the "hostname" of your machine, i.e. the name of your +computer in a network. + +After the semicolon ":", the directory in which you are currently located is +going to be displayed. In our case, the "~" symbol is displayed, meaning that we +are inside our home directory. If you wish to see the full absolute path in +which you are located, you can input the command "pwd" + +```sh +user@host:~$ pwd +/home/user +user@host:~$ +``` + +The dollar "$" symbol, tells us that we are logged in as "normal" user. In Linux +and all *nix systems, there is a so called "super user", or just the "root" user +for short. Normal users don't have full access to all of the files in the +system, including other users' files. The root user has full access to all +system files. When you are logged in as the root user, the dollar "$" symbol is +going to be replaced by the hash "#" symbol. + +However, we will be talking about the root user and permissions another time. + +I can't tell you exactly how to open the terminal, as it is different in each +distro and desktop environment. You will have to look for the link that says +"Terminal" in your programs' menu, with the icon of a terminal on it. + +To be able to start working in the terminal, we'll need to become acquainted +with some of the main commands used for navigating. + +### Navigation in the terminal + +There is one more thing that needs to be taken into consideration when working +with Linux and Unix-like systems, and that is, case-sensitivity. *nix systems +are case-sensitive, in contrast to Windows ones, which aren't. What that means, +is that, if on Windows, files "README.TXT" and "readme.txt" are the same file, +in Linux and Unix they are completely different files. + +To move around directories, we use the "cd" (or change directory) command, +followed by the name, or path of the directory. The directory can be absolute or +relative. + +A relative path, is, for example, the name of a subdirectory inside the +directory in which we are currently located. In other words, the path relative +to where we are located. + +An absolute path, is the path relative to the root directory. + +For example, if we want to move to the "Documents" directory inside +"/home/user/", and we are already at "/home/user/", the we can just type the +following + +```sh +user@host:~$ cd Documents +user@host:~/Documents$ +``` + +If we wanted to move to that same directory from another location in the system, +we would type + +```sh +user@host:/var$ cd /home/user/Documents +user@host:~/Documents$ +``` + +To move one folder up, we write "..". Example + +```sh +user@host:~/Documents$ cd .. +user@host:~$ +``` + +The two dots "..", means the root directory of the current subdirectory. One dot +"." means the current directory. + +There is one more command, that will aid you in navigating - ls. This command +outputs a list of files and directories in the current location + +```sh +user@host:~/Documents$ ls +Books todo.txt picture.png +``` + +This command also accepts arguments and flags. For example, to list hidden files +as well, add the "-a" flag + +```sh +user@host:~/Documents$ ls -a +Books .secret todo.txt picture.png +``` + +Hidden files in Linux start with a dot (e.g., hidden directory ".secret"). + +There is also the "-l" parameter, which shows us a list of the contents with +additional information, such as, permissions (more on that in the next part), +amount of files inside a directory, owner of the file (user and group), size on +disk, datetime of creation/modification, and the name of the file. Example + +```sh +user@host:~/Documents$ ls -l +drwxr-xr-x 2 user user 4.0K Jul 18 04:20 Books +-rw-r--r-- 1 user user 350 Jul 18 04:20 todo.txt +-rw-r--r-- 1 user user 1.2M Jul 18 04:20 picture.png +``` + +You can mix flags as well, + +```sh +user@host:~/Documents$ ls -al +drwxr-xr-x 2 user user 4.0K Jul 18 04:20 Books +drwxr-xr-x 5 user user 4.0K Jul 18 04:20 .secret +-rw-r--r-- 1 user user 350 Jul 18 04:20 todo.txt +-rw-r--r-- 1 user user 1.2M Jul 18 04:20 picture.png +``` + +You can also take a look at what is inside a directory without having to move to +it first, by passing along as the last argument the name/path of said directory, +for example + +```sh +user@host:~/Documents$ ls -l Books +drwxr-xr-x 12 user user 4.0K Jul 18 04:20 Lessons +-rw-r--r-- 1 user user 2.3M Jul 18 04:20 Crime and Punishment.pdf +``` + +### Shortcuts + +Before we conclude the first part of this tutorial, I would like to mention some +useful "shortcuts" in bash. + +The first one is command history. Each time you input a command into the +terminal, it saves it in a history file. You can move around your command +history by using the up and down arrows. Let's say you want to repeat the last +command you used, instead of typing it all over again, you could just hit the up +arrow one time, maybe modify it a bit, and then press enter to input it. If you +want to use an older command, you can press the up arrow multiple times, and if +you missed the command you needed, you can go forward in your history by +pressing the down arrow. + +There is one more useful thing in Bash - Tab completion. When you press the +"Tab" key, bash will try to autocomplete the command for you. + +Let's say, for example, that you are in the root directory and you want to move +to "/home/user/". you can start typing "cd h", then press "Tab", so you now have +"cd home/", now type "u", press "Tab" one more time, and now you have "cd +home/user/". + +If there are multiple possible options to be autocompleted, then on the first +hit of the "Tab" key you are not going to get anything. If you don't get +anything it could also mean that there are nothing to autocomplete. In the first +case, if you press "Tab" twice, bash is going to output a list of possibilities, +for example + +```sh +user@host:~$ cd Do +Documents/ Downloads/ +user@host:~$ cd Do +``` + +In this case, we can type the next letter, for example "cd Doc", and press "Tab" +one more time, and we are going to get "cd Documents/". However, if you didn't +get anything on pressing "Tab" twice, it means that is nothing to autocomplete. + +It can be a little be hard to understand at first how "Tab completion" works, +but the best way to understand it, by trying it yourself. + +That is all for now, in the next part I am going to talk more about working on +the terminal. diff --git a/content/weblog/2018-11-05_intro-to-linux-and-bash/index.ru.md b/content/weblog/2018-11-05_intro-to-linux-and-bash/index.ru.md new file mode 100644 index 0000000..e9ba17d --- /dev/null +++ b/content/weblog/2018-11-05_intro-to-linux-and-bash/index.ru.md @@ -0,0 +1,271 @@ ++++ +title = "Intro to Linux and the Bash command line" +date = 2018-11-05T23:53:00Z ++++ + +Недавно я решил познакомить друга с великолепным миром Линукса, и как например, +человек переезжает в совсем новый город, его нужно познакомить с городом, как +передвигаться по городу, где все нужные заведения и т.д. В принципе и также +когда человек переходит на новую ОС, ему нужно привыкнуть к новой среде, +создавать новые привычки, особенно когда это касается мира линукса. Собственно +этот туториал я пишу для моего друга и любого другого человека который +заинтересован Линуксом, но хотят научится использовать его более эффективно, +т.е. высше уровня рядового пользователя. + + + +Скорее всего вам уже известно, но Линукс на самом деле сам по себе не ОС, а ядро +которое используется совместно с набором комонентов и программ GNU (вставьте +здесь шутки и мемы про GNU/Linux (или GNU+Linux)), и есть несколько вариантов, +или точнее - дистрибутивов, так называемого GNU/Linux. + +Если только собираетесь установить Линукс и еще не решились какой дистрибутив +выбрать, здесь маленткий, который может помочь вам выбрать: + +* Manjaro - Лично я пользуюсь этим дистрибутивом. У него есть несколько вариации + с разными рабочими средами, например KDE или GNOME. Это дистрибутив "rolling + release", что означает то, что у него будет более новые пакеты чем у + классических дистро, в замен меньшей стабильности системы. Его довольно легко + установить и использовать (если выбрать что-то вроде KDE или GNOME). +* Ubuntu - Самый известный дистрибутив. Является один из самых легких в + использовании. Более стабильный чем Manjaro (хоть и не всегда). Если вы просто + хотите установить ОС в которой уже все настроена и не хотите выбирать рабочую + среду (или вы не знаете что такое рабочая среда), скорее всего этот дистро для + вас. +* Debian - Один из самых стабильных дистро. Его не так легко установить как + Ubuntu или Manjaro, но все же не сложно. Собственно Ubuntu разработан на + основе Debian'а. Его скорее всего придется настроить под себя (лично меня не + нравятся дефолтные настройки GNOME'а), но если вы хотите стабильный, + провереный дистрибутив, то он для вас. Один минус для некоторых - поумолчанию + не подключены репозитории с "несвободным" софтом, придется подключить самому + если нуждаетесь в проприетарном софте. +* Fedora - По стабильностью и сложности установки/пользования похож на Ubuntu + (то есть довольный просто). У него такой же минус как и у Debian - отсуствия + "несвобоного" софта в главном репозиторий. + +Если при чтения списка вам словосочетание "рабочая среда" оказалась незнакомой, +то грубо говоря, это набор программ которые предоставляют вам графический +интерфейс для взаимодейстмия с системой. Как выглядит ОС не так сильно зависит +от дистро, в основном оно зависит от рабочей среды. + +Установили Линукс? Отлично, можем начать. + +## Файловая структура + +Если вы привыкли работать с Windows, то есть некоторые моменты, то первое что вы +заметите это то, что файловая структура выглядит немного иначе. Windows, из-за +наследства MS-DOS, использует буквы для обозначения дисков, томов и файловых +систем. В Линукс, как и в других Unix-подобных системах (например macOS, BSD) +это немного иначе. + +В Линуксе всё являтся файлом, в том числе и устройства подключенных к вашему +компьютеру. От клавиатуры до накопителя. Папки (или директории) тоже файлы. + +Разные диски или накопители монтируются в определеной папке, и в этой папке +будут размещатся файлы данного накопителя. Монтировать и демонтировать диски, +флэшки и тд можно самому, но нечего боятся, если вы установили какой-нибудь из +самых популярных дистро, то система сделать это для вас автоматический, и +создаст ярлык в браузере файлов или на рабочем столе. + +В Линуксе есть корневая папка + +``` +/ +``` + +Внутри нее все файлы и поддиректории вашей системы. + +В Линуксе, у каждого пользователя есть своя "домашняя папка". В вашей домашней +папки будут размещаться ваши файлы, документы. Домашняя папка пользователя +"user", например, будет распологатся здесь + +``` +/home/user +``` + +Но вы можете перейти к этой папке используя символ ~. Например, если в консоле +вы введете + +```sh +$ cd ~ +``` + +То это комманда вас переместит в вашую домашнюю папку (например, /home/user). + +## Терминал - Bash + +Самая полезная программа в линуксе, это скорее всего терминал. Да, рядовой +пользователь может и без нее жить, но это довольно гибкий и полезный инструмент. +Очень часто задачу на самом деле проще и быстрее реализовать в текстовой среде +чем в графической. Очевидно быстрее научится пользоватся графической средой, но +после того как вы научитесь пользоватся текстовой средой (терминал), вы сможете +работать более эффективно. + +Пример того как может выглядить ваша коммандная строка + +```sh +user@host:~$ +``` + +Первая часть - пользователь через которого вы зашли в систему. Вторая после +символа "@" - hostname, или название вашего устройства в сети. + +Вслед за ":" - директория в котором вы находитесь в данный момент. В этом случае +символ "~" указывает что мы находемся в домашнем каталоге нашего пользователя. +Чтобы посмотреть абсолютный путь, мы можем ввести комманду "pwd". + +```sh +user@host:~$ pwd +/home/user +user@host:~$ +``` + +Символ "$" указывает на то что мы сейчас работаем через обычного пользователя. В +Линуксе и во всех *nix системах, есть такая вещь как "супер пользователь", или +root пользователь. У обычных пользователей нет полный доступ к важным файлам +системы, или к файлам других пользователей. У root, доступ есть на всю систему. +Когда вы авторизованные через root, символ "$" меняется на "#". + +Но о правах и о root пользователе, попозже поговорим. + +Чтобы открыть терминал, достаточно зайти в меню программ/приложений и нажать на +его иконку или названия. Не могу объяснить подробнее где располагается ярлык +терминала, поскольку оно будет отличатся в зависимо от дистрибутива. + +Для того, чтобы начать работать в терминале, необходимо познакомится с основными +коммандами, начиная с коммандами для навигации. + +### Навигация в терминале + +Еще один момент, который стоит учесть при работе с Линуксом и *nix системами, +это то, что реестр учитывается. Если в Windows'е файл README.TXT и readme.txt +один и то же самый, то в Линуксе и Unix-подобных системах это разные файлы. + +Для перемещения по директориям, мы пришем в коммандой строке "cd <путь>". Путь +может быть относительным или абсолютным. + +Относительный путь, это, например, название папки которая находится внутри той +директории где мы находимся. Или иными словами, путь относительно того где мы +находимся. + +Абсолютный путь, это путь относительно корневой директории (или root на английском). + +Например, если мы хотим переместится в каталог "Documents" внутри /home/user/, и +мы уже в /home/user/, то мы можем просто ввести + +```sh +user@host:~$ cd Documents +user@host:~/Documents$ +``` + +А если бы нам надо было перейти на эту же папку с совершено другого каталога, то +нам бы пришлось ввести + +```sh +user@host:/var$ cd /home/user/Documents +user@host:~/Documents$ +``` + +Чтобы перейти на корневого каталога данной директории мы используем две точки +"..". Например + +```sh +user@host:~/Documents$ cd .. +user@host:~$ +``` + +".." означает корневой каталог данной директории. А также есть "." который +означает данная директория. + +Есть еще одна комманда, которая поможет вам при навигации в коммандой строке - +ls. Это комманда позволяет увидет содержимое данной директорий + +```sh +user@host:~/Documents$ ls +Books todo.txt picture.png +``` + +Она также принимает параметры и аргументы, например, чтобы увидеть скрытые +файлы, добавьте параметр "-a" + +```sh +user@host:~/Documents$ ls -a +Books .secret todo.txt picture.png +``` + +Скрытые файлы и каталоги в Линуксе начинаются с точкой (например, скрытый +каталог ".secret"). + +Также есть параметр "-l" который показывает содержимое в списке с +допольнительной информация, такой как разрещения (больше о них в следующей +части), количество файлов в каталоге, владелец файла (пользователь и группа), +размер, дата создания/модификации, и название самого файла. Например + +```sh +user@host:~/Documents$ ls -l +drwxr-xr-x 2 user user 4.0K Jul 18 04:20 Books +-rw-r--r-- 1 user user 350 Jul 18 04:20 todo.txt +-rw-r--r-- 1 user user 1.2M Jul 18 04:20 picture.png +``` + +Также параметры можно совмещать + +```sh +user@host:~/Documents$ ls -al +drwxr-xr-x 2 user user 4.0K Jul 18 04:20 Books +drwxr-xr-x 5 user user 4.0K Jul 18 04:20 .secret +-rw-r--r-- 1 user user 350 Jul 18 04:20 todo.txt +-rw-r--r-- 1 user user 1.2M Jul 18 04:20 picture.png +``` + +Можно смотреть содержимое другого каталога не переходя на него, передавая его +название/путь в качестве последнего аргумента, например + +```sh +user@host:~/Documents$ ls -l Books +drwxr-xr-x 12 user user 4.0K Jul 18 04:20 Lessons +-rw-r--r-- 1 user user 2.3M Jul 18 04:20 Crime and Punishment.pdf +``` + +### Шорткаты + +Перед тем как завершить первую часть этого туториала, хотелось бы написать про +несколько "шорткатов" при работе в bash'е. + +Первое это перемещение по истории коммандов. Каждый раз когда вы вводите +комманду в терминале, она сохраняется в истории. Вы можете перемещаться по +истории комманд терминала используя стрелки вверх и вниз. Чтобы последнюю +комманду повторить, вы можете один раз нажать на стрелку вверх, а затем можно ее +дописать или переписать и нажать клавишу ввода. Чтобы повторить более старые +комманды, вы можете несколько раз нажать на стрелку вверх до нужной комманды, а +стрелку вниз если пропустили нужную комманду. + +Еще есть очень полезная штука в баше - автозполнение. При нажатии на клавишу +"Таб" баш попытается заполнить для вас комманду. + +Например, допустим вы находитесь в корневом каталоге, и вы хотите перейти в путь +"/home/user/". Вы можете начать печатать "cd h" нажать на "Таб" и у вас +получится "cd home/" затем дописать букву "u" и снова нажать на клавишу "Таб" и +в итоге у вас получится "cd home/user/". + +Если будут несколько возможных вариантов автодополнения, то при одном нажатии +ничего не получится. Это значит, что либо нет такого каталога, либо есть +несколько возможных вариантов для автозаполнение. Во втором случае можно два +раза подряд нажать на клавишу "Таб" и баш вам покажет все возможные варианты, +например + +```sh +user@host:~$ cd Do +Documents/ Downloads/ +user@host:~$ cd Do +``` + +В таком случае мы, например, можем допечатать "cd Doc" и снова нажать на "Таб" и +у нас получится "cd Documents/". Однако, если при двойном нажатие ничего не +выводится, значит что вариантов для автозаполнения. + +В начале может показаться немного не понятно как система автозаполнения +работает, поэтому следует самому попробовать воспользоватся ей на практике +самому. + +На этом пока все, в следующей части расскажу побольше о работе в терминале. diff --git a/content/weblog/2018-12-31_intro-to-linux-and-bash-pt2/index.md b/content/weblog/2018-12-31_intro-to-linux-and-bash-pt2/index.md new file mode 100644 index 0000000..5739e06 --- /dev/null +++ b/content/weblog/2018-12-31_intro-to-linux-and-bash-pt2/index.md @@ -0,0 +1,398 @@ ++++ +title = "Intro to Linux and the Bash command line, pt II" +date = 2018-12-31T09:20:00Z ++++ + +So the year is coming to an end, and I didn't follow up on the first part of +these mini tutorial/guide/introduction. Might as well end the year on a good +note and write at least one post this last month. + + + +In this part I will be writing about some more aspects of Linux and Unix-like +systems and tools that will come in handy when using the terminal. All or most +of these tools are a standard part of Linux and Unix/Unix-like systems. + +## File manipulation + +I didn't get into detail in the previous part of this guide on the file +manipulation side of things. However it is a crucial part of any computer +system, after all they wouldn't be as useful as they are if you couldn't create, +edit and delete files. + +### Create files + +Usually, the way you would go about creating and editing files is by using the +corresponding programs. Like for example, vim to create and edit text files. +However, there's also a utility to create blank files called touch. + +You can make a blank file by writing touch followed by the path of the file you +wish to create, like this + +```sh +user@host:~$ touch example.txt +``` + +Now we have an empty file at "/home/user/example.txt". Although I kind of lied +when I said that this command is for making blank files. In reality, what it +does is check if such file exists, if it does, it modifies the date and time of +access and modification, otherwise it makes a new empty file, like in our case. +Most of the time you won't really need this command, since you would actually be +creating files through programs or means, though it does come in handy +sometimes. + +### Create directories + +Now on to something more interesting, making directories. This one is quite +simple, and the command for that is mkdir. For example + +```sh +user@host:~$ mkdir foo +``` + +In this case we have created a new folder called "foo" in "/home/user/". But +remember that we are passing paths here, which can be relative or absolute (if +you don't know or remember what this means, check the first part of this guide). +In our case we were using a relative path, with just the name of the directory +to create. + +If we were to indicate an absolute path like "/home/user/foo" we would need to +make sure that directories "home" and "user" already exist. However, there's a +useful argument we can pass to mkdir to make parent directories if needed, -p + +```sh +user@host:~$ mkdir -p /tmp/foo/bar +``` + +In this case, if directory "foo" doesn't exist, mkdir will make it for us along +with "bar" inside it. + +### Moving and renaming + +This one is pretty simple, and both actions are handled by the same command, mv, +which is short for move. + +If you want to rename a file or directory, simply "move" it to the same +destination directory with a new/different name, for example + +```sh +user@host:~$ mv untitled titled +``` + +If you want to move it to a different location, just indicate that path as the +second argument. Remember that we are using paths here, and we use either +absolute or relative paths + +```sh +user@host:~$ mv titled Documents/titled +``` + +### Copying + +Copying files is similar to moving them, except that the command is different, +cp + +```sh +user@host:~$ cp titled Documents/titled2 +``` + +However, copying directories is different. To copy directories you have to use a +special flag, the -r flag. This flag means that the operation ought to be +recursive, that is to copy every file and subdirectory in that directory along +with the directory (and files in those subdirectories and files the +subdirectories of the subdirectories and... yeah recursion, you get it) to the +destination path. So we would do something like this + +```sh +user@host:~$ cp -r dir dir-copy +``` + +### Removing + +Removing files is pretty simple, just use rm followed by the path of the file, +for example + +```sh +user@host:~$ rm title +``` + +However, removing directories is a little bit trickier. One option would be to +use the command rmdir, however, the directory has to be empty before you can +remove it. + +The second option, is to use the same command as we used with files, but passing +it the -r flag so that it removes files recursively, similar to what we did with +the copy (cp) command. Do watch out, as it will remove the directory along with +everything that is in it. + +So to remove a directory and everything in it, we input something like this + +```sh +user@host:~$ rm -r dir +``` + +This command also has another flag to forcefully remove files without prompting, +the -f flag. This might be useful when you are removing files recursively and +there might be some special files, like hidden files (the ones with a dot as the +first character) and you don't want to be prompted for each and everyone of +them. + +Thread REALLY carefully when using this command though, especially if you are +issuing it as root. You don't wanna issue a "sudo rm -rf /" and end up with a +borked system and lost files. Unless you are some kind of sadist or something. + +An example of when it might be useful, is when you need to delete a git +repository from your computer, since it contains a lot of special hidden files +which git uses to keep track of your commits and other stuff. So to remove it, +we do + +```sh +user@host:~$ rm -rf somerepo +``` + +### Permissions + +The Unix or Unix-like user and permissions systems, is a robust system for +managing what particular users can do with certain files and directories. This +allows to create a secure environment, especially when there are multiple users +using one computer. + +Every file has three types of permissions which dictate what can be done with +it. Each permission is represented by a single letter + +* r - read: the user can read/view the file. +* w - write: the user can write/modify (this includes deleting) the file. +* x - execute: the file can be run or executed by the user, if it is a program + or script. + +There are as well three different sets of people the permissions and ownership +might apply to. These are + +* u - user/owner: the one user that owns the file. Usually it is the user that + created the file, but ownership can be modified. +* g - group: every file has a group it belongs to. The group can be a one user + group (every user has their own one-user group), or a common group with + multiple users. +* o - others: everybody else who is not either in the group or the owner. + +If you read the first part of this guide you might remember that I mentioned +using the command "ls -l" to list the contents of the directory with details +about the files, including permissions + +```sh +user@host:~/Documents$ ls -l +drwxr-xr-x 2 user user 4.0K Jul 18 04:20 Books +-rwxr-xr-- 1 user group 350 Jul 18 04:20 run.py +-rw-r--r-- 1 user user 1.2M Jul 18 04:20 picture.png +``` + +As mentioned in the first part, the first ten characters of a row of the output +is what tells us about the permissions of the given file in that row. + +The first character in that sequence tells us if it is a normal file, or a +directory. If it has a d, it is a directory (duh), if it has a dash, it is a +normal file. It can be another letter, like an l for a symbolic link (a topic +for another day). + +The next 9 characters are divided in subsequences of three letters, each for a +set of people. The first three characters after the file type one are the +permissions for the owner, the next three are for the group, and the last three +for others. + +In each of this subset of three characters, the permissions are in the order of +read, write, and execute. So a letter means that that said set of users have +said permission, and its absence means the lack of that permission. + +Let's take for example the "run.py" file. By the information there we can see +that it is a normal file (no d (that's what she said)), its owner (user) can +read, write and even execute it; the group users (in group group) can read and +execute it, but not write to it; and the others can just take a look at its +contents. + +You might have noticed that directories tend to have the "x" part of the +permissions, however, this means something a little bit different on directories +than on files. It doesn't mean that you can execute but rather that you can +"search it", or in other words, access files inside of it. Because having the +"read" permission on a directory only means that you can take a look at what +files are inside of it, and write that you can put files inside the directory. + +### Changing permissions + +There is a really useful command that allows us to change permissions on files, +chmod. It is short for change file mode bits. + +To change the permissions on the file you input chmod followed by the +permissions and the path of the file. There are two ways of setting the +permissions, the easy and long one using letters, and the short but not as easy +way with octal "permission bits". We'll take a look at the easy one first. + +The easier way is made up of three parts + +* Who - user/owner, group, others or all (u, g, o, or a) +* Revoke or grant, "+" to grant, "-" to revoke +* The permission we are setting - read, write or execute (r, w, or x) + +So let's suppose we have a script we want to set the execute permission for so +that any user in the computer can execute it. + +```shh +user@host:~/Documents/stuff$ ls -l +-rw-r--r-- 1 user group 420 April 20 6:59 script.sh +user@host:~/Documents/stuff$ chmod a+x script.sh +-rwxr-xr-x 1 user group 420 April 20 6:59 script.sh +``` + +As we can see, after executing the command, every user on the computer now has +execute permission on the script. Now let's say that we want to revoke read +permissions for everybody except for the owner (user), we could execute o-r and +then g-r, but we can also combine them, like so + +```sh +user@host:~/Documents/stuff$ chmod go-r script.sh +-rwx--x--x 1 user group 420 April 20 6:59 script.sh +``` + +Now onto the short way. This one's a bit harder to remember as you have to have +some understanding of binary. Basically the way it works is that you set the +permissions by passing three octal numbers (i.e., 0-7) that each represent the +permission bits for each set of people (user/owner, group, others). + +As it is we have three possible permissions (read, write and execute) and 2^3 +just so happens to be 8 (possible combinations), that's why it is in octal. +Here's a table to help you out + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OctalBinary
0001
1001
2010
3011
4100
5101
6110
7111
+ +Basically what this means, is that when we have a 1, said permission is granted, +when it is 0, it is not. So for example, 6 means that read and write have been +granted, but not execute, because 6 => 110 => rw-. + +So let's say for example that we want to set the permissions of file so that the +owner can read, write, and execute, the group can read and execute, and others +can only execute. It would look something like this + +```sh +user@host:~/Documents/stuff$ chmod 751 script.sh +user@host:~/Documents/stuff$ ls -l +-rwxr-x--x 1 user group 420 April 20 6:59 script.sh +``` + +If you are changing the permissions of a directory, the permissions will apply +only to the directory itself and not to the files and subdirectories inside of +it, unless you use the recursive flag -R (note that in the case of chmod and +chown it is a capital R). + +### Changing ownership + +Changing the owner of a file is easier than changing permissions, since less +variables are involved. To change owner we use the chown command, for example, +change the user that owns a file + +```sh +user@host:~/.logs$ ls -l +-rw-r--r-- 1 root root 69 April 20 6:59 some.log +user@host:~/.logs$ sudo chown user some.log +user@host:~/.logs$ ls -l +-rw-r--r-- 1 user root 69 April 20 6:59 some.log +``` + +As the file doesn't belong to the same user initially, we need to use sudo +elevate our permissions to "super user". Note that in order to be able to use +sudo or "elevate your permissions" your user needs to be either in the sudoers +file or in other distros in the "wheel" group, or both. I won't go into details +on how to do that, since most probably your user is already in the sudoers file, +and a quick search on the internet will give you the information needed. + +Now let's say that you wanted to change both the user and group that file +belongs to, we would do like this + +```sh +user@host:~/.logs$ ls -l +-rw-r--r-- 1 root root 69 April 20 6:59 some.log +user@host:~/.logs$ sudo chown user:group some.log +user@host:~/.logs$ ls -l +-rw-r--r-- 1 user group 69 April 20 6:59 some.log +``` + +Just as with chmod, if you want to change ownership recursively in a directory, +you need to use the -R flag. + +## Epilogue/Some tips + +I forgot to mention in the previous part how to write paths with spaces. You +cannot write paths with spaces just like that, since spaces are treated as the +separator between arguments. + +There are two ways of writings paths and filenames (and other arguments) with +spaces. One is to put the argument between quotation marks, like for example + +```sh +user@host:~/Documents$ rm "Shopping List.txt" +``` + +Another is to use an escape character, i.e. just put a backslash (\) before the +space, like this + +```sh +user@host:~/Documents$ rm Shopping\ List.txt +``` + +One more thing that I wanted to mention is the man(ual) pages. Basically all +Linux distros come with man pages. + +You don't always have to resort to the internet if you don't remember how to use +a command, like what flags a command accepts, what are the order of the +arguments, etc. You might not have internet one day, and you might to resort to +good ol' offline resources, and the man pages are a good one. + +Besides, it is sometimes faster and easier to not have to leave the terminal to +look up the information. + +To read the man(ual) pages of a command, input "man" followed by the name of the +command, e.g. "chmod", and it will provide you with almost all the information +that you need. + +You can use vim keys (hjkl), or the arrow keys to scroll. Type / to search +for that word, and afterwards press n to find the next found item. + +This is all for this part. Happy 2019! diff --git a/content/weblog/2018-12-31_intro-to-linux-and-bash-pt2/index.ru.md b/content/weblog/2018-12-31_intro-to-linux-and-bash-pt2/index.ru.md new file mode 100644 index 0000000..34ad9d9 --- /dev/null +++ b/content/weblog/2018-12-31_intro-to-linux-and-bash-pt2/index.ru.md @@ -0,0 +1,404 @@ ++++ +title = "Intro to Linux and the Bash command line, pt II" +date = 2018-12-31T09:20:00Z ++++ + +И так, год подходит к концу, и я так еще не написал вторую часть туториала про +Bash и Linux. Надо бы написать хотя бы один пост в этом, последнем месяце года. + + + +В этой части, я расскажу чуть больше про инструменты и команды в Linux и +Unix-подобных системах, которые вам пригодятся при работе в терминале. Все или +большинство из этих программ являются частью основного набора программ и утилит +большинства бистрибутивов Linux и Unix/Unix-подобных систем. + +## Работа с файлами + +В предыдущей части я стал объяснять подробно как работать с файлами. Однако, +возможность манипулировать файлы является очень полезным и важным функционалом +компьютерных систем. + +### Создать файл + +Обычно, если хотим создать файл, мы используем определенную программу специально +предназначена для создания и редактирования определенного вида файлов. Например, +vim для редактирования и записи текстовых файлов. Однако есть утилита которая +позволяет создавать пустые файлы - touch. + +Вы можете создать пустой файл введя touch и последовательно название или путь +файла который вы хотите создать, например + +```sh +user@host:~$ touch example.txt +``` + +А теперь у нас пустой файл в "/home/user/example.txt". Но, я немного соврал, +когда сказал что данная команда для того чтобы создавать пустые файлы. На самом +деле, она сначала проверяет наличия файла, затем, если он существует, она +редактировает его даты и время доступа и редактирования, иначе он создает пустой +файл, как в данном случае. Очень редко когда данная команда на самом деле +понадобится, поскольку в большинство случаях сами программы для редактирования +файлов могут также их создавать. Тем не менее бывают случаи когда она может +пригодится. + +### Создать директорий + +Сейчас у нас будет что-то поинтереснее, как создать директорий. Создавать +директории довольно просто, команда - mkdir. Например + +```sh +user@host:~$ mkdir foo +``` + +Мы только что создали директорий "foo" в "/home/user/". Не забудьте что мы +всегда передаем путь файла, будь они относительными или абсолютными (если вы не +помните что это значит, прочитайте первую часть). В данном случае, мы используем +относительный путь содержающий только название директория. + +Если бы мы использовали абсолютный путь, он выглядел бы таким образом - +"/home/user/foo". Нам бы пришлось убедиться в том что директории "home" и "user" +существуют. Однако, существует очень подезный флажок, которые мы можем передать +команде, чтобы она создавала родительские директории при необходимости - -p + +```sh +user@host:~$ mkdir -p /tmp/foo/bar +``` + +Если директории "tmp" и/или "foo" не существуют, он их автоматический сделает, +вместе с "bar" внутри их. + +### Перемещение и переименования + +Это довольно просто, и обе действия можно выполнить одной командой - mv, что +происходит с английского move. + +Если вам необходимо переименовать файл или директорий, переместите его в тот же +самый директорий, с новым/другим названием, например + +```sh +user@host:~$ mv untitled titled +``` + +А вот если потребуется переместить в другую локацию, просто укажите путь новой +локации в качестве второго аргумента. Не забудьте что оба аргумента являются +путями, либо относительными либо абсолютными + +```sh +user@host:~$ mv titled Documents/titled +``` + +### Копировать + +Копирование похоже на перемещения, отличие просто в названии команды - cp. + +```sh +user@host:~$ cp titled Documents/titled2 +``` + +Однако, копирование директории отличается немного от копирования файлов. Чтобы +копировать директории, нужно использовать флаг -r. Он указывает что операция +должна быть рекурсивной, то есть, нужно скопировать каждый файл и поддиректорию +внутри директории (и файлы внутри этих поддиректории и в поддиректории +поддиректории и... ну то есть, рекурсия) в указанный путь. То есть что-то похоже +на это + +```sh +user@host:~$ cp -r dir dir-copy +``` + +### Удалить + +Удалять файлы довольно просто, достаточно ввести rm а затем путь файла + +```sh +user@host:~$ rm title +``` + +Однако, чтобы удалять директории не так просто. Один способ - использовать +команду rmdir, но она только работает на пустых директориях. + +Второй вариант, использовать ту же команду что и для файлов, но используя флаг +-r чтобы удалить файлы рекурсивно, также как и с командой cp. Будьте +внимательные при использовании этой команды, ибо она удаляет все файлы внутри +директории, вместе с директорией. + +Итак, чтобы удалить директорию и все содержимое, нам понадобиться ввести +следующую команду + +```sh +user@host:~$ rm -r dir +``` + +У этой команды есть еще один флаг, чтобы принудительно удалить файлы без +вопросов - флаг -f. Этот аргумент может пригодится, например, когда нужно +удалить сразу несколько файлов, и среди них есть специльные файлы, как скрытые +файлы (те, у которых точка перед названием) и вам не хочется подтвердить +действие перед каждым файлом. + +Следует быть ОЧЕНЬ осторожным перед тем как использовать этот флаг, особенно +если вы собираетесь ввести команду под root пользователем. Поверьте, вам будет +очень неприятно если вы введете например "sudo rm -rf /" и у вас полетят +полностью система и файлы. Если вы не садист, конечно. + +Пример ситуации когда данное сочетание флагов с командой rm может пригодится +это, когда вам необходимо удалить репозиторий git, поскольку в них содержатся +множество специальных скрытых файлов, которые git использует затем чтобы следить +за коммитами и прочее. Пример использования команды + +```sh +user@host:~$ rm -rf somerepo +``` + +### Контроль доступа + +В Unix и Unix-подобных системах существует довольно прочная система для контроля +прав доступа. Она позволяет определять полномочия определеных пользователей или +групп пользователей над определенными файлам, создавая безопасную среду для +компьютеров с множество пользователями. + +У каждого файла три вида прав доступа, которые определяют что можно с ними +делать. Каждое право обозначается одной буквой английского алфавита + +* r - чтение: пользователь имеет право читать данный файл. +* w - запись: пользователь может писать/редактровать данный файл (включая + возможность его удалять). +* x - выполнение: файл может быть выполнен пользователем, если он является + программой или скриптом. + +Так же существует три разных наборов человек к которым могут относится права +доступа + +* u - пользователь/владелец: пользователь, которому принадлежит файл. Обычно это + тот же самый пользователь, который создал файл, но владелца можно поменять. +* g - группа: каждый принадлежит определенной группе пользователей. Это может + быть группа одного пользователя (у каждого пользователя есть своя + однопользовательская группа), или общая группа. +* o - другие: Все остальные кто не являются владелцем или ну состоит в группе. + +Если вы читали первую часть туториала, вы наверное помните что я рассказывал про +команду "ls -l" чтобы посмотреть дополнительную информацию о файлах, включая +права доступа + +```sh +user@host:~/Documents$ ls -l +drwxr-xr-x 2 user user 4.0K Jul 18 04:20 Books +-rwxr-xr-- 1 user group 350 Jul 18 04:20 run.py +-rw-r--r-- 1 user user 1.2M Jul 18 04:20 picture.png +``` + +Первые десять символов в каждой строке - права доступа для файла в данной +строке. + +Первый символ в данном сочетаний символов определяет является ли файл обычным +файлом или другим видом. Если первым символом является буква d, то это +директория, если там просто черточка (тире/дефис), то это обычный файл. Там +также может быть другая буква, как например l для ссылок, но это уже не входит в +рамках данного поста. + +Следующие 9 символов разделяются в свое время в сочетание из трех символов, +каждое для определенного набора пользователей. Первые три символа после символа +вида файла это права для владелца, следующие три для группы, и последние три для +отсальных. + +В каждом из этих сочетании из трех букв, права доступа в порядке чтение, запись, +выполнение. Наличие буквы означает что у данного набора пользвателей данно это +право, отсуствие значит нет такого права для данного набора пользоваетелей. + +Возьмем в качестве примера файл "run.py". Исходя из информации на экране мы +можем определить что это обычный файл (нет буквы d), владелец (user) имеет право +читать, записывать и выполнять его; группа пользователей (в группе group) имеет +право на чтение и выполнения, но не записи; и остальные только могут его читать. + +Наверное вы заметили что почти всегда у директории присуствует право на +выполнение (буква x), однако это означает что-то немножко иное в отличие от +файлов. Буква "x" у директориях означает что есть право на вход в директорию и +есть доступ к файлам внутри директории. Право на чтения директории всего лишь +означает что можно смотреть на то какие файлы содержатся в директории, и право +на запись означает что есть то чтобы записывать файла внутри директории. + +### Изменить права + +Существует очень полезная команда которая позволяет менять права на доступ +файлов - chmod. + +Чтобы изменить права на файле, необходимо ввести chmod и затем права и путь +файла. Есть два способа чтобы менять права, легкий но более долгий способ +используя буквы, и более быстрый но не совсем легкий используя восмеричный код. +Начнем с более легкого. + +Более легкий способ состоит из трех частей + +* Кто - пользователь/владелец, группа, остальные или все (u, g, o, или a) +* Дать или отменить право, "+" чтобы дать, "-" чтобы отменить +* Право которое мы меняем - чтение, запись или испольнение (r, w, или x) + +Допустим у нас есть скрипт для которого мы хотим дать право на запуск для всех +пользователей. + +```sh +user@host:~/Documents/stuff$ ls -l +-rw-r--r-- 1 user group 420 April 20 6:59 script.sh +user@host:~/Documents/stuff$ chmod a+x script.sh +-rwxr-xr-x 1 user group 420 April 20 6:59 script.sh +``` + +Как можно заметить, после запуска команды все пользователи компьютера имеют +право на выполнения скрипта. А теперь допустим что мы передумали и хотим +отменить право выполнения для всех пользователей кроме владелца, мы могли бы +ввести o-r и затем g-r, но мы можем также совмещать следующим образом + +```sh +user@host:~/Documents/stuff$ chmod go-r script.sh +-rwx--x--x 1 user group 420 April 20 6:59 script.sh +``` + +А теперь пора выучить быстрый способ. Его сложнее запомнить, поскольку еще +нужны базовые понимания двоичной системы счисления. Грубо говоря, оно работает +подовая три цифры в восьмеричной системе счисления (то есть 0-7) каждая из +которых обозначает бит права для каждого набора пользователей +(пользователь/владелец, группа, другие). + +Получается у нас три возможные права (чтение, запись и выполнение) и 2^3 нам +дает 8 возможных сочетании прав, и вот почему у нас восьмеричная система. +Следующая таблица поможет определить отношение нужной цифры для определенного +сочетания прав + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Восьмеричная системаДвоичная система
0001
1001
2010
3011
4100
5101
6110
7111
+ +Зная как переводятся цифры в двоичную становится намного проще знать к какой +комбинации прав она относится, ибо каждая цифра в сочетании трех бинарных цифр +относится к одному виду прав в выше указанному порядке (r, w, x). Если у нас +единица (1) это означает что есть данное право, а ноль (0) означает его +отсуствие. И так, например, 6 означает что у нас есть право на чтение и запись, +поскольку 6 = 110 = rw-. + +Допустим что мы хотим поменять права доступа к файлу таким образом чтобы +владелец мог читать, записывать и выполнять; группа имела право на чтения и +выполнения; и остальные могли только выполнять. Для этого мы ввели что-то +подобное + +```sh +user@host:~/Documents/stuff$ chmod 751 script.sh +user@host:~/Documents/stuff$ ls -l +-rwxr-x--x 1 user group 420 April 20 6:59 script.sh +``` + +Если вы меняете права доступа директория, новые права будут изменены только для +самой директории, не включая файлы и поддиректории внутри. Чтобы также изменить +права для всех файлов внутри директории, необходимо использовать флаг рекурсии - +-R (обратите внимания на то что, в chmod флаг рекурсии обозначается большой +буквой R в отличие от cp или rm). + +### Поменять владелца + +Менять владельца файла проще чем менять права. Чтобы поменять владельца необходимо +использовать команду chown. Например, допустим мы хотим поменять пользователя, +которого владеет файлом + +```sh +user@host:~/.logs$ ls -l +-rw-r--r-- 1 root root 69 April 20 6:59 some.log +user@host:~/.logs$ sudo chown user some.log +user@host:~/.logs$ ls -l +-rw-r--r-- 1 user root 69 April 20 6:59 some.log +``` + +Поскольку файл не принадлежал тому же самому владельцу с которого мы выполняем +команды, нам необходимо выполнить команду через sudo чтобы повысить наши +права. Чтобы иметь возможность повышать права вашего пользователя, необходимо +чтобы ваш пользователь состоял в файле "sudoers" и/или в группе "wheel" зависимо +от дистрибутива/ОС. В большинство случаев (если вы пользуетесь +"домашним/дестктопным" дистро) у вас уже будут права на sudo, в любом случае +быстрый поиск в интернете поможет вам найти информацию о том как поменять +настройки прав в вашем дистрибутиве/ОС. + +А теперь допустим что вы хотели поменять и пользователя и группу которому +принадлежит файл, в таком случае мы бы ввели следующее + +```sh +user@host:~/.logs$ ls -l +-rw-r--r-- 1 root root 69 April 20 6:59 some.log +user@host:~/.logs$ sudo chown user:group some.log +user@host:~/.logs$ ls -l +-rw-r--r-- 1 user group 69 April 20 6:59 some.log +``` + +Также как и с chmod, если вам необходимо поменять владелца рекурсивной в +директории, вам нужно использовать флаг -R. + +## Эпилог/Советы + +В предыдущей части я забыл написать о том как ввести пути с пробедами. Нельзя +просто так печатать пути с пробелами, ибо пробел означает переход к следующему +аргументу. + +Есть два способа печатать пути, названия файлов и другие аргументы с пробелами. +Первый способ - кавычки. Например + +```sh +user@host:~/Documents$ rm "Shopping List.txt" +``` + +Второй - экранирования символа с помощью символа "\" перед пробелом. Например + +```sh +user@host:~/Documents$ rm Shopping\ List.txt +``` + +Еще одно о чем я хотел рассказать - мануалы (man). Почти (если не все) +дистрибутивы Линукса имеют мануалы. + +Не всегда необходимо обращаться к интернету если вы забыли как пользоваться +определнной командой. Если вы однажды оказались без интернета и вы хотите +узнать побольше об одной команде, man отличный оффлайн ресурс. + +Не говоря уже о том что проще и быстрее делать все сразу с терминала не +переключаясь к браузеру чтобы искать нужную информацию. + +Чтобы прочитать мануал определенной команды, введите man и затем название +команды. Например "man chmod". + +Вы можете пользоваться клавишами vim (hjkl) для перемещения. Введите /<термин> +чтобы искать этот термин, а затем нажмите на n чтобы найти следующее совпадение. + +Это все на данный момент. С новым 2019-м годом! -- cgit v1.2.3