I would like to use this Ruby WEBrick server solution for on-demand showcasing of some random web pages. So I set up some forwarding exception on my adsl modem local web interface( Then enabled iptables with a very basic setup. I use an iptables command to temporarily open port 3000 for tcp, then launch the Ruby script, and when I interrupt the server(with ctlr-c), it closes and I remove that very same filter rule to tidy things up(even though I know the rule wouldn't persist accross reboots):

# sudo iptables -I INPUT -p tcp --dport 3000 -j ACCEPT
# ./myscript(ruby) - server goes up
<ctrl-c>          - server goes down
# sudo iptables -D INPUT -p tcp --dport 3000 -j ACCEPT

How would I do that with a single command/script? I can make an alias to wrap the first command and starting the server, but it's not clear how to take care of the exit and the last command...


I don't know how to do this with the shell. But since the script is already trapping the interrupt signal, you might as well leverage that and add an extra command there as you can execute commands with that interpreter, like so:

#!/usr/bin/env ruby

require 'webrick'
system *%W(sudo iptables -I INPUT -p tcp --dport 3000 -j ACCEPT)
server = WEBrick::HTTPServer.new(:Port => 3000,
                                 :DocumentRoot => '~/webrickroot')

# stop server with Ctrl-C
trap('INT') { server.stop; system *%W(sudo iptables -D INPUT -p tcp --dport 3000 -j ACCEPT) }

Using for convenience an array of blank separated words with system to echo some concerns for the sanity of how the commands' constructs could be interpreted and processed generally. Every token is seemingly supplied to sudo as an argument here1. You will of course be asked for your password(twice) as iptables requires superuser privileges for any significant use, including interactively adding and removing rules.

1. As demonstrated with the apt ruby -e 'system *%W(ls -l foo; rm -rf /)'. Of course DO NOT try this without the splat+word array component(*%W) while quoting what is inside the parentheses.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy