Created
March 30, 2020 08:37
-
-
Save bored-engineer/ef577a3409c705cda1c499c1b7991685 to your computer and use it in GitHub Desktop.
Get the PID of a SSH controlmaster process
This file contains hidden or 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
package main | |
import ( | |
"bytes" | |
"encoding/binary" | |
"io" | |
"log" | |
"net" | |
"os" | |
"time" | |
) | |
var helloHandshake = []byte{ | |
// Length | |
0, 0, 0, 8, | |
// MSG_HELLO | |
0, 0, 0, 1, | |
// Protocol Version | |
0, 0, 0, 4, | |
} | |
var aliveCheck = []byte{ | |
// Length | |
0, 0, 0, 8, | |
// MUX_C_ALIVE_CHECK | |
16, 0, 0, 4, | |
// Request ID | |
1, 2, 3, 4, | |
} | |
var aliveResponse = []byte{ | |
// Length | |
0, 0, 0, 12, | |
// MUX_S_ALIVE | |
128, 0, 0, 5, | |
// Request ID | |
1, 2, 3, 4, | |
// PID | |
0, 0, 0, 0, | |
} | |
func main() { | |
path := os.Args[1] | |
conn, err := net.DialTimeout("unix", path, 3*time.Second) | |
if err != nil { | |
log.Fatalf("%s: failed to dial ControlMaster: %v", path, err) | |
} | |
defer conn.Close() | |
// Hello handshake | |
if _, err := conn.Write(helloHandshake); err != nil { | |
log.Fatalf("%s: failed to write hello handshake: %v", path, err) | |
} | |
// Read the response to our handshake and ensure it is same version | |
helloReply := make([]byte, len(helloHandshake)) | |
if _, err := io.ReadFull(conn, helloReply); err != nil { | |
log.Fatalf("%s: failed to read handshake response: %v", path, err) | |
} | |
if !bytes.Equal(helloHandshake, helloReply) { | |
log.Fatalf("%s: did not recieve expected handshake response", path) | |
} | |
// Send the alive check | |
if _, err := conn.Write(aliveCheck); err != nil { | |
log.Fatalf("%s: failed to write alive check: %v", path, err) | |
} | |
// Read the alive response | |
aliveReply := make([]byte, len(aliveResponse)) | |
if _, err := io.ReadFull(conn, aliveReply); err != nil { | |
log.Fatalf("%s: failed to read alive response: %v", path, err) | |
} | |
if !bytes.Equal(aliveResponse[:12], aliveReply[:12]) { | |
log.Fatalf("%s: did not recieve expected alive response", path) | |
} | |
pid := binary.BigEndian.Uint32(aliveReply[12:16]) | |
log.Printf("PID: %d", pid) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment