Skip to content

Instantly share code, notes, and snippets.

@methane
Last active February 25, 2018 18:33
Show Gist options
  • Save methane/7397627 to your computer and use it in GitHub Desktop.
Save methane/7397627 to your computer and use it in GitHub Desktop.
Go で 80 番以下のポートを listen するためのスクリプト
#!/usr/bin/python
from __future__ import print_function
import os
import pwd
import socket
import sys
def bind_and_exec(host, port, uid, gid, cmd):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((host, port))
sock.listen(2048)
if hasattr(sock, 'set_inheritable'): # Python 3.4
sock.set_inheritable(True)
fd = sock.fileno()
os.setgid(gid)
os.setuid(uid)
for i in range(1, len(cmd)):
cmd[i] = cmd[i].replace('$FD', str(fd))
print("executing:", cmd)
os.execvp(cmd[0], cmd)
def main():
if len(sys.argv) < 4:
sys.exit("usage: bind_and_setuser.py address:port user cmd...")
host, port = sys.argv[1].rsplit(':', 1)
port = int(port)
pw = pwd.getpwnam(sys.argv[2])
bind_and_exec(host, port, pw.pw_uid, pw.pw_gid, sys.argv[3:])
if __name__ == '__main__':
main()
[circus]
statsd = 1
[watcher:echo-go]
cmd = ./server_go -fd $(circus.sockets.echo)
use_sockets = True
uid = myservice
gid = myservice
[socket:echo]
host = 0.0.0.0
port = 80
package main
import (
"flag"
"fmt"
"log"
"net"
"os"
)
func echo_handler(conn net.Conn) {
defer conn.Close()
buf := make([]byte, 128)
for {
n, err := conn.Read(buf)
if err != nil {
log.Println(err)
return
}
fmt.Println("Received: ", string(buf[:n]))
conn.Write(buf[:n])
}
}
func main() {
fd := flag.Uint("fd", 0, "fd to listen and serve")
port := flag.Uint("port", 0, "port to listen and serve")
flag.Parse()
var l net.Listener
var err error
if *fd != 0 {
l, err = net.FileListener(os.NewFile(uintptr(*fd), ""))
if err != nil {
log.Panic(err)
}
} else if *port != 0 {
l, err = net.ListenTCP("tcp", &net.TCPAddr{Port: int(*port)})
if err != nil {
log.Panic(err)
}
} else {
fmt.Println("fd or port required.")
return
}
for {
conn, e := l.Accept()
if e != nil {
log.Fatal(e)
return
}
go echo_handler(conn)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment