如何在已知PID的指定Bash进程中执行命令?
Can I execute a command in a specific Bash process via its PID?
Short answer: Yes, you can—but the approach depends on your setup, and there are important caveats to keep in mind. Let’s break down two common methods to do this, along with their pros and cons.
Method 1: Inject commands via gdb
This is a direct way to force the target Bash process to run your command by calling its built-in system() function. Here’s how:
- Attach
gdbto the target PID (100 in your example):gdb -p 100 - Once inside
gdb, execute your command using thesystem()call:call system("ls") - When done, detach from the process and exit
gdb:detach quit - You can also run this all in one line for automation:
gdb -p 100 -ex 'call system("ls")' -ex detach -ex quit
Notes for this method:
- Permissions: You’ll need sufficient privileges (either root access or the same user as the target process) to attach to it. System security tools like SELinux might block this if not configured to allow it.
- Process interference: If the target Bash process is actively running another command, injecting
system()will pause its current work, run your command, then resume. This can cause unexpected behavior if the process is handling critical tasks. - Output handling: The output of
lswill go to the target process’s original stdout (usually its terminal). If you need to capture this output in your script, redirect it to a file first:
Then your script can readgdb -p 100 -ex 'call system("ls > /tmp/ls_output.txt")' -ex detach -ex quit/tmp/ls_output.txt.
Method 2: Write to the target’s terminal (for interactive Bash processes)
If the target Bash process is interactive (sitting at a prompt waiting for user input), you can send commands directly to its associated terminal device:
- Find the terminal linked to the target process:
This will show a symlink to a device likels -l /proc/100/fd/0/dev/pts/2(the terminal the process is attached to). - Write your command to this terminal:
echo "ls" > /dev/pts/2
Notes for this method:
- Prerequisite: The target process must be in an idle state (waiting for input at the Bash prompt). If it’s running another command, the injected
lswill be queued and run after the current command finishes. - Permissions: You need write access to the terminal device. This usually means being the same user as the terminal owner, or having root privileges.
- Output visibility: The
lsoutput will display on the target’s terminal, not in your script’s output stream.
Key Caveats to Remember
- Security risks: Injecting commands into another process can be misused, so system hardening tools might block these operations. Only do this on systems you own or have explicit permission to modify.
- Unpredictable behavior: If the target process is handling sensitive tasks or has open state (like variables, current directory), your injected command will run in that context—this could lead to unintended side effects.
内容的提问来源于stack exchange,提问作者Sai Nikhil
相关产品推荐
相关产品推荐

