Last active
June 10, 2023 21:49
-
-
Save lstellway/58c78471ce09f665dd10adb973378935 to your computer and use it in GitHub Desktop.
Change the default SSH port on macOS
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
# Setup SSH port | |
SYSTEM_SSH_PLIST="/System/Library/LaunchDaemons/ssh.plist" | |
ssh_set_port() { | |
# Ensure a port is specified | |
if [ -z "$1" ]; then | |
printf "No port specified...\n" | |
return 1 | |
fi | |
# Ensure original file exists | |
if [ ! -f "${SYSTEM_SSH_PLIST}" ]; then | |
printf "SSH process definition not found in default location:\n%s\n" "${SYSTEM_SSH_PLIST}" | |
return 1 | |
fi | |
PORT="$1" | |
FIND="<string>ssh<\/string>" | |
REPLACE="<string>${PORT}<\/string>" | |
# Unload existing service if a file already exists | |
# (errors may occur if service is already unloaded - these can be ignored)) | |
if [ -f "/Library/LaunchDaemons/ssh.plist" ]; then | |
sudo launchctl unload /Library/LaunchDaemons/ssh.plist > /dev/null 2>&1 | |
fi | |
# Copy original SSH process definition and replace the port value | |
sudo cp ${SYSTEM_SSH_PLIST} /Library/LaunchDaemons/ssh.plist | |
sudo sed -i '' "1,/${FIND}/s/${FIND}/${REPLACE}/" /Library/LaunchDaemons/ssh.plist | |
# Load the service | |
sudo launchctl load -w /Library/LaunchDaemons/ssh.plist | |
printf "SSH port successfully updated to '%s'\nRun the following command to verify the port:\n\n %s\n" "$1" "sudo lsof -iTCP -sTCP:LISTEN -n -P" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Include the provided function in your profile (Bash, Zsh, etc..) and run the following command:
For example, to change the SSH port to
2222
, run:The process requires
sudo
privileges, so you may need to enter your password. Once confirmed (and you have enabled "Remote Login" under Sharing Preferences), you can run the following command to verify the port has been updated: