Last active
September 19, 2016 16:22
-
-
Save jessedearing/91f3cb42b119962a453e7df9d43dc0de to your computer and use it in GitHub Desktop.
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
sshClient, err := setUpSSHClient(host) | |
if err != nil { | |
log.Panic(err) | |
} | |
defer sshClient.Close() | |
lsofOut, err := runCmd(sshClient, "sudo lsof -i tcp:"+port+" | tail -1 | awk '{ print $2; }'") | |
lsofOut = strings.Trim(lsofOut, "\n\r ") | |
if err != nil { | |
log.Panic(err) | |
} | |
psOut, err := runCmd(sshClient, "ps -p "+lsofOut+" -o pid -o etime -o command") | |
if err != nil { | |
log.Panic(err) | |
} | |
log.Printf("PID: %s\n", lsofOut) | |
log.Printf("Process that owns connection:\n%s\n", psOut) | |
func setUpSSHClient(host string) (*ssh.Client, error) { | |
privkey, err := ioutil.ReadFile(os.Getenv("HOME") + "/.ssh/id_rsa") | |
if err != nil { | |
return nil, err | |
} | |
signer, err := ssh.ParsePrivateKey(privkey) | |
if err != nil { | |
return nil, err | |
} | |
sshConfig := &ssh.ClientConfig{ | |
User: *sshuser, | |
Auth: []ssh.AuthMethod{ | |
ssh.PublicKeys(signer), | |
}, | |
} | |
client, err := ssh.Dial("tcp", host+":22", sshConfig) | |
if err != nil { | |
return nil, err | |
} | |
return client, nil | |
} | |
func runCmd(client *ssh.Client, command string) (string, error) { | |
sess, err := client.NewSession() | |
if err != nil { | |
return "", err | |
} | |
defer sess.Close() | |
b, err := sess.CombinedOutput(command) | |
if err != nil { | |
return "", err | |
} | |
return string(b), nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment