Skip to content

Instantly share code, notes, and snippets.

@mdeweerd
Last active November 11, 2023 17:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdeweerd/07918a6a1300fa64f0faf08c7e2a1dd1 to your computer and use it in GitHub Desktop.
Save mdeweerd/07918a6a1300fa64f0faf08c7e2a1dd1 to your computer and use it in GitHub Desktop.
Screen/bash setup for Home Assistant "Terminal & SSH" add-on

Home Assistant "Terminal & SSH" screen configuration.

Purpose

  • Start gnu screen automatically when connecting interactively to Home Assistant (keep terminal session across connections).
  • Provide a status line in the terminal
  • Define some aliases
  • Automatically "re-install" after add-on upgrade (create symbolic links, .vimrc, .viminfo)
  • Use vim when calling vi

How to

  • These files reside in /data
  • The "Terminal & SSH" add-on automatically relinks the .bash_profile script (see /etc/cont-init.d/profile.sh )
  • If you add a requirements.txt in /data then it will install the python modules listed in it.
  • Add the appropriate apks to your "Terminal & SSH configuration". This is what my configuration looks like (PUBLIC_KEY and KEY_ALIAS need to be replaced with your values - password is optional). You only need the 'screen' apk, I suggest the other ones (database access, install python modules):
authorized_keys:
  - >-
    ssh-rsa
    PUBLIC_KEY KEY_ALIAS
password: ''
apks:
  - screen
  - etckeeper
  - sqlite
  - py3-pip
server:
  tcp_forwarding: false

You can get started quickly with some of the following examples (on HAOS). (Examples with ls -lrt to view the files)

cd data
git init .
git remote add -t \* -f origin https://gist.github.com/07918a6a1300fa64f0faf08c7e2a1dd1.git
git checkout main

Using the zip will require that you update the zip file name and subdirectory:

cd /data
wget -O bashenv.zip https://gist.github.com/mdeweerd/07918a6a1300fa64f0faf08c7e2a1dd1/archive/dbcc36adb7b6f77541a5cbfd2f3fcfe5e7b26a7f.zip
unzip bashenv.zip
SDIR=07918a6a1300fa64f0faf08c7e2a1dd1-dbcc36adb7b6f77541a5cbfd2f3fcfe5e7b26a7f
mv ${SDIR}/* ${SDIR}/.[a-z]* .
rmdir ${SDIR}
ls -lrat

Keyboard in console

This is just a note regarding the keyboard layout for the machine's console, not the ssh add-on. This issue is discussed at home-assistant/operating-system#1775 .

The following may help to set the keymap:

apk update
apk add -s kbd-bkeymaps alpine-conf busybox-openrc
setup-keymap
# or
setup-keymap fr fr
##### Autostart 'screen' in '.bashrc'
if [ "$PS1" != "" ] && [ "$TERM" != "screen" ] && [ "${STARTED_SCREEN:-x}" = x ] && [ "${SSH_TTY:-x}" != x ]
then
# Find path where real .bash_profile is
SRCPATH=$(dirname "$(realpath "${HOME}/.bash_profile")")
for p in .screenrc .vimrc .viminfo ; do
if [[ ! -L "${HOME}/$p" ]] && [[ ! -e "${HOME}/$p" ]] ; then
ABSPATH=${SRCPATH}/$p
if [[ ! -e "${ABSPATH}" ]] ; then
touch "${ABSPATH}"
fi
ln -s "${ABSPATH}" "${HOME}/$p"
fi
done
if [ ! -r "/config" ] && [ -r "/homeassistant" ] ; then
ln -s /homeassistant/ /config
fi
# Name of file that has the timestamp to know if requirements.txt is nex
REQFILEREFERENCE=${HOME}/.lastreqread
# The requirements.txt to install
REQFILE="${SRCPATH}/requirements.txt"
# Install requirements.txt if newer.
if [ -e "${REQFILE}" ] ; then
if [ ! -e "${REQFILEREFERENCE}" ] || [ "$(stat -c %Y "${REQFILE}")" -gt "$(stat -c %Y "${REQFILEREFERENCE}")" ] ; then
( date && nohup pip install -r "${REQFILE}" && touch "${REQFILEREFERENCE}" && pip cache purge ) >> "${HOME}/pipinstall.log" &
fi
fi
# shellcheck disable=SC2050
if [ 0 == 1 ] ; then
# Screen disable at this time because of issue on latest SSH add-ons
STARTED_SCREEN=1 ; export STARTED_SCREEN
[ -d "${HOME}/lib/screen-logs" ] || mkdir -p "${HOME}/lib/screen-logs"
sleep 1
screen -RR && exit 0
# normally, execution of this rc script ends here...
echo "Screen failed! continuing with normal bash startup"
fi
fi
###### [end of auto-screen snippet]
# Use vim when typing vi
alias vi=\\vim
alias pd=pushd
export LANG=C.UTF-8
# shellcheck disable=SC1091
ha completion bash > /tmp/bash_completion && . /tmp/bash_completion
###### Colorfull prompt (at end of '.bashrc')
mUID=$(id -u)
MACHINE=$(hostname -f)
if [ "$mUID" = "0" ] ; then
PS1="${C_RED}\u${C_DEF}@${C_RED}${MACHINE}${C_DEF}:\w${C_RED}#${C_DEF} "
PS2="${C_RED}>${C_DEF} "
else
PS1="${C_BLUE}\u${C_DEF}@${MACHINE}:\w${C_BLUE}\$ ${C_DEF}"
PS2="${C_BLUE}>${C_DEF} "
fi
export PS2
export PS1
case $TERM in
xterm*)
PROMPT_COMMAND='echo -ne "\033]0;${USER}@${MACHINE}: ${PWD}\007"'
echo -ne "\033]0;${USER}@${MACHINE}: ${PWD}\007"
;;
*)
#setterm -blength 0
;;
esac
###### [end of colorfull prompt (at end of .bashrc)]
.bash_history
.ssh/
.viminfo
host_keys/
options.json
---
files: ^(.*\.(py|json|md|sh|yaml|cfg|txt))$
exclude: ^(\.[^/]*cache/.*|.*/_user.py)$
repos:
- repo: https://github.com/executablebooks/mdformat
# Do this before other tools "fixing" the line endings
rev: 0.7.17
hooks:
- id: mdformat
name: Format Markdown
entry: mdformat # Executable to run, with fixed options
language: python
types: [markdown]
args: [--wrap, '75', --number]
additional_dependencies:
- mdformat-toc
- mdformat-beautysh
# -mdformat-shfmt
# -mdformat-tables
- mdformat-config
- mdformat-black
- mdformat-web
- mdformat-gfm
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
# - id: no-commit-to-branch
# args: [--branch, main]
- id: check-yaml
args: [--unsafe]
- id: debug-statements
- id: end-of-file-fixer
- id: trailing-whitespace
- id: check-json
- id: mixed-line-ending
- id: check-builtin-literals
- id: check-ast
- id: check-merge-conflict
- id: check-executables-have-shebangs
- id: check-shebang-scripts-are-executable
- id: check-docstring-first
- id: fix-byte-order-marker
- id: check-case-conflict
# - id: check-toml
- repo: https://github.com/adrienverge/yamllint.git
rev: v1.32.0
hooks:
- id: yamllint
args:
- --no-warnings
- -d
- '{extends: relaxed, rules: {line-length: {max: 90}}}'
- repo: https://github.com/lovesegfault/beautysh.git
rev: v6.2.1
hooks:
- id: beautysh
- repo: https://github.com/codespell-project/codespell
rev: v2.2.5
hooks:
- id: codespell
args:
# - --builtin=clear,rare,informal,usage,code,names,en-GB_to_en-US
- --builtin=clear,rare,informal,usage,code,names
- --ignore-words-list=hass,master
- --skip="./.*"
- --quiet-level=2
######## ~/.screenrc ########
#termcapinfo xterm*|rxvt*|kterm*|Eterm* 'hs:ts=\E]0;:fs=\007:ds=\E]0;\007'
#defhstatus "screen ^E (^Et) | $USER@^EH"
hardstatus alwayslastline
hardstatus string '%{gk}[ %{G}%H %{g}][%= %{wk}%?%-Lw%?%{=b kR}(%{W}%n*%f %t%?(%u)%?%{=b kR})%{= kw}%?%+Lw%?%?%= %{g}][%{Y}%l%{g}]%{=b C}[ %m/%d %c ]%{W}'
# see http://www4.informatik.uni-erlangen.de/~jnweiger/screen-faq.html
# support color X terminals
termcap xterm 'XT:AF=\E[3%dm:AB=\E[4%dm:AX'
terminfo xterm 'XT:AF=\E[3%p1%dm:AB=\E[4%p1%dm:AX'
termcapinfo xterm 'XT:AF=\E[3%p1%dm:AB=\E[4%p1%dm:AX:hs:ts=\E]2;:fs=\007:ds=\E]2;screen\007'
termcap xtermc 'XT:AF=\E[3%dm:AB=\E[4%dm:AX'
terminfo xtermc 'XT:AF=\E[3%p1%dm:AB=\E[4%p1%dm:AX'
termcapinfo xtermc 'XT:AF=\E[3%p1%dm:AB=\E[4%p1%dm:AX:hs:ts=\E]2;:fs=\007:ds=\E]2;screen\007'
# auto-screen support; see http://taint.org/wk/RemoteLoginAutoScreen
# detach on hangup
autodetach on
# no startup msg
startup_message off
# always use a login shell
shell -$SHELL
# auto-log
logfile $HOME/lib/screen-logs/%Y%m%d-%c-%H.log
deflog off # change to 'on' if you want to log all your sessions
#################### End of ~/.screenrc
set mouse=v
#!/bin/bash
# This imports the authorized_keys (from USB key)
# to the homeassistant container.
#
# This allows login as root over SSH on port 22222
# (ssh -p 22222 <IP|ha_noproxy_domain>)
#
# Requires auhtorized_keys on the USB drive.
#
# ? Possible to copy files to USB key from Terminal+SSH
ha os import
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment