Last active
August 29, 2015 13:56
-
-
Save bert2002/9056102 to your computer and use it in GitHub Desktop.
list open ssh connections and show menu to connect
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
#!/bin/bash | |
# Description: Show current ssh client connections and | |
# establish further one if requested. | |
set -e | |
# Define optional exclude regex. | |
EXCLUDE_RE="" | |
count=1 | |
ssh_client_pids=$( lsof -n -iTCP -sTCP:ESTABLISHED | awk '/^ssh/{print | |
$2}' ) | |
if [[ -z $ssh_client_pids ]]; then | |
echo "No established ssh connection found." | |
exit | |
fi | |
for pid in $ssh_client_pids; do | |
# Insert space between cmd parameters via xargs. | |
ssh_client_cmd="$( ps -eo pid,args | awk -v pid=$pid '$1 ~ pid && $2 ~/ssh/{$1=""; print $0}' )" | |
if [[ $ssh_client_cmd =~ ${EXCLUDE_RE:-^$} ]]; then | |
continue | |
else | |
echo "[$count] $ssh_client_cmd" | |
array[$count]="$ssh_client_cmd" | |
count=$(( $count+1 )) | |
fi | |
done | |
# Exit if array has no content. | |
if [[ $count = 1 ]]; then | |
echo "No ssh connections for reuse available." | |
exit | |
fi | |
printf "%s " "Enter connection id:" | |
read connection_id | |
if [[ ! $connection_id =~ ^([1-9][0-9]*|$) ]]; then | |
echo "Only positive integers allowed." | |
exit | |
else | |
# Use id 1 if $connection_id is unset. | |
${array[${connection_id:-1}]} | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment