Основы программирования Shell




Перевод текста «Веб-серверы. Основы Shell»

 

Веб-серверы

Веб-сервер представляет собой компьютерную систему, основной функцией которой является обработка запросов с использованием HTTP (протокол передачи гипертекста). HTTP считается основным сетевым протоколом для распространения любого рода информации в World Wide Web (всемирная информационная сеть). Этот термин можно применять по отношению как ко всей системе, так и к определённому программному обеспечению, которое принимает и контролирует HTTP-запросы.

Чаще всего Вы будете встречаться с веб-серверами, оснащёнными кроссплатформенным программным обеспечением Apache (Апачи).

В основные задачи веб-сервера входит хранение, обработка и предоставление веб-страниц клиентам. Связь между клиентом и сервером, как уже было упомянуто ранее, осуществляется через HTTP. Чаще всего доставляемые клиентам страницы представляют собой документы, созданные на основе HTML (язык гипертекстовой разметки), которые в дополнение к текстовому контенту могут содержать изображения, таблицы стилей и различные сценарии.

Пользователь, в большинстве своём представленный веб-браузером или поисковым роботом, инициирует процесс обмена сообщениями, посылая запрос на определенный ресурс с использованием HTTP. Сервер, в свою очередь, отвечает содержимым этого ресурса или уведомляет пользователя об ошибке в случае, если доступ к данному ресурсу невозможен. Обычно ресурс представляет собой реальный файл, расположенный на вторичном хранилище сервера. Стоит, однако, отметить, что это зависит от конфигурации самого сервера.

Несмотря на то, что основной задачей сервера является предоставление информации, полная реализация функций HTTP также включает получение разнообразной информации от клиентов. Эта функция реализуется в процессе отправки веб-форм и загрузки файлов.

Используя активные серверные страницы (Active Server Pages, ASP), предварительный обработчик гипертекста (PHP) или другие языки сценариев, многие веб-серверы поддерживают сценарии на стороне сервера. Это означает, что инструкции касательно работы веб-сервера записываются в отдельных файлах, а фактическое серверное ПО при этом остается неизменным. Обычно эта функция используется в процессе динамической генерации HTML-документов, суть которой заключается в извлечении или изменении информации баз данных. Документы, сгенерированные статически, как правило, намного быстрее и проще кэшировать, но в то же время динамический контент в них отсутствует.

Стоит отметить, что веб-серверы используются не только для обслуживания запросов в интернете. Их присутствие можно найти в таких устройствах, как принтеры, маршрутизаторы и веб-камеры. Зачастую они могут быть настроены на обслуживание определенной локальной сети. Веб-сервер может использоваться как часть системы для мониторинга или администрирования какого-либо устройства. В таких случаях на компьютере клиента не должно устанавливаться дополнительное программное обеспечение, поскольку для осуществления данной функции требуется только веб-браузер (который теперь включен в большинство операционных систем).

 

Основы программирования Shell

Структура файловой системы

Как вы уже могли заметить, структуры файловых систем Linux и Windows несколько различаются. Поначалу подобное расположение каталогов может показаться вам нелогичным и даже странным, и Вы будете путаться в местах расположения программ, символов, файлов конфигурации и других необходимых для эффективной работы элементов.

Это далеко не полный список всех директорий Linux, однако в него включены самые необходимые места вашей файловой системы.

</>

Корневой каталог представляет собой отправную точка всей структуры файловой системы, и именно отсюда стартует система Linux. Любой другой файл или директория в вашей системе так или иначе находятся в корневом каталоге. Обычно корневой каталог содержит только подкаталоги, поэтому не следует хранить отдельные файлы в каталоге как таковом.

Не путайте корневой каталог с учетной записью пользователя root и его паролем или домашним каталогом пользователя root (/root).

</ boot>

Как следует из названия, это место, где Linux хранит информацию, необходимую для загрузки операционной системы. Здесь хранится ядро ​​Linux. Если вы сделаете запрос касательно просмотра содержимого каталога / boot, Вы увидите файл с именем vmlinuz, который и будет содержать в себе ядро.

</ etc>

В этом каталоге хранятся файлы конфигурации для системы Linux. Большинство из них являются текстовыми файлами и Вы с легкостью можете редактировать их вручную. Обратите особое внимание на следующие файлы:

/etc/inittab

Это текстовый файл, описывающий процессы, которые запускаются при загрузке системы и во время нормальной работы сервера. Здесь Вы можете определить, хотите ли вы, чтобы X Window System запускалась автоматически и настроить что происходит при нажатии Ctrl + Alt + Del.

/etc/Fstab

Этот файл содержит описательную информацию о различных файловых системах и возможных местах установки, таких как дискеты, диски CD-ROM и многие другие.

/etc/passwd

Файл, содержащий информацию для каждой учетной записи пользователя. Именно этот файл отвечает за определение пользователя.

</bin, /usr/bin>

Эти два каталога содержат множество системных программ (двоичных файлов, а следовательно, и имя каталога). В каталоге /bin находятся наиболее важные программы, которыми оперирует система, например, команды shell, ls, grep и другие необходимые утилиты. /usr bin в свою очередь содержит приложения для пользователей системы. Однако в некоторых случаях совершенно неважно поместите Вы программу в каталог /bin или /usr/bin.

</sbin, /usr/sbin>

В этих каталогах хранится большинство программ системного администрирования. Зачастую Вам придется запускать эти программы из-под пользователя root.

</usr>

Этот каталог содержит пользовательские приложения и другую информацию, такую как исходные коды и изображения, документы или файлы конфигурации, которые необходимы для пользователя. /usr является самым большим каталогом в системе Linux, и некоторые пользователи целенаправленно выделяют ему место при разделении диска. В /usr следует обратить внимание на:

/usr/doc

Документация для пользовательских приложений в различных форматах текстовых файлов.

/usr/share

Здесь находятся файлы конфигурации и графика для многих пользовательских приложений.

/usr/src

Файлы, содержащие исходный код для программного обеспечения системы, а также ядро ​​Linux.

/usr/include

Является хранилищем заголовочных файлы для компилятора C. Заголовочные файлы определяют структуры и константы, необходимые для создания наиболее стандартных программ. Подкаталог /usr/include содержит заголовки для компилятора C ++.

/usr/X11R6

Cодержит систему X Window и необходимые для ее функционирования утилиты. Подкаталоги /usr/X11R6 могут содержать некоторые собственные бинарные файлы, а также документацию, заголовочные файлы, файлы конфигурации, изображения, звуки и другие вещи, связанные с графическими программами.

</usr/local>

Место для хранения приложений и других файлов для использования на локальном компьютере. Если ваш компьютер является частью сети, каталог /usr может физически находиться на другом компьютере и может использоваться многими сетевыми рабочими станциями Linux. В этом виде сети каталог /usr/local содержит только материал, который не должен использоваться на многих машинах и предназначен для использования только на локальной машине.

Скорее всего, однако, Ваше устройство не входит в такую ​​сеть, но это совершенно не означает, что каталог /usr/local бесполезен. Если вы найдете интересные приложения, которые официально не являются частью вашего дистрибутива, Вам следует установить их в /usr/local. Например, если Вы собирались установить приложение в /usr/bin, но оно не является частью вашего дистрибутива, Вы должны установить его в /usr/local/bin. При разграничении программ, которые входят и не входят в ваш дистрибутив, Вы избегаете путаницы и храните свои файлы в порядке.

</ lib>

Общие библиотеки для динамически связанных программ. Чем-то напоминают DLL (динамически связанные библиотеки), если говорить о Windows.

</ home>

Здесь пользователи сохраняют свои личные файлы. Каждый пользователь имеет свой собственный каталог /home, и обычно это единственное место, где обычным пользователям разрешено записывать файлы. Вы можете настроить систему Linux так, чтобы обычные пользователи не могли даже просмотреть содержимое домашних каталогов других пользователей.

</ root>

Домашний каталог суперпользователя (root's). Не путайте это с корневым каталогом (/) системы Linux.

</ var>

Этот каталог содержит переменные данные, которые постоянно изменяются при запуске системы. Некоторые интересные подкаталоги:

/var/log

Каталог, содержащий файлы системных журналов. Они обновляются, когда система работает, и проверка их может дать вам ценную информацию о работоспособности вашей системы. Если что-то в вашей системе внезапно пойдет не так, файлы журнала могут содержать некоторую информацию о ситуации.

/var/mail

Входящая и исходящая почта хранятся в этом каталоге.

/var/spool

Этот каталог содержит файлы, помещенные в очередь для некоторого процесса, например, печать.


Оригинал текста «Веб-серверы. Основы Shell»

Web servers

A web server is a computer system that processes requests via HTTP, the basic network protocol used to distribute information on the World Wide Web. The term can refer to the entire system, or specifically to the software that accepts and supervises the HTTP requests.

We will mostly work with Apache web servers.

The primary function of a web server is to store, process and deliver web pages to clients. The communication between client and server takes place using the Hypertext Transfer Protocol (HTTP). Pages delivered are most frequently HTML documents, which may include images, style sheets and scripts in addition to text content.

A user agent, commonly a web browser or web crawler, initiates communication by making a request for a specific resource using HTTP and the server responds with the content of that resource or an error message if unable to do so. The resource is typically a real file on the server's secondary storage, but this is not necessarily the case and depends on how the web server is implemented.

While the primary function is to serve content, a full implementation of HTTP also includes ways of receiving content from clients. This feature is used for submitting web forms, including uploading of files.

Many generic web servers also support server-side scripting using Active Server Pages (ASP), PHP, or other scripting languages. This means that the behavior of the web server can be scripted in separate files, while the actual server software remains unchanged. Usually, this function is used to generate HTML documents dynamically ("on-the-fly") as opposed to returning static documents. The former is primarily used for retrieving or modifying information from databases. The latter is typically much faster and more easily cached but cannot deliver dynamic content.

Web servers are not only used for serving the World Wide Web. They can also be found embedded in devices such as printers, routers, webcams and serving only a local network. The web server may then be used as a part of a system for monitoring or administering the device in question. This usually means that no additional software has to be installed on the client computer since only a web browser is required (which now is included with most operating systems).

Shell Basics

Filesystem Structure

As you may have noticed, Linux organizes its files differently from Windows. At first the directory structure may seem illogical and strange to you and you'll have no idea where all the programs, icons, config files, and others are. This is by no means a complete list of all the directories on Linux, but it shows you the most interesting places in your file system.

< / >

The root directory. The starting point of your directory structure. This is where the Linux system begins. Every other file and directory on your system is under the root directory. Usually the root directory contains only subdirectories, so it's a bad idea to store single files directly under root. Don't confuse the root directory with the root user account, root password (which obviously is the root user's password) or root user's home directory (see /root below).

< / boot>

As the name suggests, this is the place where Linux keeps information that it needs when booting up. For example, this is where the Linux kernel is kept. If you list the contents of /boot, you'll see a file called vmlinuz - that's the kernel.

< / etc>

The configuration files for the Linux system. Most of these files are text files and can be edited by hand. Some interesting stuff in this directory:

/etc/inittab
A text file describing the processes that are started at system bootup and during normal operation. For example, here you can determine if you want the X Window System to start automatically at bootup, and configure what happens when a user presses Ctrl+Alt+Del.

/etc/fstab

This file contains descriptive information about the various file systems and their mount points, like floppies, cdroms, and so on.

/etc/passwd

A file that contains various pieces of information for each user account. This is where the users are defined.

</bin, /usr/bin>

These two directories contain a lot of programs (binaries, hence the directory's name) for the system. The /bin directory contains the most important programs that the system needs to operate, such as the shells, ls, grep, and other essential things. /usr/bin in turn contains applications for the system's users. However, in some cases it really doesn't make much difference if you put the program in /bin or /usr/bin.

</sbin, /usr/sbin>

Most system administration programs are stored in these directories. In many cases you must run these programs as the root user.

</usr>

This directory contains user applications and a variety of other things for them, like their source codes, and pictures, docs, or config files they use. /usr is the largest directory on a Linux system, and some people like to have it on a separate partition. Some interesting stuff in /usr:

/usr/doc

Documentation for the user apps, in many file formats.

/usr/share

Config files and graphics for many user apps.

/usr/src

Source code files for the system's software, including the Linux kernel.

/usr/include

Header files for the C compiler. The header files define structures and constants that are needed for building the most standard programs. A subdirectory under /usr/include contains headers for the C++ compiler.

/usr/X11R6

The X Window System and things for it. The subdirectories under /usr/X11R6 may contain some X binaries themselves, as well as documentation, header files, config files, icons, sounds, and other things related to the graphical programs.

< / usr/local>

This is where you install apps and other files for use on the local machine. If your machine is a part of a network, the /usr directory may physically be on another machine and can be shared by many networked Linux workstations. On this kind of a network, the /usr/local directory contains only the stuff that is not supposed to be used on many machines and is intended for use at the local machine only.

Your machine most likely isn't a part of a network like this, but it doesn't mean that /usr/local is useless. If you find interesting apps that aren't officially a part of your distro, you should install them in /usr/local. For example, if the app would normally go to /usr/bin but it isn't a part of your distro, you should install it in /usr/local/bin instead. When you keep your own programs away from the programs that are included in your distro, you'll avoid confusion and keep things nice and clean.

< / lib>

The shared libraries for programs that are dynamically linked. The shared libraries are similar to DLL's on Windows.

< / home>

This is where users keep their personal files. Every user has their own directory under /home, and usually it's the only place where normal users are allowed to write files. You can configure a Linux system so that normal users can't even list the contents of other users' home directories.

< / root>

The superuser's (root's) home directory. Don't confuse this with the root directory (/) of a Linux system.

< / var>

This directory contains variable data that changes constantly when the system is running. Some interesting subdirectories:

/var/log

A directory that contains system log files. They're updated when the system runs, and checking them out can give you valuable info about the health of your system. If something in your system suddenly goes wrong, the log files may contain some info about the situation.

/var/mail

Incoming and outgoing mail is stored in this directory.

/var/spool

This directory holds files that are queued for some process, like printing.


Глоссарий

Word Definition Example Translation
  Active Server Pages   Many generic web servers also support server-side scripting using Active Server Pages (ASP).  
  Apache   We will mostly work with Apache web servers.  
  app   This directory contains user applications.  
  Apache web servers   We will mostly work with Apache web servers.  
  CentOS   CentOS is the operating system most commonly used on ServerMania devices.  
  Cloud servers   Cloud servers are an affordable alternative to dedicated servers.  
  cPanel   cPanel is an online (Linux-based) web hosting control panel  
  communication   The communication between client and server takes place using the Hypertext Transfer Protocol (HTTP).  
  compiler   Header files for the C compiler.  
  database   A database is an organized collection of data.  
  Data Backup   They can add more RAM, add and change HDD and SSD, select RAID, configure Network Configuration select OS, choose Data Backup etc.  
  database management system   A database management system (DBMS) is a computer software application that interacts with the user, other applications, and the database itself to capture and analyze data.  
  data centers   VPSs are being created on servers located across all data centers  
  Debian   Debian is a Linux distribution that is composed entirely of free software  
  Dedicated servers   ServerMania offers these types of Dedicated servers  
  device   The devices that are available to a Linux system.  
  directory   Every other file and directory on your system is under the root directory.  
  dynamic content   The latter is typically much faster and more easily cached but cannot deliver dynamic content.  
  file   This is where users keep their personal files.  
  Gaming Server   As in Gaming Server, clients can configure the server specs to best suit their needs.  
  HDD   They can add more RAM, add and change HDD and SSD, select RAID, configure Network Configuration select OS, choose Data Backup etc.  
  Hybrid Servers   Hybrid Servers are virtualized machines, sold with pre-configured resources.  
  HTML documents   Pages delivered are most frequently HTML documents.  
  Hypertext Transfer Protocol   The communication between client and server takes place using the Hypertext Transfer Protocol (HTTP).  
  kernel   If you list the contents of /boot, you'll see a file called vmlinuz - that's the kernel.  
  Linux   As you may have noticed, Linux organizes its files differently from Windows.  
  Network Configuration   They can add more RAM, add and change HDD and SSD, select RAID, configure Network Configuration select OS, choose Data Backup etc.  
  Node   Each node is a separate standalone server.  
  OS   They can add more RAM, add and change HDD and SSD, select RAID, configure Network Configuration select OS, choose Data Backup etc.  
  partition   some people like to have it on a separate partition.  
  permissions   Most files should have permissions set to 644, and directories to 755.  
  Plesk control panel   They can add cPanel or Plesk control panels.  
  Private Cloud servers   Private Cloud servers are utilized by a single client and are custom designed for the application that the cloud will be used for.  
  Public Cloud servers   Public Cloud servers are shared by multiple users and designed to be the most useful for the widest array of applications.    
  resources   They are specific because they come with more resources than other Dedicated servers.  
  RAM   They can add more RAM, add and change HDD and SSD, select RAID, configure Network Configuration select OS, choose Data Backup etc.  
  subdirectories   Usually the root directory contains only subdirectories  
  server-side scripting   Many generic web servers also support server-side scripting using Active Server Pages (ASP).  
  Source code   Source code files for the system's software, including the Linux kernel.  
  Storage Servers   Storage Servers, as the name suggest, is mostly used to store a large volume of information.  
  system administration   Most system administration programs are stored in these directories.  
  Ubuntu   Ubuntu is the most popular operating system running in cloud environments  
  user applications   This directory contains user applications.  
  VPS   A virtual private server (VPS) is a virtual machine sold as a service (aaS) by Server Mania.  
  Webmail   Webmail is a cPanel mail interface that allows cPanel users to access their cPanel account mail from anywhere.  
  Windows   As you may have noticed, Linux organizes its files differently from Windows.  
  web crawler   A user agent, commonly a web browser or web crawler, initiates communication.  
  web forms   This feature is used for submitting web forms, including uploading of files.  
  web server   A web server is a computer system that processes requests via HTTP, the basic network protocol used to distribute information on the World Wide Web.  
  World Wide Web   Web servers are not only used for serving the World Wide Web.  

Список использованных источников

1. Голикова, Т.И. Лексические трудности перевода: учебно-методическое пособие [для студентов 3-го курса факультета межкультурных коммуникаций] / Т. И. Голикова; Министерство образования Республики Беларусь, Минский государственный лингвистический университет. – Минск, 2009. – 125 с.

2. Словарь Multitran [Электронный ресурс]. – 2018. – Режим доступа: https://www.multitran.ru. – Дата доступа: 10.05.2018.

3. Context Reverso [Электронный ресурс]. – 2018. – Режим доступа: https://www.multitran.ru. – Дата доступа: 10.05.2018.

4.

 


Дневник производственной практики: преддипломной

 



Поделиться:




Поиск по сайту

©2015-2024 poisk-ru.ru
Все права принадлежать их авторам. Данный сайт не претендует на авторства, а предоставляет бесплатное использование.
Дата создания страницы: 2019-06-10 Нарушение авторских прав и Нарушение персональных данных


Поиск по сайту: