|
| 1 | +#!/bin/bash |
| 2 | +VAR_DIR=${HOME}/var/jupyter |
| 3 | +mkdir -p ${VAR_DIR} |
| 4 | +JUPYTER_IP_FILE=`echo ${VAR_DIR}/jupyter_host_ip.txt` |
| 5 | + |
| 6 | +function start_on_port(){ |
| 7 | + # netstat -tuln --> list all the ports in use |
| 8 | + # tr -s ' ' --> squeezes multiple space into one space (make a consistent delimiter) |
| 9 | + # cut -d' ' -f4 --> gets the fourth field of the output (which is address and port) |
| 10 | + # rev | cut -d':' -f1 | rev --> reverse the input get the port as the first field and reverse back to original (required because ipv6 notation is :::) |
| 11 | + # grep -v '^$' --> drop blank lines |
| 12 | + # sort -n | uniq --> only include unique port numbers |
| 13 | + |
| 14 | + port_list=$(netstat -tuln | \ |
| 15 | + tr -s ' ' | \ |
| 16 | + cut -d' ' -f4 | \ |
| 17 | + rev | cut -d':' -f1 | rev | \ |
| 18 | + grep -v '^$' | \ |
| 19 | + sort -n | uniq) |
| 20 | + |
| 21 | + # Start port number to search from |
| 22 | + start_port=8001 |
| 23 | + |
| 24 | + # Loop to find the first open port above 8000 |
| 25 | + while true; do |
| 26 | + # Check if the port is open using netstat and grep |
| 27 | + if ! echo $port_list | grep -q "$start_port\b"; then |
| 28 | + echo $start_port |
| 29 | + break |
| 30 | + fi |
| 31 | + |
| 32 | + # If the port is not open, check the next port |
| 33 | + ((start_port++)) |
| 34 | + done |
| 35 | +} |
| 36 | + |
| 37 | +mkdir -p ${HOME}/Notebooks |
| 38 | +cd ${HOME}/Notebooks |
| 39 | + |
| 40 | +# Delete any old jupyter ip files if they exist |
| 41 | +# we check this file after startup for the ssh tunnel |
| 42 | +if [ -f "$JUPYTER_IP_FILE" ] ; then |
| 43 | + rm "$JUPYTER_IP_FILE" |
| 44 | +fi |
| 45 | + |
| 46 | +# Make sure we are starting jupyter lab in the base conda environment |
| 47 | +active_env=`conda info|egrep "active environment"|cut -d: -f2|tr -d '[:space:]'` |
| 48 | +if [ "$active_env" == "base" ]; then |
| 49 | + host_ip=`ifconfig 2>/dev/null|grep inet|grep 255.255.252.0|sed -e's/^[ ]*//'|cut -d' ' -f2` |
| 50 | + host_port=$(start_on_port) |
| 51 | + echo jupyter-lab --ip $host_ip --port=$host_port |
| 52 | + echo "$host_ip:$host_port" >${JUPYTER_IP_FILE} |
| 53 | + nohup jupyter-lab --no-browser --ip $host_ip --port=$host_port 1>${VAR_DIR}/jupyter-lab.log 2>${VAR_DIR}/jupyter-lab.err & |
| 54 | +else |
| 55 | + echo "You Must start in the base conda environment!" |
| 56 | +fi |
0 commit comments