Script: Network Connections

Published 12-29-2018 13:18:36

Raw | Network Document Template | Template Help

#!/bin/bash
# Bound to Mod+n

# Set menu properties
mymenu=$(setmenu -lb)

# Where network documents are stored
Docs="/home/$USER/Documents/networks/"

# Where should log files be stored
Logs="/home/$USER/Logs/"

MenuChoices=\
"Info
Servers
Networking
Workstations
Printers
Ping
PullRC
Reboot
ShoVer
Time Entry
VPN"

runprefix=
tty=$(tty)
case $tty in
	*tty1|"not a tty") runprefix="$TERMINAL -e" ;;
esac

ClearExit() { clear ; exit 0 ;}
SecurePW() { PassFile=$(mktemp) ; echo "$Password" >$PassFile ;}
Say() { (echo "$1" "$2" | lolcat) ; notify-send "$1" "$2" ;}
MainMenu() {
	Chosen=$(cat /tmp/nets-names | $mymenu "Choose a network:") || ClearExit
	clear
	[[ $Chosen = "Time Entry" ]] && timeentry && ClearExit
	for i in $Docs* ; do
		[[ $Chosen = $( (sed "3q;d" $i) | awk '{print $2;}' | cut -d '"' -f2) ]] && Document=$i
	done
	[[ -z $Document ]] && ClearExit
	ScanDoc $Document
	CommandMenu ;}
CommandMenu() {
	CommandChoice=$(echo -e "$MenuChoices" | $mymenu "$Network Command:")
	clear
	[[ -z $CommandChoice ]] && ClearExit
	case $CommandChoice in
		"Info")		openfile $Document ; exit 0 ;;
		"Time Entry")	timeentry $Network ; exit 0 ;;
		"VPN")		connectvpn "$VPNType" "$VPNName" "$Network" ; exit 0 ;;
		*)		SubMenu ;;
	esac ;}
SubMenu() {
	case $CommandChoice in
		Ping)	ChosenHost=$(echo -e "$ServerChoices\n$SwitchChoices\n$WorkstationChoices\n$PrinterChoices" | \
			$mymenu "$Network Choose a device to ping:") ;;
		Reboot) ChosenHost=$(echo -e "$ServerChoices" | $mymenu "$Network Choose a device to reboot:") ;;
		PullRC)	ChosenHost=$(echo -e "$CiscoChoices\nALL!" | $mymenu "$Network Cisco Devices:") ;;
		ShoVer)	ChosenHost=$(echo -e "$CiscoChoices\nALL!" | $mymenu "$Network Cisco Devices:") ;;
		Servers) ChosenHost=$(echo -e "$ServerChoices" | $mymenu "$Network Servers:") ;;
		Networking) ChosenHost=$(echo -e "$SwitchChoices" | $mymenu "$Network Networking Devices:") ;;
		Workstations) ChosenHost=$(echo -e "$WorkstationChoices" | $mymenu "$Network PCs:") ;;
		Printers) ChosenHost=$(echo -e "$PrinterChoices" | $mymenu "$Network Printers:") ;;
	esac
	clear
	if [ -z $ChosenHost ] ; then CommandMenu
	elif [ $ChosenHost = "ALL!" ]; then
		CiscoChoices=${CiscoChoices//'\n'/ }
		for arg in $CiscoChoices ; do
			ChosenHost=$arg
			ExecuteMyCommand
		done
		Say "👍 Finished 'ALL!' tasks"
	else Skipopen="prompt" ; ExecuteMyCommand ; fi ;}
ExecuteMyCommand() {
	HostIP=$(awk -F '|' '/^'$ChosenHost'/ { print $2 }' "$Document" | sed -e 's/^\s*//' -e '/^$/d' -e 's/\s*$//')
	Protocol=$(awk -F '|' '/^'$ChosenHost'/ { print $3 }' "$Document" | sed -e 's/^\s*//' -e '/^$/d' -e 's/\s*$//')
	Username=$(awk -F '|' '/^'$ChosenHost'/ { print $4 }' "$Document" | sed -e 's/^\s*//' -e '/^$/d' -e 's/\s*$//')
	Password=$(awk -F '|' '/^'$ChosenHost'/ { print $5 }' "$Document" | sed -e 's/^\s*//' -e '/^$/d' -e 's/\s*$//')
	Enable=$(awk -F '|' '/^'$ChosenHost'/ { print $6 }' "$Document" | sed -e 's/^\s*//' -e '/^$/d' -e 's/\s*$//')
	Say "🔗 Checking network connectivity."
	if ! ping -c 1 -w 5 "$HostIP" &>/dev/null ; then connectvpn "$VPNType" "$VPNName" "$Network" ; fi
	[[ "$CommandChoice" == "Workstations" ]] && Protocol="RDP"
	if ! grep -R $ChosenHost.$Domain /etc/hosts &>/dev/null ; then
		Line=$(echo -e "$HostIP\t$ChosenHost.$Domain\t\t$ChosenHost")
		sudo -- sh -c -e "echo '$Line' >> /etc/hosts" ; fi
	case $CommandChoice in
		Ping)	$runprefix cping $HostIP ;;
		Reboot) SecurePW ; remotereboot "$Protocol" "$ChosenHost.$Domain" "$Username" "$PassFile" ;;
		PullRC)	SecurePW ; ciscorun "$ChosenHost" "$Username" "$PassFile" "$Enable" "$Network" "$Domain" "$Skipopen" ;;
		ShoVer)	SecurePW ; ciscover "$ChosenHost" "$Username" "$PassFile" "$Enable" "$Network" "$Domain" "$Skipopen" ;;
		Servers|Networking|Workstations|Printers)
			case $Protocol in
				HTTP|HTTPS) $BROWSER $HostIP >/dev/null &disown ;;
				*SSH*|RDP)
					LogFile="$Logs/nets/$(date +%b%d)/$(date +%H%M).$Network.$Protocol.$ChosenHost.log"
					mkdir -p $Logs/nets/$(date +%b%d)/
					> $LogFile
					[[ $(echo -e "Scrape\nManual" | $mymenu "Scrape or input credentials?") = "Manual" ]] && \
					temp1=$(inprompt "Username:") && temp2=$(dmenupass "Password:") && \
					Username="$temp1" && Password="$temp2"
					SecurePW
					clear
					connectcomputer "$Protocol" "$ChosenHost.$Domain" "$Username" "$PassFile" "$Network" "$LogFile" "$Domain" ||
					faillog $Network $Protocol $LogFile "$ChosenHost.$Domain" ;;
			esac ;;
	esac ;}
FindCiscoDevices() {
	for arg in "$@" ; do
		Protocol=$(awk -F '|' '/^'$arg'/ { print $3 }' "$Document" | sed -e 's/^\s*//' -e '/^$/d' -e 's/\s*$//')
		[[ "$Protocol" == "CISCOSSH" ]] && CiscoChoices="$CiscoChoices $arg"
	done
	CiscoChoices=${CiscoChoices// /'\n'}
	CiscoChoices=${CiscoChoices:2} ;}
ScanDoc() {
	Network= Domain= VPNType= VPNName=
	SwitchChoices=() ServerChoices=() WorkstationChoices=() PrinterChoices=() CiscoChoices=()
	local section temp skip_read=false a b
	{
	read
	read
	IFS=$'" \t' read -r __ Network
	IFS=$'" \t' read -r __ Domain
	IFS=$'" \t' read -r __ VPNType
	IFS=$'" \t' read -r __ VPNName
	while [[ $skip_read == true ]] || IFS=$' \t' read -r a b ; do
		skip_read=false
		case "$a $b" in
		'## SWITCHING'*|'## SERVERS'|'## WORKSTATIONS'|'## PRINTERS')
			section=$b
			temp=()
			while IFS=$' \t' read -r a b ; do
				if [[ $a == '##' ]]
				then skip_read=true ; break ; fi
				if [[ $a != 'NAME' ]] && [[ $a != *---* ]]
				then temp+=("$a") ; fi
			done
			case $section in
				SWITCHING*)	SwitchChoices="${temp[@]}"
						FindCiscoDevices "${temp[@]}" ;;
				SERVERS)	ServerChoices="${temp[@]}" ;;
				WORKSTATIONS)	WorkstationChoices="${temp[@]}" ;;
				PRINTERS)	PrinterChoices="${temp[@]}" ;;
			esac ;;
		esac
	done
	SwitchChoices=${SwitchChoices// /'\n'}
	SwitchChoices=${SwitchChoices:2:-2}
	ServerChoices=${ServerChoices// /'\n'}
	ServerChoices=${ServerChoices:2:-2}
	WorkstationChoices=${WorkstationChoices// /'\n'}
	WorkstationChoices=${WorkstationChoices:2:-2}
	PrinterChoices=${PrinterChoices// /'\n'}
	PrinterChoices=${PrinterChoices:2:-2}
	} < "$1" ;}

> ~/.bashrc.networks
> /tmp/nets-names
for file in $Docs* ; do
	echo $(sed "3q;d" $file | cut -d '"' -f2) >> /tmp/nets-names
	echo alias $(basename "${file:0:-3}")=\"$EDITOR $file\" >> ~/.bashrc.networks
done
echo "Time Entry" >> /tmp/nets-names
MainMenu
if [ ! $Network = "Home" ] && [ $(echo -e "Yes\nNo" | $mymenu "Make a time entry note?") == "Yes" ]
then timeentry $Network $SECONDS $ChosenHost
else ClearExit ; fi
exit 0

ReadMe

Required Packages

  • dmenu – the menu
  • lolcat – colors terminal output
  • sshpass – for SSH connections
  • freerdp – for RDP connections
  • expect – a tool for automating applications

VPN packages for Arch Linux

  • pptp
  • networkmanager
  • network-manager-applet
  • vpnc
  • networkmanager-vpnc
  • openvpn
  • networkmanager-openvpn
  • openconnect
  • network-manager-openconnect

VPN packages for Debian

  • network-manager
  • network-manager-gnome
  • openconnect
  • network-manager-openconnect
  • network-manager-openconnect-gnome
  • openvpn
  • network-manager-openvpn
  • network-manager-openvpn-gnome
  • pptp-linux
  • network-manager-pptp
  • network-manager-pptp-gnome
  • vpnc
  • network-manager-vpnc
  • network-manager-vpnc-gnome

How This Script Works

$EDITOR $TERMINAL and $BROWSER variables should be set in ~/.bashrc or ~/.profile

This script will scan any file located in $Docs and produce a menu of networks and devices to interact with.

Every time the script is run it will rewrite the ~/.bashrc.networks file.

If .bashrc.networks is sourced in your .bashrc file, this will make every network document filename a bash alias. Typing any of these aliases into a terminal window will open the network document for editing.

The Menu

Use the arrow keys to navigate the menu, or you can type any characters to filter the menu choices. Press Enter to make a selection.

  • Info – opens the network document in $EDITOR
  • Servers – produces a menu of devices listed in the ## SERVERS table of the network document
  • NetworkingDevices – menu of devices listed in the ## SWITCHING & ROUTING table of the network document
  • Workstations – menu of devices listed in the ## WORKSTATIONS table of the document
  • Printers – menu of devices listed in the ## PRINTERS table of the document
  • Ping – menu of ALL devices listed in ALL tables of the document to send a PING command to
  • PullRC – menu of all Cisco devices listed in the ## SWITCHING & ROUTING table to pull a running config from
  • Reboot – menu of ALL devices listed in ALL tables of the document to send a REBOOT command to
  • ShoVer – menu of all Cisco devices listed in the ## SWITCHING & ROUTING table to send a sho ver command to
  • VPN – makes a VPN connection to the selected network

Change Log

02-11-1029

  • Moved functions to new scripts in ‘sysadmin’ dir

10-27-2018

  • Improved logging (again)
  • Added time entry option when SSH and RDP connections are closed.

8-27-2018

  • Improved logging
  • Added notify-send (dunst) output and icons for notifications

6-14-2018

  • Added “ALL!” to the PullRC menu. This will pull running configs of all the listed Cisco devices.
  • Added ShoVer (Pull_Cisco_Version()) and an extract script named pullciscover.
  • Config file change for extract script location and path for Cisco show-version output.

6-10-2018

  • Fixed the tty variable.
  • Removed telnet.
  • Added Reboot to the Command_Menu()
  • Cleaned up menus, fixed using Esc to back through menus.
  • Improved Fail_Log() output.

6-8-2018

  • Added function Fail_Log() for clear useful feedback if the script is executed inside a terminal.
  • Changed IP-based connections to name-based, using $Chosen_Host.$DomainName for the name. If this hostname is not found in /etc/hosts it will be added. This is to eliminate conflicting entries in ~/.ssh/known_hosts.
  • Added “None” to the case statement in Check_VPN(). If your remote network’s VPN is not supported by the script, put None in the $NetworkDocument header for vpn-profile:.

6-6-2018

  • Added package dependency: expect.
  • Added function Find_Cisco_Devices() to scrape for “CISCOSSH” in the “ACCESS” column of the $NetworkDocument.
  • Added PULLRC (Pull Running Config) and an extract script named pullciscorc.
  • Moved user-defined variables to a $ConfigFile so users can share the same script with their own local settings.

6-5-2018

  • Added package dependency: zenity
  • Added function Prompt_For_Creds() to ask user to scrape credentials from $NetworkDocument or to manually input them for RDP connections.