Created
May 13, 2010 21:44
-
-
Save andrewvc/400501 to your computer and use it in GitHub Desktop.
Simple init script for creating an ssh tunnel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
#Init script for setting up a ssh tunnel | |
#Remote Port | |
tun_port = 123 | |
#Local port to use | |
tun_lport = 1234 | |
#Remote User | |
tun_user = 'username' | |
#Remote Host | |
tun_host = '1.2.3,4' | |
tun_pid_file = '/tmp/tunnel.pid' | |
tun_pid, proc_ps_info = nil, nil | |
if File.exists?(tun_pid_file) | |
tun_pid = File.read(tun_pid_file).chomp | |
tun_pid = tun_pid.to_i | |
proc_ps_info = `ps aux | awk '$2 == #{tun_pid} {print $_}'` | |
end | |
def kill_pid(pid,signal) | |
if pid | |
puts "Killing PID #{pid}" | |
`kill -#{signal} #{pid}` | |
else | |
puts "Cannot stop tunnel, no known/running process." | |
end | |
end | |
case ARGV[0] | |
when 'stop' | |
kill_pid(tun_pid,15) | |
when 'force-stop' | |
kill_pid(tun_pid,9) | |
when 'status' | |
unless proc_ps_info.nil? || proc_ps_info.empty? | |
puts proc_ps_info | |
else | |
puts "Cannot show status. No known/running process" | |
end | |
when 'start','restart' | |
unless proc_ps_info.nil? || proc_ps_info.empty? | |
puts "Found a running tunnel... sending SIGTERM efore starting" | |
kill_pid(tun_pid,15) | |
end | |
cmd="ssh -N -L #{tun_lport}:#{tun_host}:#{tun_port} #{tun_host} -l #{tun_user}" | |
pid = Process.fork do | |
exec(cmd) | |
end | |
puts "Started a new tunnel with PID #{pid}" | |
File.open(tun_pid_file,'w') {|f| f.write pid.to_s} | |
else | |
puts "Unrecognized/no option, try (start|restart|status|stop|force-stop)" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment