Running ssh on Amazon EC2 instance on port other than 22

佐手、 提交于 2019-12-03 02:15:35

To connect to an AWS instance through ssh from a port different than default 22:

  1. Open the security group of your instance so that it allows connections to that port from the source that you choose (0.0.0.0/0 for any source).
  2. In your instance:

    • It is a new instance you could use an user-data script like this one:

    #!/bin/bash -ex perl -pi -e 's/^#?Port 22$/Port 443/' /etc/ssh/sshd_config service sshd restart || service ssh restart

Please note that this only works if you are launching a new instance:

User data scripts and cloud-init directives only run during the first boot cycle when an instance is launched.

  • If it is not a new Instance, edit the /etc/ssh/sshd_config file adding/changing Port 22 to the port that you want (i.e: Port 443) to connect through ssh and then do service ssh restart and you should be done.

Note: I did this with an Ubuntu instance, with another Linux instances may be slightly different.

The amazon firewall blocks all ports other than 22. You first have to enable port 80/443/whatever.

HOWTO: Go to "security groups" -> click on the group you chose for your instance, then on the "Inbound" tab.

There you can add your ports.

EDIT: If by chance you also installed apache or some other webserver, port 80 will be used and cannot be used by sshd. I do not know which operating system is installed on your server, but maybe some webserver is already included?

Here is what I came up with to run sshd on 443 and 22 having rhel8 on ec2

  1. make sure your security groups allow connection from your network/ip to the desired ports (in my case 22 and 443)
tcp 443 1.2.3.4/32 #allow access to 443 from IP 1.2.3.4
tcp 22 1.2.3.4/32 #allow access to 22 from IP 1.2.3.4
  1. Login to the EC2 and
#install semanage with
sudo yum install -y policycoreutils-python-utils
#delete 443 from http ports
sudo semanage port -d -t http_port_t -p tcp 443
#add 443 to ssh ports
sudo semanage port -m -t ssh_port_t -p tcp 443
  1. Edit /etc/ssh/sshd_config
Port 22
Port 443
  1. Restart sshd
sudo service sshd restart
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!