Close all ports linux

How to close ports in Linux?

I have some question in closing port, I think I got some strange things.

When I use execute

it shows that 23/TCP port is open.

But when I execute

it show that 23/tcp port is closed.

Which of them is true? I want to close this port on my whole system, how can I do it?

5 Answers 5

Nmap is a great port scanner, but sometimes you want something more authoritative. You can ask the kernel what processes have which ports open by using the netstat utility:

The options I have given are:

  • -t TCP only
  • -l Listening ports only
  • -n Don’t look up service and host names, just display numbers
  • -p Show process information (requires root privilege)

In this case, we can see that sshd is listening on any interface ( 0.0.0.0 ) port 22, and cupsd is listening on loopback ( 127.0.0.1 ) port 631. Your output may show that telnetd has a local address of 192.168.1.1:23 , meaning it will not answer to connections on the loopback adapter (e.g. you can’t telnet 127.0.0.1 ).

There are other tools that will show similar information (e.g. lsof or /proc ), but netstat is the most widely available. It even works on Windows ( netstat -anb ). BSD netstat is a little different: you’ll have to use sockstat(1) to get the process information instead.

Once you have the process ID and program name, you can go about finding the process and killing it if you wish to close the port. For finer-grained control, you can use a firewall (iptables on Linux) to limit access to only certain addresses. You may need to disable a service startup. If the PID is «-» on Linux, it’s probably a kernel process (this is common with NFS for instance), so good luck finding out what it is.

Источник

Manually closing a port from commandline

I want to close an open port which is in listening mode between my client and server application.

Is there any manual command line option in Linux to close a port?

NOTE: I came to know that «only the application which owns the connected socket should close it, which will happen when the application terminates.»

I don’t understand why it is only possible by the application which opens it . But I’m still eager to know if there is any other way to do it.

15 Answers 15

I had same problem, the process must keep alive but the socket must close. Closing a socket in a running process is not impossible but difficult:

locate the process :

You get a source/destination ip:port portstate pid/processname map

locate the the socket’s file descriptor in the process

You get a list: process name, pid, user,fileDescriptor, . a connection string.

Locate the matching fileDescriptor number for the connection. It’ll be something like «97u» which means «97».

Now connect the process:

Читайте также:  Red giant magic bullet suite 2020 mac os

Now close the socket:

Then detach gdb:

And the socket is closed.

You’re kind of asking the wrong question here. It isn’t really possible to simply «close a port» from outside the application that opened the socket listening on it. The only way to do this is to completely kill the process that owns the port. Then, in about a minute or two, the port will become available again for use. Here’s what’s going on (if you don’t care, skip to the end where I show you how to kill the process owning a particular port):

Ports are resources allocated by the OS to different processes. This is similar to asking the OS for a file pointer. However, unlike file pointers, only ONE process at a time may own a port. Through the BSD socket interface, processes can make a request to listen on a port, which the OS will then grant. The OS will also make sure no other process gets the same port. At any point, the process can release the port by closing the socket. The OS will then reclaim the port. Alternatively, if the process ends without releasing the port, the OS will eventually reclaim the port (though it won’t happen immediately: it’ll take a few minutes).

Now, what you want to do (simply close the port from the command-line), isn’t possible for two reasons. First, if it were possible, it would mean one process could simply steal away another process’s resource (the port). This would be bad policy, unless restricted to privileged processes. The second reason is it is unclear what would happen to the process that owned the port if we let it continue running. The process’s code is written assuming that it owns this resource. If we simply took it away, it would end up crashing on it’s own, so OS’s don’t let you do this, even if you’re a privileged process. Instead, you must simply kill them.

Anyway, here’s how to kill a process that owns a particular port:

That will output the line corresponding to the process holding port , for example:

In this case, procHoldingPort is the name of the process that opened the port, 4683 is its pid, and 8000 (note that it is TCP) is the port number it holds.

Then, look in the last column, you’ll see /. Then execute this:

If that doesn’t work (you can check by re-running the netstat command). Do this:

In general, it’s better to avoid sending SIGKILL if you can. This is why I tell you to try kill before kill -9 . Just using kill sends the gentler SIGTERM.

Like I said, it will still take a few minutes for the port to re-open if you do this. I don’t know a way to speed this up. If someone else does, I’d love to hear it.

Источник

How to close an open port in Ubuntu?

I need a command to list all open ports in my PC, and another command to close a port.

I need to close some applications’ port.

7 Answers 7

netstat can be used to see the ports stat.

To list all Listening ports Numbers with the Process responsible on each one. Terminate or kill the process to close port. ( kill , pkill . )

Without process termination, It is not possible! . See Manually closing a port from command line. Other way you may look for a firewall solution (as isolating that port from network)

Читайте также:  Windows метрика сетевого интерфейса

for closing open port in ubuntu you can use below command

in place of 3000 you can specify your port number

lsof command will give information about file opened by process

-t : This flag specifies that lsof should produce terse output with process identifiers only and no header — e.g., so that the output may be piped to kill(1). This option selects the -w option.

-i : This flag selects the listing of files any of whose Internet address matches the address specified in i. If no address is specified, this option selects the listing of all Internet and x.25 (HP-UX) network files.

Источник

How to «close» open ports?

A few days ago I started to care a lot about my data security, I end up nmap ing myself with: nmap 127.0.0.1

Surprise, surprise, I have lots of active services listen to localhost:

The only one that I might use is ssh (although it is probably not well configured, I will keep this matter to another question).

As far as I know ipp protocol is used by CUPS to share my printers, I don’t need to share them, just access printers from a server.

This is the output of netstat -lntup by the root user, removing the localhost addresses:

How do I configure those services so they only listen to the outside world when I’m actually using them?

3 Answers 3

Determine your exposure

Taking your output from the netstat command, what looks like a lot of services is actually a very short list:

Getting a lay of the land

Looking at this list there are several services which I’d leave alone.

  • dhclient
    • DHCP server daemon responsible for getting your IP address, have to have this one.
  • dropbox
    • obviously Dropbox, have to have

Start reducing it — disable Samba

You can probably right off the bat disable Samba, it accounts for 2 of the above services, nmbd and smbd . It’s questionable that you’d really need that running on a laptop whether on localhost or your IP facing your network.

To check that they’re running you can use the following command, status :

Turning services off can be confusing with all the flux that’s been going on with upstart, /etc/rc.d, business so it might be difficult to figure out which service is under which technology. For Samba you can use the service command:

Keeping them off . permanently

To make them stay off I’ve been using this tool, sysv-rc-conf , to manage services from a console, it works better than most. It allows you to check which services you want to run and in which runlevel they should be started/stopped:

Disabling the rest of what’s NOT needed

So now Samba’s off we’re left with the following:

  • avahi-daemon
    • part of zeroconf (plug-n-play), turn it off
  • rpcbind
    • needed for NFS — turn it off
  • rpc.statd
    • needed for NFS — turn it off

For the remaining 3 you can do the same things we did for Samba to turn them off as well.

To turn CUPS off, which you don’t really need by the way, you can follow the same dance of turning the service off and then disabling it from starting up. To be able to print you’ll need to setup each printer individually on your system. You can do so through the system-config-printer GUI.

Читайте также:  Msi system control manager windows 10 32 bit

Making these services on demand?

This is really the heart of your question but there isn’t really a silver bullet solution to making these services «smart» so that they run when they’re being used, rather than all the time.

#1 — systemd vs. upstart

Part of it is the current split between systemd and upstart. There’s a good overview of the 2 competing technologies here.

Both technologies are trying to do slightly different things, IMO, given their feature sets, systemd seems geared more towards servers whereas upstart seems geared more towards the desktop roll. Over time this will work itself out, IMO, and both services will be stable and feature rich.

Eventually both services will offer on demand starting & stopping across the board for all the services they manage. Features such as StopWhenUnneeded=yes already exist in systemd for example, so it’s only a matter of time until these capabilities get fleshed out.

#2 — service support

Some services don’t support being stopped/started very well if at all. Services such as sshd seem to make little sense to run as on-demand, especially if they’re used heavily. Also some services such as Apache provide mechanisms within themselves to spin up more or less of their own listeners managing themselves. So it’s unclear how on-demand provided by systemd or upstart are going to integrate with these types of services.

Is this really necessary?

You’ll hear from both sides that this is overkill or that you should take a minimalist’s approach only installing what you absolutely need, but it’s really a personal choice. Understanding that these services are there and what they do is really what’s important. At the end of the day a computer is a tool, and by using a Unix system you’re already saying that you’re willing to peek behind the curtain and understand what makes your computer tick.

I’d say that this type of questioning is exactly the frame of mind one should strive for when dealing with computers and Unix in general.

Источник

🐧 Как найти и закрыть открытый порт в Linux

Возможно ли, что трафик использует открытый порт на машине? Если это так, то где находится этот самый порт и как вы его закрываете?

На машинах Linux эта задача на самом деле довольно проста.

Что вам нужно

Для этого вам понадобится только работающий экземпляр Ubuntu Server и учетная запись пользователя с привилегиями sudo.

  • -t Показать только сокеты TCP в Linux
  • -u Показать только сокеты UDP в Linux
  • -l Показать прослушивающие сокеты (например, TCP-порт 22 открыт SSHD-сервером)
  • -p Список имен процессов, которые открывали сокеты
  • -n Не резолвить имена сервисов

Как закрыть порт на Linux

Скажем, вы размещаете веб-сервер на компьютере, но не хотите прослушивать порт 8080.

Вместо этого вы хотите, чтобы трафик проходил только через порты 80 (HTTP) и 443 (HTTPS).

Чтобы закрыть порт 8080, мы будем использовать команду ufw (Uncomplicated FireWall) следующим образом:

  • Аудит ИБ (44)
  • Вакансии (10)
  • Закрытие уязвимостей (98)
  • Книги (27)
  • Мануал (1 937)
  • Медиа (66)
  • Мероприятия (38)
  • Мошенники (22)
  • Обзоры (724)
  • Обход запретов (33)
  • Опросы (3)
  • Скрипты (106)
  • Статьи (292)
  • Философия (77)
  • Юмор (17)

Anything in here will be replaced on browsers that support the canvas element

Источник

Оцените статью