Mostrando postagens com marcador ssh. Mostrar todas as postagens
Mostrando postagens com marcador ssh. Mostrar todas as postagens

Disconnect Inactive or Idle SSH Connections in Linux


Identifying Inactive or Idle SSH Connections

Before disconnecting inactive or idle SSH connections, it is important to first identify them. In Linux, there are several commands that can be used to list active users and their sessions, display information about logged-in users and their processes, and view a log of previous logins and sessions.
Using the 'who' command to list active users and their sessions

The 'who' command is used to display a list of currently logged-in users along with their login name, terminal line number (tty), login time, and remote hostname or IP address. To specifically view only SSH connections, the '-u' option can be added to the command. This will display only active SSH connections with the corresponding user information.

who -u

If you have identified an inactive or idle SSH connection and want to terminate it manually, there are several commands that you can use to do so. These commands specifically target the processes associated with the SSH connection, allowing you to end them without affecting any other processes on your system.
Using the 'kill' command to terminate a specific session ID

The 'kill' command is used to send a signal to a particular process (or multiple processes) in order to terminate them. When it comes to disconnecting an inactive or idle SSH connection, you can use 'kill' with the session ID associated with that particular connection.

To determine the session ID of an inactive or idle SSH connection, you can use any of the methods mentioned in section two of this article. Once you have determined the session ID, simply run the following command −

kill [sessionID]

This will immediately terminate that specific SSH connection and log out any user associated with it.
Using the 'pkill' command to kill all processes associated with a specific user

If you want to disconnect all inactive or idle SSH connections for a particular user at once, then you can use the 'pkill' command. This command sends a signal not only to a specific process but also kills all other related processes as well. To terminate all connections for one particular user, run this command −

pkill -U [username]

This will send signals and end all ssh connections opened by [username].
Using the 'skill' command to send a signal to terminate specific processes

Sometimes using kill or pkill methods may terminate other associated processes also with an active session. It is not always easy to determine which of these processes are associated with the active SSH connection, so you can use the 'skill' command instead. The 'skill' command allows you to target specific processes by name, user or group.

You can use it to send a signal that will terminate any process that matches a particular pattern. To kill a particular ssh session run this command −

skill -KILL -u [username] --tty=[terminal] 

 This will send a signal to end all ssh connections opened by [username] on the specified terminal. The skill command could terminate additional processes also running in the terminal.

SSH 2FA

 

Neste tutorial, exploraremos como configurar a autenticação de dois fatores (2FA) em um servidor Debian Linux usando o aplicativo Microsoft Authenticator. A autenticação de dois fatores é uma camada adicional de segurança que ajuda a proteger suas contas contra acessos não autorizados, exigindo não apenas uma senha, mas também um código gerado por um aplicativo autenticador instalado em um dispositivo móvel.

O Microsoft Authenticator é um aplicativo de autenticação amplamente utilizado e compatível com vários serviços e sistemas. Ao seguir este guia passo a passo, você aprenderá como habilitar o 2FA para usuários em seu servidor Debian Linux e como vincular suas contas ao aplicativo Microsoft Authenticator para garantir uma autenticação segura e protegida.

Para configurar a autenticação de dois fatores (2FA) em um servidor Debian Linux e usar o Microsoft Authenticator como aplicativo de autenticação, siga estas etapas:

  1. Atualize os pacotes e instale os pacotes necessários:

sudo apt update sudo apt upgrade sudo apt install libpam-google-authenticator

  1. Configure o Google Authenticator para cada usuário que deseja habilitar 2FA:

Faça login como o usuário que deseja configurar o 2FA e execute o comando “google-authenticator“. Siga as instruções na tela e anote o código QR, as chaves de recuperação e o código secreto.

google-authenticator

  1. Adicione a conta no aplicativo Microsoft Authenticator:

Abra o aplicativo Microsoft Authenticator em seu dispositivo móvel e siga as etapas para adicionar uma nova conta. Selecione a opção “Outra conta (Google, Facebook, etc.)” e escaneie o código QR ou insira manualmente o código secreto fornecido na etapa anterior.

  1. Configure PAM (Pluggable Authentication Modules) para usar o Google Authenticator:

Edite o arquivo PAM de autenticação SSH. Neste exemplo, usaremos o “nano” como editor de texto, mas você pode usar o editor de sua preferência.

sudo nano /etc/pam.d/sshd

Adicione a seguinte linha ao arquivo, logo abaixo da linha “@include common-auth:

auth required pam_google_authenticator.so

Salve e feche o arquivo.

  1. Configure o SSH para solicitar a autenticação 2FA:

Edite o arquivo de configuração do SSH:

sudo nano /etc/ssh/sshd_config

Procure a linha “ChallengeResponseAuthentication” e altere seu valor para “yes“. Se a linha estiver comentada (iniciando com um “#“), remova o comentário. Se a linha não existir, adicione-a ao arquivo:

ChallengeResponseAuthentication yes

Salve e feche o arquivo.

  1. Reinicie o serviço SSH para aplicar as alterações:

sudo systemctl restart ssh

  1. Teste a autenticação 2FA:

Tente fazer login no servidor via SSH. Você deverá ser solicitado a fornecer sua senha e o código de verificação gerado pelo Microsoft Authenticator.

Lembre-se de que a autenticação 2FA agora está habilitada para os usuários configurados e que a perda do dispositivo com o aplicativo Microsoft Authenticator pode bloquear o acesso à conta. Portanto, guarde as chaves de recuperação geradas na etapa 2 em um local seguro.


Source: https://dolutech.com/configurando-a-autenticacao-de-dois-fatores-2fa-em-um-servidor-debian-linux-com-microsoft-authenticator-um-guia-passo-a-passo/

Limit SSH access by user and network

 Add user filtering with AllowUsers option in sshd_config file:

AllowUsers johndoe@192.168.1.* admin2@192.168.1.* otherid1 otherid2

This allows johndoe and admin2 only from 192.168.1.* addresses and otherid1, otherid2 from anywhere.

 

 

Run local script on remote host via SSH

 

ssh root@<remoteServer> "bash -s" < /opt/script.sh
Run in multiple hosts: 
for i in `cat hosts.txt` ; do echo $i && ssh root@$i "bash -s" < script.sh ; done 

Source: https://unix.stackexchange.com/questions/87405/how-can-i-execute-local-script-on-remote-machine-and-include-arguments

ESXI enalbe SNMP

 Run through ssh (it's  all in one line)

esxcli system snmp set -r && esxcli system snmp set -c COMMUNITY && esxcli system snmp set -p 161 && esxcli system snmp set -C CONTACTA_MAIL && esxcli system snmp set -L "LOCATION" && esxcli system snmp set -e yes
 

Rsync with SSH


On source server:

rsync -arvz -e 'ssh -p 22' –progress /local-folder remote_user@remote_ip:/remote-folder 

SSH timeout interval

A user can log in to the server via ssh, and you can set an idle timeout interval to avoid unattended ssh session. Open sshd_config and make sure following values are configured:
ClientAliveInterval 300
ClientAliveCountMax 0


You are setting an idle timeout interval in seconds (300 secs == 5 minutes). After this interval has passed, the idle user will be automatically kicked out (read as logged out).

Secure SSH


1 – Edit sshd_config file
vi /etc/ssh/sshd_config

# Allow only listed users
AllowUsers adam bob carl

# SSH port
Port 22

# Deny root login
PermitRootLogin no

# Deny login without password
PermitEmptyPasswords no

ESXI CLI

Activate SNMP on VSphere client
Configuration -> Security Profile -> Firewall -> Properties -> SNMP


Connect to ESXI using SSH and run the command below, changing community, contact email and location:

esxcli system snmp set -r && esxcli system snmp set -c public && esxcli system snmp set -p 161 && esxcli system snmp set -C contact@domain.com && esxcli system snmp set -L "City, State" && esxcli system snmp set -e yes


#firewall all hosts
esxcli network firewall ruleset set --ruleset-id snmp --allowed-all true
esxcli network firewall ruleset set --ruleset-id snmp --enabled true
#firewall for specific network
esxcli network firewall ruleset set --ruleset-id snmp --allowed-all false
esxcli network firewall ruleset allowedip add --ruleset-id snmp --ip-address 10.20.0.0.0/23
esxcli network firewall ruleset set --ruleset-id snmp --enabled true
#restart snmp
/etc/init.d/snmpd restart 



Set time:
esxcli system time set -d 31 -M 1 -y 2012 -H 18 -m 0 -s 0

source: https://kb.vmware.com/s/article/1003736


View log in browser:

https://server_ip_or_name/host/syslog.log





Use the Direct Console User Interface (DCUI) over ssh



1 - Browse to the host in the vSphere Web Client inventory.
2 - Click the Manage tab and click Settings.
3 - Under System, select Security Profile.
4 - In the Services panel, click Edit.
5 - Select a service from the list.

        ESXi Shell
        SSH
        Direct Console UI
      
6 - Click Service Details and select the startup policy Start and stop manually.
When you select Start and stop manually, the service does not start when you reboot the host. If you want the service to start when you reboot the host, select Start and stop with host.
7 - Select Start to enable the service.
8 - Click OK.

9 - Access the server over ssh andrun

dcui

ctrl+c to exit

Shutdown Windows or Linux by network

Linux
sshpass -p "$PASSWD" ssh -o StrictHostKeyChecking=no -l $USER $IP 'init 0'


Windows

Use this command to shutdown the computer remotely:
net rpc shutdown --ipaddress ip --user username%password

Add -r if you want to restart, not shutdown:
net rpc shutdown -r -f --ipaddress ip --user username%password

Slow ssh login


Disable DNS option in sshd
vi /etc/ssh/sshd_config

UseDNS no

Execute command and keep ssh session open

execute command and keep ssh session open 

ssh -t 192.168.0.1 'ls /etc; bash'

Failed ssh login attempts

On Debian/Ubuntu

awk '/sshd.*Failed/ { for (f=1; f<NF; f++) if ( $f ~ "from" ) print $2, $1, $(f-1), $(f+1) }' /var/log/auth.log*

Monitoring response time with curl

   curl -s -o /dev/null -w "Conecction: %{time_connect}s | Start transfer: %{time_starttransfer}s | Total time: %{time_total}s\n" ...

Mais vistos