Last active
March 10, 2021 13:06
-
-
Save fuegas/e60fdb5ea74bc808dda4c3355d9a78e0 to your computer and use it in GitHub Desktop.
Script to fix pty default for SSH connections
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 | |
| # Common functions | |
| function log_prefix { date +%Y-%m-%d\ %H:%M:%S; } | |
| function info { echo "[$(log_prefix)] Info: ${1}"; } | |
| function error { >&2 echo "[$(log_prefix)] Error: ${1}"; } | |
| function fatal { >&2 echo "[$(log_prefix)] Fatal: ${1}"; exit ${2:1}; } | |
| # Detect if we're on OS-X | |
| if [[ "${OSTYPE}" != darwin* ]]; then | |
| fatal 'Chef knife fixer can only run on OS-X!' | |
| fi | |
| # Because OS-X is BSD based, we need to template the conflicting options | |
| sed --version >/dev/null 2>&1 && sed_opts='--in-place' || sed_opts='-i ""' | |
| stat -c %U "$(pwd)" >/dev/null 2>/dev/null && stat_opts='-c %U' || stat_opts='-f %Su' | |
| # Try to find the file we need to fix | |
| info 'Searching for knife scripts we need to fix' | |
| search='/opt/chef-workstation/embedded/lib/ruby/gems/*/gems/chef-*/lib/chef/knife/ssh.rb' | |
| ls ${search} >/dev/null 2>&1 | |
| if [ $? -gt 0 ]; then | |
| fatal 'No files to fix found, is chef workstation installed?' 2 | |
| fi | |
| found=0 | |
| fixed=0 | |
| correct=0 | |
| # Fix each found file | |
| for path in $(ls ${search}); do | |
| found=$(( ${found} + 1)) | |
| egrep 'def.*open_session.*pty ?= ?false' "${path}" >/dev/null 2>/dev/null | |
| if [ $? -eq 0 ]; then | |
| info "Need to fix ${path}" | |
| owner="$(stat ${stat_opts} "${path}")" | |
| [[ "${owner}" != "${USER}" ]] \ | |
| && sudo='sudo' \ | |
| && info 'Elevated permissions required to edit this file' \ | |
| || sudo='' | |
| ${sudo} sed -E ${sed_opts} \ | |
| 's/^( *def open_session.*,) ?pty ?= ?false(.*)$/\1 pty = true\2/' \ | |
| "${path}" | |
| [ $? -eq 0 ] \ | |
| && info 'Fixed pty default' \ | |
| && fixed=$(( ${fixed} + 1)) \ | |
| || error 'Failed to alter file...' | |
| else | |
| info "No need to fix ${path}" | |
| correct=$(( ${correct} + 1 )) | |
| fi | |
| done | |
| if [ ${found} -eq 0 ]; then | |
| info 'No files found to be fixed, is this expected?' | |
| else | |
| info "Found ${found} files that might needed fixing" | |
| [ ${fixed} -gt 0 ] && info "- ${fixed} fixed" | |
| [ ${correct} -gt 0 ] && info "- ${correct} did not need fixing" | |
| incorrect=$(( ${found} - ${fixed} - ${correct} )) | |
| if [ ${incorrect} -gt 0 ]; then | |
| error "Not all found files could be fixed (${incorrect}), please check the log above." | |
| else | |
| info "Happy knifing!" | |
| fi | |
| fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment