Skip to content

Instantly share code, notes, and snippets.

@lstellway
Last active June 10, 2023 21:49
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save lstellway/58c78471ce09f665dd10adb973378935 to your computer and use it in GitHub Desktop.
Change the default SSH port on macOS
# 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"
}
@lstellway
Copy link
Author

Include the provided function in your profile (Bash, Zsh, etc..) and run the following command:

ssh_set_port [PORT]

For example, to change the SSH port to 2222, run:

ssh_set_port 2222

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:

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