Skip to content

Instantly share code, notes, and snippets.

@dave-kennedy
Last active December 16, 2021 15:42
Show Gist options
  • Save dave-kennedy/3f2fc0fc56ba66888e82c7754f9a1271 to your computer and use it in GitHub Desktop.
Save dave-kennedy/3f2fc0fc56ba66888e82c7754f9a1271 to your computer and use it in GitHub Desktop.
Bash script for controlling VNC sessions
#!/usr/bin/env bash
display_help() {
echo "Usage: `basename "$0"` OPTIONS ACTION
Options must be specified before any action, and only one action may be specified.
Options:
-g | --geometry size specify VNC session display size
-s | --server name specify VNC server name in case it's not the current host
-h | --help display this message and exit
Actions:
list list open sessions
create create session
kill session kill session
Environment variables:
VNC_GEOMETRY VNC session display size
VNC_SERVER VNC server name"
}
list_sessions() {
server=$1
if [ -z "$server" ]; then
if ! sessions=`ls ~/.vnc/*.pid 2>&1`; then
echo 'Error: no open VNC sessions on current host'
exit 1
fi
else
if ! sessions=`ssh -q "$server" 'ls ~/.vnc/*.pid' 2>&1`; then
echo "Error: no open VNC sessions on current $server"
exit 1
fi
fi
for session in $sessions; do
basename -s .pid "$session"
done
}
create_session() {
server=$1
geometry=$2
if [ -z "$server" ]; then
if ! vncserver -geometry "$geometry" > /dev/null; then
echo "Error: couldn't create VNC session on current host"
exit 1
fi
else
if ! ssh -q "$server" "vncserver -geometry $geometry" > /dev/null; then
echo "Error: couldn't create VNC session on $server"
exit 1
fi
fi
list_sessions "$server"
}
kill_session() {
server=$1
session=$2
if [ -z "$session" ]; then
echo 'Error: must specify VNC session to terminate'
exit 1
fi
if [ -z "$server" ]; then
if ! vncserver -kill "$session" > /dev/null; then
echo "Error: couldn't kill VNC session $session on current host"
exit 1
fi
else
if ! ssh -q "$server" "vncserver -kill $session" > /dev/null; then
echo "Error: couldn't kill VNC session $session on $server"
exit 1
fi
fi
}
if [ $# -eq 0 ]; then
echo 'Error: no arguments specified'
display_help
exit 1
fi
if [ -n "$VNC_GEOMETRY" ]; then
geometry=$VNC_GEOMETRY
else
geometry=1024x768
fi
server=$VNC_SERVER
while [ $# -gt 0 ]; do
case "$1" in
-g | --geometry)
geometry=$2
shift
shift
;;
-s | --server)
server=$2
shift
shift
;;
-h | --help)
display_help
exit 0
;;
list)
list_sessions "$server"
exit 0
;;
create)
create_session "$server" "$geometry"
exit 0
;;
kill)
kill_session "$server" "$2"
exit 0
;;
-*)
echo "Error: unrecognized option $1"
display_help
exit 1
;;
*)
echo "Error: extra argument $1"
display_help
exit 1
;;
esac
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment