- Linux.yaroslavl.ru
- О getty_ps
- О mgetty
- О agetty
- getty
- Contents
- Installation
- Add additional virtual consoles
- Automatic login to virtual console
- Virtual console
- Serial console
- Nspawn console
- Prompt only the password for a default user in virtual console login
- Have boot messages stay on tty1
- Последовательное оборудование и запрос login:
- Настройка mgetty Daemon
- Linux что такое getty
- ARGUMENTS
- OPTIONS
- EXAMPLES
- ISSUE ESCAPES
- FILES
Linux.yaroslavl.ru
getty — программа, которая обслуживает процесс входа в систему, когда вы регистрируетесь на Unix машине. Вы должны будете использовать getty, если хотите звонить модемом на вашу Linux машину. Вы не должны использовать getty, если вы хотите только звонить наружу вашим модемом. Имеются три версии, которые обычно используются в Linux: getty_ps, mgetty и agetty. Синтаксис для этих программ отличается, так что убедитесь, что вы проверили и удостоверились, что вы используете правильный синтаксис для того getty, которым пользуетесь.
О getty_ps
Большинство дистрибутивов приходит с установленным пакетом getty_ps. (Debian использовал agetty, но теперь использует mgetty). Он содержит две программы: getty — используется для консоли и устройств терминала, и uugetty для модемов. Я использую эту версию getty, так что на него я и буду ориентироваться.
О mgetty
mgetty — версия getty, главным образом для использования с модемами. Она может использоваться для аппаратных терминалов, но документация приблизительно на 99%, связана с модемами. В дополнение ко входу в систему по телефонной линии, mgetty также обеспечивает поддержку факсов и автоматическое обнаружение PPP. Документация по mgetty (поставляется в формате texinfo) достаточно хороша, и не нуждается в дополнении.
Пожалуйста, обратитесь к ней для инструкций по установке. Вы можете найти последнюю информацию о mgetty по адресу http://www.leo.org/
О agetty
Agetty — третья разновидность getty. Это простая полнофункциональная реализация getty, которая больше подходит для виртуальных консолей или терминалов, чем для модемов.
setserial — программа, которая позволяет вам смотреть и изменять различные атрибуты последовательного устройства, включая адрес порта, прерывание и другие опции последовательного порта. Вы можете посмотреть версию вашей копии этой программы, запустив setserial без параметров. Если параметр — /dev/ttyS1, и т.д., то вы увидите некоторую информацию об этом порте.
Когда ваша Linux система загружается, настраиваются только ttyS<0-3>, используя значения по умолчанию IRQS 4 и 3. Так что, если у вас есть любые другие последовательные порты, обеспеченные другими платами или если ttyS <0-3>имеют необычный IRQ, то вы должны использовать setserial, чтобы сконфигурировать эти последовательные порты. Полный список опций есть в man.
Источник
getty
A getty is the generic name for a program which manages a terminal line and its connected terminal. Its purpose is to protect the system from unauthorized access. Generally, each getty process is started by systemd and manages a single terminal line.
Contents
Installation
This article or section needs language, wiki syntax or style improvements. See Help:Style for reference.
agetty is the default getty in Arch Linux, as part of the util-linux package. It modifies the TTY settings while waiting for a login so that the newlines are not translated to CR-LFs. This tends to cause a «staircase effect» for messages printed to the console. Agetty manages virtual consoles and six of these virtual consoles are provided by default in Arch Linux. They are usually accessible by pressing Ctrl+Alt+F1 through Ctrl+Alt+F6 .
- mingetty — A minimal getty which allows automatic logins.
mingettyAUR || mingettyAUR
- fbgetty — A console getty like mingetty, which supports framebuffers.
http://projects.meuh.org/fbgetty/ || fbgettyAUR
- mgetty — A versatile program to handle all aspects of a modem under Unix.
http://mgetty.greenie.net/ || mgettyAUR
Add additional virtual consoles
Open the file /etc/systemd/logind.conf and set the option NAutoVTs=6 to the number of virtual terminals that you want at boot.
If you wish to start one temporarily, you can start a getty service at the desired TTY by typing:
Automatic login to virtual console
Configuration relies on systemd drop-in files to override the default parameters passed to agetty.
Configuration differs for virtual versus serial consoles. In most cases, you want to set up automatic login on a virtual console, (whose device name is ttyN , where N is a number). The configuration of automatic login for serial consoles will be slightly different. Device names of the serial consoles look like ttySN , where N is a number.
Virtual console
Create a drop-in snippet for getty@tty1.service with the following contents:
If you do not want full automatic login, but also do not want to type your username, you can replace —autologin username with —skip-login —login-options username .
If you want to use a tty other than tty1, see systemd FAQ.
Serial console
Create the following file (and leading directories):
Nspawn console
To configure auto-login for a systemd-nspawn container, override console-getty.service :
If machinectl login my-container method is used to access the container, also add —autologin username to container-getty@.service template that manages pts/2 pseudo ttys:
Prompt only the password for a default user in virtual console login
Getty can be used to login from a virtual console with a default user, typing the password but without needing to insert the username. For instance, to prompt the password for username on tty1 :
Have boot messages stay on tty1
By default, Arch has the getty@tty1 service enabled. The service file already passes —noclear , which stops agetty from clearing the screen. However systemd clears the screen before starting it. To disable this behavior, create /etc/systemd/system/getty@tty1.service.d/noclear.conf :
This overrides only TTYVTDisallocate for agetty on TTY1, and leaves the global service file /usr/lib/systemd/system/getty@.service untouched. See Systemd#Editing provided units.
Источник
Последовательное оборудование и запрос login:
Когда-то очень распространенным вариантом Unix-систем был такой: одна мощная машина, а вокруг нее много тупых («dumb») символьных терминалов или модемов. Сейчас такая схема очень редкая, что очень радует. А вот модемы сейчас очень распространены, хотя они используются обычно для сервисов SLIP и PPP (описаны в главе 7 и главе 8). Однако, каждая из этих конфигураций может использовать простую программу, названную getty.
Термин getty сокращение от «get tty» Программа getty открывает последовательное устройство, конфигурирует его, факультативно конфигурирует модем и ждет подключение, которое будет сделано. Активное подключение на последовательном устройстве обычно указывается Data Carrier Detect (DCD) штырьком в последовательном шнуре. Когда происходит соединение, getty выдает приглашение login: и затем вызывает программу login, чтобы обработать вход в систему. Каждый из виртуальных терминалов (устройств /dev/tty1 ) в Linux имеет свою копию программы getty, запущенную именно для него.
Имеется ряд различных версий getty, каждая разработанная, чтобы удовлетворить некоторые конфигурации лучше, чем другие. Версия getty, которую я опишу, названа mgetty. Она ориентирована на работу с модемами, что и принесло ей солидную популярность, включая поддержку для автоматических факсимильных программ и речевых модемов. При конфигурировании mgetty я сконцентрируюсь на ответах на стандартные вызовы для обмена данными.
Настройка mgetty Daemon
mgetty daemon доступен в исходных кодах с ftp://alpha.greenie.net/pub/mgetty/source и почти во всех дистрибутивах Linux. Демон mgetty отличается от большинства других версий getty, которые были разработаны для Hayes-совместимых модемов. Он поддерживает прямые подключения терминала, но лучше всего подходит для dialup прикладных программ. Вместо DCD-линии для определения входного подключения, эта версия слушает сообщение RING , генерируемое современными модемами, когда они обнаруживают входящее обращение и не сконфигурированы для автоответа.
Главный исполняемый модуль назван /usr/sbin/mgetty , а основной файл настройки /etc/mgetty/mgetty.config . Имеется ряд других программ и файлов конфигурации, которые покрывают другие свойства mgetty .
Для большинства инсталляций настройка сводится к правке /etc/mgetty/mgetty.config и добавлении соответствующих записей в файл /etc/inittab , чтобы выполнять mgetty автоматически.
Пример 4-6 показывает очень простой файл настройки mgetty. Этот пример определяет два последовательных устройства. Первое, /dev/ttyS0 , поддерживает Hayes-модем со скоростью 38,400 bps. Второе, /dev/ttyS0 , поддерживает терминал прямого доступа VT100 со скоростью 19,200 bps.
Пример 4-6. Простой файл /etc/mgetty/mgetty.config
Файл конфигурации поддерживает глобальные и специфические для порта параметры. В нашем примере мы использовали глобальную опцию, чтобы установить быстродействие в 38,400 bps. Это значение унаследовано портом ttyS0 . mgetty применяет именно это значение, если в секции специфической информации для порта не задано другое, как это сделано для ttyS1 .
Ключевое слово debug управляет уровнем детализации отчетов mgetty. Ключевое слово data-only в конфигурации ttyS0 предписывает mgetty игнорировать любые свойства факс-модема, чтобы функционировать только как модем данных. Ключеове слово direct в конфигурации ttyS1 предписывает mgetty не делать попытку инициализации модема на этом порте. Наконец, toggle-dtr предписывает mgetty не делать попытку повесить трубку при получении на линии сигнала DTR (Data Terminal Ready).
Вы можете также оставить пустым файл mgetty.config и использовать параметры командной строки, чтобы определить те же самые параметры. Документация, сопровождающая программу, включает полное описание параметров командной строки и файла конфигурации mgetty .
Мы должны добавить две записи в файл /etc/inittab , чтобы активизировать эту конфигурацию. Файл inittab файл конфигурации команды init. Команда init является ответственной за инициализацию системы. Она автоматически выполняет программы при начальной загрузке и перезапускает их, когда они завершаются. Это идеально для целей работы программы getty.
Каждая строка файла /etc/inittab содержит 4 поля, разделяемые двоеточиями. Первое поле является идентификатором. Оно уникально маркирует запись в файле. Традиционно это два символа, но современные версии позволяют четыре. Второе поле содержит список уровней выполнения, на которых эта запись должна быть активна. Уровни выполнения являются средством обеспечения альтернативных конфигураций системы. Они связаны с наборами скриптов в каталогах /etc/rc1.d , /etc/rc2.d и т.д. Третье поле описывает, когда принять меры. Для работы программы getty оно должно быть определено как respawn . Это означает, что при завершении программы, она будет запущена вновь. Имеется еще несколько параметров, но они не важны для наших целей в данный момент. Четвертое поле задает команду, которая будет выполнена. Именно здесь надо определить команду mgetty и все необходимые ее параметры. В нашем простом примере мы запускаем и перезапускаем mgetty, когда система действует на уровнях выполнения 2 или 3 и передаем в качестве аргумента только имя устройства для работы. Команда mgetty подразумевает каталог /dev , так что задавать его явно в имени устройства не нужно.
Эта глава дает только общее представлдение о mgetty. Подробные сведения можно найти в Serial-HOWTO.
После правки файла конфигурации, надо перезапустить процесс init, чтобы изменения вступили в силу. Пошлите сигнал hangup процессу init. Он всегда имеет ID процесса равный единице, так что можно использовать команду:
Источник
Linux что такое getty
agetty has several non-standard features that are useful for hard-wired and for dial-in lines: o Adapts the tty settings to parity bits and to erase, kill, end-of-line and uppercase characters when it reads a login name. The program can handle 7-bit characters with even, odd, none or space parity, and 8-bit characters with no parity. The following special characters are recognized: @ and Control-U (kill); #, DEL and back space (erase); carriage return and line feed (end of line). o Optionally deduces the baud rate from the CONNECT messages produced by Hayes(tm)-compatible modems. o Optionally does not hang up when it is given an already opened line (useful for call-back applications). o Optionally does not display the contents of the /etc/issue file. o Optionally displays an alternative issue file instead of /etc/issue . o Optionally does not ask for a login name. o Optionally invokes a non-standard login program instead of /bin/login . o Optionally turns on hard-ware flow control o Optionally forces the line to be local with no need for carrier detect.
This program does not use the /etc/gettydefs (System V) or /etc/gettytab (SunOS 4) files.
ARGUMENTS
Under System V, a «-» port argument should be preceded by a «—«. baud_rate. A comma-separated list of one or more baud rates. Each time agetty receives a BREAK character it advances through the list, which is treated as if it were circular.
Baud rates should be specified in descending order, so that the null character (Ctrl-@) can also be used for baud rate switching. term The value to be used for the TERM environment variable. This overrides whatever init(8) may have set, and is inherited by login and the shell.
OPTIONS
-l login_program Invoke the specified login_program instead of /bin/login. This allows the use of a non-standard login program (for example, one that asks for a dial-up password or that uses a different password file). -H login_host Write the specified login_host into the utmp file. (Normally, no login host is given, since agetty is used for local hardwired connections and consoles. However, this option can be useful for identifying terminal concentrators and the like. -m Try to extract the baud rate the CONNECT status message produced by Hayes(tm)-compatible modems. These status messages are of the form: » «. agetty assumes that the modem emits its status message at the same speed as specified with (the first) baud_rate value on the command line.
Since the -m feature may fail on heavily-loaded systems, you still should enable BREAK processing by enumerating all expected baud rates on the command line. -n Do not prompt the user for a login name. This can be used in connection with -l option to invoke a non-standard login process such as a BBS system. Note that with the -n option, agetty gets no input from user who logs in and therefore won’t be able to figure out parity, character size, and newline processing of the connection. It defaults to space parity, 7 bit characters, and ASCII CR (13) end-of-line character. Beware that the program that agetty starts (usually /bin/login) is run as root. -t timeout Terminate if no user name could be read within timeout seconds. This option should probably not be used with hard-wired lines. -L Force the line to be a local line with no need for carrier detect. This can be useful when you have a locally attached terminal where the serial line does not set the carrier detect signal. -w Wait for the user or the modem to send a carriage-return or a linefeed character before sending the /etc/issue (or other) file and the login prompt. Very useful in connection with the -I option.
EXAMPLES
For a hard-wired line or a console tty:
/sbin/agetty 9600 ttyS1
For a directly connected terminal without proper carriage detect wiring: (try this if your terminal just sleeps instead of giving you a password: prompt.)
/sbin/agetty -L 9600 ttyS1 vt100
For a old style dial-in line with a 9600/2400/1200 baud modem:
/sbin/agetty -mt60 ttyS1 9600,2400,1200
For a Hayes modem with a fixed 115200 bps interface to the machine: (the example init string turns off modem echo and result codes, makes modem/computer DCD track modem/modem DCD, makes a DTR drop cause a dis-connection and turn on auto-answer after 1 ring.)
/sbin/agetty -w -I ‘ATE0Q1&D2&C1S0=1\015’ 115200 ttyS1
ISSUE ESCAPES
b Insert the baudrate of the current line. d Insert the current date. s Insert the system name, the name of the operating system. l Insert the name of the current tty line. m Insert the architecture identifier of the machine, eg. i486 n Insert the nodename of the machine, also known as the hostname. o Insert the NIS domainname of the machine. O Insert the DNS domainname of the machine. r Insert the release number of the OS, eg. 1.1.9. t Insert the current time. u Insert the number of current users logged in. U Insert the string «1 user» or » users» where is the number of current users logged in. v Insert the version of the OS, eg. the build-date etc. Example: On my system, the following /etc/issue file:
FILES
The text in the /etc/issue file (or other) and the login prompt are always output with 7-bit characters and space parity.
The baud-rate detection feature (the -m option) requires that the modem emits its status message after raising the DCD line.
Источник