在CentOS上实现Python远程控制前,需确保服务器已开启SSH服务(默认端口22),以便Python脚本通过SSH协议连接。
sudo yum install -y openssh-server
sudo systemctl start sshd
sudo systemctl enable sshd
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --reload
以上步骤完成后,可通过ssh username@your_server_ip从本地机器测试SSH连接。
Paramiko是Python实现的SSH2协议库,支持远程命令执行、文件传输等功能,是Python远程控制的常用工具。
pip install paramiko
ls -l命令并输出结果:import paramiko
def run_remote_command(hostname, port, username, password, command):
# 创建SSH客户端实例
client = paramiko.SSHClient()
# 允许连接未信任的主机(生产环境建议使用密钥认证)
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
# 连接远程服务器
client.connect(hostname=hostname, port=port, username=username, password=password)
# 执行命令
stdin, stdout, stderr = client.exec_command(command)
# 输出命令结果(解码为UTF-8)
print(stdout.read().decode('utf-8'))
except Exception as e:
print(f"连接或执行命令出错: {e}")
finally:
# 关闭连接
client.close()
# 使用示例(替换为实际信息)
if __name__ == "__main__":
run_remote_command(
hostname="your_server_ip",
port=22,
username="your_username",
password="your_password",
command="ls -l /tmp"
)
import paramiko
def transfer_file(hostname, port, username, password, local_path, remote_path, direction="upload"):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname, port, username, password)
sftp = client.open_sftp()
if direction == "upload":
sftp.put(local_path, remote_path) # 上传本地文件到远程
print(f"文件 {local_path} 上传至 {remote_path} 成功")
else:
sftp.get(remote_path, local_path) # 下载远程文件到本地
print(f"文件 {remote_path} 下载至 {local_path} 成功")
sftp.close()
except Exception as e:
print(f"文件传输出错: {e}")
finally:
client.close()
# 使用示例(上传本地文件到远程/tmp目录)
transfer_file(
hostname="your_server_ip",
port=22,
username="your_username",
password="your_password",
local_path="local_file.txt",
remote_path="/tmp/remote_file.txt",
direction="upload"
)
安全性提示:生产环境中建议使用SSH密钥认证(paramiko.RSAKey.from_private_key_file)替代密码,避免密码泄露风险。
Fabric是基于Paramiko的高级库,提供更简洁的API,适合批量执行远程命令、文件传输等任务。
pip install fabric
from fabric import Connection
def deploy_code():
# 创建连接(替换为实际信息)
conn = Connection(
host="your_server_ip",
user="your_username",
connect_kwargs={"password": "your_password"}
)
try:
# 进入目标目录
with conn.cd("/var/www/myapp"):
# 拉取最新代码
conn.run("git pull origin main")
# 安装依赖
conn.run("pip install -r requirements.txt")
# 重启服务
conn.run("systemctl restart myapp")
print("部署完成!")
except Exception as e:
print(f"部署出错: {e}")
finally:
conn.close()
if __name__ == "__main__":
deploy_code()
Fabric的Connection对象封装了SSH连接逻辑,run方法用于执行远程命令,cd方法用于切换目录,代码更易读和维护。
除远程控制外,可通过Python扩展功能,实现更全面的自动化运维:
psutil库获取CPU、内存、磁盘使用率,判断是否超过阈值。import psutil
def check_system_status():
cpu_usage = psutil.cpu_percent(interval=1)
memory_usage = psutil.virtual_memory().percent
disk_usage = psutil.disk_usage("/").percent
print(f"CPU使用率: {cpu_usage}%, 内存使用率: {memory_usage}%, 磁盘使用率: {disk_usage}%")
return cpu_usage > 80 or memory_usage > 80 or disk_usage > 80
if check_system_status():
print("警告:系统资源使用率过高!")
smtplib库在检测到异常时发送邮件通知。import smtplib
from email.mime.text import MIMEText
def send_alert(subject, body, to_email):
from_email = "your_email@example.com"
password = "your_email_password"
smtp_server = "smtp.example.com" # 如QQ邮箱的smtp.qq.com
msg = MIMEText(body)
msg["Subject"] = subject
msg["From"] = from_email
msg["To"] = to_email
try:
with smtplib.SMTP(smtp_server, 587) as server:
server.starttls()
server.login(from_email, password)
server.sendmail(from_email, [to_email], msg.as_string())
print("告警邮件发送成功!")
except Exception as e:
print(f"邮件发送失败: {e}")
# 使用示例
if check_system_status():
send_alert("服务器资源告警", "CPU或内存使用率超过80%", "admin@example.com")
crontab设置定时任务,定期运行Python脚本。crontab -e
添加以下内容(每小时执行一次/path/to/script.py):0 * * * * /usr/bin/python3 /path/to/script.py >> /var/log/python_script.log 2>&1
以上方法覆盖了CentOS环境下Python远程控制的核心需求,可根据实际场景选择合适的工具组合。