import platform
import subprocess
import requests
import paramiko
def install_nginx_remotely(client, server_ip):
if "Ubuntu" in platform.uname().release:
command = "apt install nginx"
elif "Linux" in platform.uname().release:
command = "yum install nginx"
else:
print("不支持的操作系统")
return
stdin, stdout, stderr = client.exec_command(command)
print(stdout.read().decode())
def check_nginx_status_remotely(client, server_ip):
try:
response = requests.get(f"http://{server_ip}", timeout=5)
if response.status_code == 200:
print(f"Nginx 服务已启动,且可以访问 {server_ip}")
else:
print(f"Nginx 服务已启动,但无法访问 {server_ip}")
except requests.exceptions.ConnectionError:
print(f"Nginx 服务未启动 {server_ip}")
def main():
# 检测服务器操作系统
os_info = platform.uname().release
if "Ubuntu" in os_info:
print("检测到服务器操作系统为 Ubuntu")
elif "Linux" in os_info:
print("检测到服务器操作系统为 Red Hat")
else:
print("不支持的操作系统")
return
# SSH 连接参数
hostname = "192.168.31.128"
username = "root"
password = ("131415711")
# 创建 SSH 客户端
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
# 连接到服务器
client.connect(hostname, username=username, password=password)
# 远程安装 Nginx 软件
install_nginx_remotely(client, hostname)
# 远程检查 Nginx 服务状态
check_nginx_status_remotely(client, hostname)
except paramiko.AuthenticationException:
print("认证失败")
except paramiko.SSHException as e:
print(f"SSH 错误: {e}")
finally:
# 关闭 SSH 连接
client.close()
if __name__ == "__main__":
main()