Command Execution
Ruby System Shell Command Execution
Some things to think about when choosing between these ways are:
Are you going to interact with none interactive shell, like
ncat
? 2. Do you just want stdout or do you need stderr as well? Or even separated out?How big is your output? Do you want to hold the entire result in memory?
Do you want to read some of your output while the subprocess is still running?
Do you need result codes?
Do you need a ruby object that represents the process and lets you kill it on demand?
The following ways are applicable on all operating systems.
Kernel#exec
Kernel#system
Dealing with ncat
session?
ncat
session?Have you ever wondered about how to do deal with interactive commands like passwd
or ncat
sessions in Ruby? If you're familiar with Python, you've probably used python -c 'import pty; pty.spawn("/bin/sh")'
. In Ruby it's really easy using exec
or system
. The main trick is to forward STDERR to STDOUT so you can see system errors.
exec
system
Kernel#` (backticks)
IO#popen
Open3#popen3
Process#spawn
Kernel.spawn executes the given command in a subshell. It returns immediately with the process id.
%x"", %x[], %x{}, %x$''$
Rake#sh
IO#ioctl (Injecting Commands)
You can also inject commands into other terminals using Ruby and IOCTL syscall
Extra
To check the status of the backtick operation you can execute $?.success?
$?
How to choose?
Last updated