Обертывание интерактивного процесса с помощью Bash для внедрения в STDIN

Puede usar lsofseleccionando el usuario y buscando el proceso vimcomo en:

sudo lsof -u user -a -c vim | grep swp

Como señala @Fox, el clásico vicrea un archivo temporal en /var/tmp, por lo que la alternativa para verlo, debe (no probarse ).

sudo lsof -u user -a -c vi | grep '/var/tmp/'

Sin embargo, como señala @Fox, no podrá correlacionarlo con el clásico vicon el archivo real, y luego necesitaría las herramientas de las que hablo a continuación en la respuesta (para clásico vi, para vimbastaría ellsof); por lo general hoy en día en Linux está usando vimal invocar vi.

Consulte 15 ejemplos de comandos lsof de Linux (Identificar archivos abiertos)

Volviendo al ejemplo vim, veremos que el archivo de intercambio que se usa con el nombre filese abre como en.file.swp

Si el usuario user1está haciendovi file:

$ sudo lsof -c vi -a -u user1 | grep swp
vi      3615  user1  3u   REG    8,1    12288 265061 /home/user1/.file.swp

deman lsof

-a causes list selection options to be ANDed

-cc This option selects the listing of files for processes executing the command that begins with the characters of c. Multiple commands may be specified, using multiple -c options. They are joined in a single ORed set before participating in AND option selection.

-u s This option selects the listing of files for the user whose login names or user ID numbers are in the comma-separated set s

Además de lsof, también puede usar como raíz, sysdig, que es un poderoso marco de depuración:

Esto mostrará todos los archivos abiertos en el sistema en tiempo real, enumerando el usuario, el pid y el proceso tan pronto como se abran:

sudo sysdig -p "%12user.name %6proc.pid %12proc.name %3fd.num %fd.typechar %fd.name" evt.type=open"

sysdig: system-level exploration and troubleshooting tool

Sysdig instruments your physical and virtual machines at the OS level by installing into the Linux kernel and capturing system calls and other OS events. Then, using sysdig's command line interface, you can filter and decode these events in order to extract useful information and statistics.

Sysdig can be used to inspect live systems in real-time, or to generate trace files that can be analyzed at a later stage.

Como otra herramienta útil para administradores de sistemas, también puede instalar snoopy, que registra todas las invocaciones de procesos llamados a syslog. Si el usuario invoca en la línea de comando vi file, lo verá en los registros del sistema.

Tenga en cuenta que después de instalar snoopy,registrará todas las invocaciones de proceso a través de execve ()hasta que lo desinstale (, lo que puede querer o no que suceda todo el tiempo ).

snoopy: execve() wrapper and logger

snoopy is merely a shared library that is used as a wrapper to the execve() function provided by libc as to log every call to syslog (authpriv). system administrators may find snoopy useful in tasks such as light/heavy system monitoring, tracking other administrator's actions as well as getting a good 'feel' of what's going on in the system (for example Apache running cgi scripts).

Para instalar snoopyysysdig:

$sudo apt-get install snoopy sysdig

Consulte también la pregunta relacionada:Comprender lo que hace un binario de Linux

2
24.03.2019, 13:07
2 ответа

Это зависит от того, предполагается ли запуск этой программы с терминала. Если да, я не думаю, что вы можете сделать в bash; вы должны использовать что-то вроде expect. Пример:

обертка.ожидание:

puts "<<< pid=[pid] >>>"
spawn {*}$argv
trap {send "quit\n"} SIGTERM
interact

пример с bc:

expect wrapper.expect bc -q

<<< pid=4771 >>>
spawn bc -q

kill 4771из другого окна заставит expectотправить строку quitна bc. Обратите внимание, что 4771— это pid процесса expect, а не подпроцесса bc.

Другим вариантом может быть использование TIOCSTIioctl для вставки строки quitв текущий терминал; но опять же, вы не сможете сделать это из оболочки; вам по-прежнему нужна небольшая программа на C (или perl, python и т. д. )только для вызова ioctl()(, а TIOCSTIуже выпотрошен в таких системах, как OpenBSD ).

1
28.04.2021, 23:35

Попробуйте это:

#!/bin/bash

coproc cat -n  # replace 'cat -n' with actual server program to be launched

# first some necessary file-descriptors fiddling
exec {srv_input}>&${COPROC[1]}-
exec {srv_output}<&${COPROC[0]}-

# background commands to relay normal stdin/stdout activity
cat <&0 >&${srv_input} &
cat <&${srv_output} >&1 &

# set signal handler up
term_received=false ; trap 'term_received=true' SIGTERM

# endless loop waiting for events
while true; do
    # wait for server to exit or sigterm received
    wait ${COPROC_PID}
    exit_status=$?
    # if sigterm received:
    if [ $exit_status -gt 128 ] && $term_received ; then
        # kill proxy command relaying stdin to server
        kill %2
        # send quit to server's stdin
        echo $'\n'quit >&${srv_input}
        # close server's stdin
        exec {srv_input}<&-
        # wait for actual server to exit
        wait ${COPROC_PID}
        exit $?
    # something else happened: kill proxy commands and exit with server's own exit status
    else
        kill %2
        kill %3
    fi
    exit $exit_status
done

Я добавлю более полное объяснение, если этот скрипт ответит на ваш вопрос

1
28.04.2021, 23:35

Теги

Похожие вопросы