帮我写一个远程修改nginx配置文件的工具类
时间: 2024-04-12 12:06:36 浏览: 7
以下是一个基本的Python类,可以远程修改Nginx配置文件:
```python
import paramiko
class NginxConfigurator:
def __init__(self, host, user, password, config_file_path):
self.host = host
self.user = user
self.password = password
self.config_file_path = config_file_path
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.client.connect(self.host, username=self.user, password=self.password)
def get_config(self):
stdin, stdout, stderr = self.client.exec_command(f"cat {self.config_file_path}")
return stdout.read().decode()
def set_config(self, config):
stdin, stdout, stderr = self.client.exec_command(f"echo '{config}' > {self.config_file_path}")
def reload_nginx(self):
stdin, stdout, stderr = self.client.exec_command("sudo systemctl reload nginx")
def close(self):
self.client.close()
```
使用示例:
```python
configurator = NginxConfigurator("example.com", "username", "password", "/etc/nginx/nginx.conf")
# 获取当前的Nginx配置
current_config = configurator.get_config()
print(current_config)
# 修改Nginx配置
new_config = current_config.replace("old_value", "new_value")
configurator.set_config(new_config)
# 重新加载Nginx配置
configurator.reload_nginx()
# 关闭SSH连接
configurator.close()
```