CentOS环境下使用Python实现远程控制的核心方法
在CentOS服务器上,需先开启SSH服务以支持远程连接。若未安装SSH服务器,可通过以下命令安装并启动:
sudo yum install openssh-server -y # 安装OpenSSH服务器
sudo systemctl start sshd # 启动SSH服务
sudo systemctl enable sshd # 设置开机自启
若需允许远程访问,需配置防火墙放行SSH(默认端口22):
sudo firewall-cmd --permanent --add-service=ssh # 永久添加SSH服务到防火墙规则
sudo firewall-cmd --reload # 重新加载防火墙配置
Paramiko是Python实现的SSH2协议库,支持远程命令执行、文件上传/下载等功能,是Python远程控制CentOS的核心工具。
在本地Python环境中安装Paramiko:
pip install paramiko
通过Paramiko建立SSH连接,执行远程命令并获取输出:
import paramiko
def execute_remote_command(hostname, username, password, command):
# 创建SSH客户端对象
ssh = paramiko.SSHClient()
# 自动添加服务器主机密钥(首次连接时无需手动确认)
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
# 连接服务器(替换为实际IP、用户名、密码)
ssh.connect(hostname=hostname, username=username, password=password, port=22)
# 执行命令(如查看系统负载)
stdin, stdout, stderr = ssh.exec_command(command)
# 获取命令输出(解码为UTF-8字符串)
output = stdout.read().decode('utf-8')
error = stderr.read().decode('utf-8')
if output:
print(f"命令输出:\n{output}")
if error:
print(f"命令错误:\n{error}")
except Exception as e:
print(f"连接或执行命令失败: {e}")
finally:
# 关闭SSH连接
ssh.close()
# 示例:执行"ls -l"命令
execute_remote_command(
hostname="192.168.1.100", # CentOS服务器IP
username="root", # 远程登录用户名
password="your_password", # 远程登录密码
command="ls -l /tmp" # 要执行的远程命令
)
通过Paramiko的SFTP功能实现文件传输:
import paramiko
def transfer_file(hostname, username, password, local_path, remote_path, direction='upload'):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(hostname=hostname, username=username, password=password, port=22)
# 打开SFTP会话
sftp = ssh.open_sftp()
if direction == 'upload':
# 上传本地文件到远程服务器
sftp.put(local_path, remote_path)
print(f"文件 {local_path} 上传至 {remote_path} 成功")
elif direction == 'download':
# 下载远程文件到本地
sftp.get(remote_path, local_path)
print(f"文件 {remote_path} 下载至 {local_path} 成功")
sftp.close()
except Exception as e:
print(f"文件传输失败: {e}")
finally:
ssh.close()
# 示例:上传本地文件到远程/tmp目录
transfer_file(
hostname="192.168.1.100",
username="root",
password="your_password",
local_path="/local/path/to/file.txt", # 本地文件路径
remote_path="/tmp/file.txt", # 远程文件路径
direction='upload'
)
# 示例:下载远程/tmp/file.txt到本地
transfer_file(
hostname="192.168.1.100",
username="root",
password="your_password",
local_path="/local/path/to/save/file.txt", # 本地保存路径
remote_path="/tmp/file.txt", # 远程文件路径
direction='download'
)
Fabric是基于Paramiko的高级库,专注于远程命令执行和文件传输,语法更简洁,适合批量管理服务器。
pip install fabric
from fabric import Connection
def fabric_remote_operations(hostname, username, password):
# 创建连接对象(替换为实际信息)
conn = Connection(
host=hostname,
user=username,
connect_kwargs={"password": password}
)
try:
# 执行远程命令(如查看磁盘使用率)
result = conn.run("df -h", hide=False)
print(f"磁盘使用率:\n{result.stdout}")
# 上传文件到远程服务器
conn.put("/local/path/to/file.conf", "/etc/file.conf")
print("文件上传成功")
# 下载远程文件到本地
conn.get("/etc/file.conf", "/local/path/to/save/file.conf")
print("文件下载成功")
finally:
# 关闭连接
conn.close()
# 示例:执行Fabric操作
fabric_remote_operations(
hostname="192.168.1.100",
username="root",
password="your_password"
)
~/.ssh/authorized_keys文件中,连接时指定私钥路径:ssh.connect(hostname=hostname, username=username, key_filename="/path/to/private_key")
sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.0/24" service name="ssh" accept'
sudo firewall-cmd --reload
paramiko.AuthenticationException),并记录操作日志以便排查问题。top、free -m等命令获取服务器CPU、内存使用情况,或通过psutil库获取更详细的系统指标。以上方法覆盖了CentOS环境下Python远程控制的核心需求,可根据具体场景选择合适的工具(Paramiko适合底层SSH操作,Fabric适合简化流程的批量任务)。