Blocking SSH Connection Using Scheduled Task and Python Script
In this article, we will discuss how to block SSH connections on a system using a Python script and a scheduled task. This can be useful in various scenarios, such as when you want to prevent unauthorized access to your system or when you want to perform maintenance on the SSH service.
Prerequisites
Before we begin, make sure you have the following:
- A system with SSH service installed
- Python installed on the system
- Administrator privileges on the system
Blocking SSH Connection with Python Script
The following Python script can be used to block SSH connections on a system. The script uses the os module to execute the command that blocks the SSH connection.
```python
import os
# Command to block SSH connection
command = "iptables -A INPUT -p tcp --dport 22 -j DROP"
# Execute the command
os.system(command)
```
To keep the script running in the background, you can use a while loop to continuously execute the command. Here is an example:
```python
import os
while True:
# Command to block SSH connection
command = "iptables -A INPUT -p tcp --dport 22 -j DROP"
# Execute the command
os.system(command)
```
Save the script as block_ssh.py and run it using the following command:
```bash
python block_ssh.py
```
Setting up Scheduled Task
To run the Python script automatically at a specific time, you can use a scheduled task. Here are the steps to set up a scheduled task on a Linux system:
- Open the terminal and enter the following command to open the crontab file:
```bash
crontab -e
```
- Add the following line to the crontab file to run the Python script every day at 2 AM:
```css
0 2 * * * /usr/bin/python /path/to/block_ssh.py
```
Replace /usr/bin/python with the path to the Python executable on your system, and replace /path/to/block_ssh.py with the path to the Python script.
Unblocking SSH Connection
To unblock SSH connections, you can simply stop the Python script or delete the scheduled task. Alternatively, you can use the following command to unblock SSH connections:
```bash
iptables -D INPUT -p tcp --dport 22 -j DROP
```
In this article, we discussed how to block SSH connections on a system using a Python script and a scheduled task. This can be useful in various scenarios, such as when you want to prevent unauthorized access to your system or when you want to perform maintenance on the SSH service.
References