在自动化运维、批量服务器管理等场景中,使用Python实现Linux远程登陆并执行命令、通过sftp传输文件是常用需求,paramiko是Python中实现SSH2协议的成熟第三方库,能够很好地支持这些功能。

环境准备
首先需要安装paramiko库,通过pip命令即可完成安装:
pip install paramiko
Python实现Linux远程登陆执行命令
核心原理
paramiko的SSHClient类封装了SSH连接的相关逻辑,通过创建该类的实例,设置连接参数后建立连接,再调用exec_command方法即可在远程服务器执行命令,获取命令执行的输出和返回码。
完整实现代码
import paramiko
def remote_execute_command(host, port, username, password, command):
# 创建SSH客户端实例
ssh_client = paramiko.SSHClient()
# 自动添加远程服务器的主机密钥,避免首次连接时的确认提示
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
# 建立SSH连接
ssh_client.connect(
hostname=host,
port=port,
username=username,
password=password,
timeout=10
)
# 执行远程命令
stdin, stdout, stderr = ssh_client.exec_command(command)
# 获取命令执行结果
result = stdout.read().decode("utf-8")
error = stderr.read().decode("utf-8")
return_code = stdout.channel.recv_exit_status()
return {
"result": result,
"error": error,
"return_code": return_code
}
except Exception as e:
return {"error": str(e)}
finally:
# 关闭连接
ssh_client.close()
# 调用示例
if __name__ == "__main__":
host = "192.168.0.1"
port = 22
username = "root"
password = "your_password"
command = "ls -l /home"
res = remote_execute_command(host, port, username, password, command)
print("命令执行结果:", res.get("result"))
print("错误信息:", res.get("error"))
print("返回码:", res.get("return_code"))
Python实现sftp文件传输
核心原理
paramiko的SFTPClient类提供了sftp协议相关的操作方法,通过已建立的SSH连接打开sftp会话,即可调用上传、下载、列出目录等方法完成文件操作。
完整实现代码
import paramiko
def sftp_operation(host, port, username, password, local_path, remote_path, operation="upload"):
# 创建SSH客户端实例
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
# 建立SSH连接
ssh_client.connect(
hostname=host,
port=port,
username=username,
password=password,
timeout=10
)
# 打开sftp会话
sftp_client = ssh_client.open_sftp()
if operation == "upload":
# 上传文件:本地路径到远程路径
sftp_client.put(local_path, remote_path)
return {"status": "上传成功", "local_path": local_path, "remote_path": remote_path}
elif operation == "download":
# 下载文件:远程路径到本地路径
sftp_client.get(remote_path, local_path)
return {"status": "下载成功", "local_path": local_path, "remote_path": remote_path}
else:
return {"error": "不支持的操作类型,仅支持upload和download"}
except Exception as e:
return {"error": str(e)}
finally:
# 关闭sftp和ssh连接
if "sftp_client" in locals():
sftp_client.close()
ssh_client.close()
# 调用示例
if __name__ == "__main__":
host = "192.168.0.1"
port = 22
username = "root"
password = "your_password"
# 上传示例
upload_res = sftp_operation(
host, port, username, password,
local_path="./test.txt",
remote_path="/home/test.txt",
operation="upload"
)
print(upload_res)
# 下载示例
download_res = sftp_operation(
host, port, username, password,
local_path="./downloaded.txt",
remote_path="/home/test.txt",
operation="download"
)
print(download_res)
常见问题与注意事项
- 如果服务器使用密钥认证而非密码认证,可以将
connect方法中的password参数替换为key_filename="私钥文件路径"即可 - 执行命令时如果需要交互式输入,
exec_command方法可以通过stdin.write写入输入内容,写入后需要调用stdin.flush()刷新缓冲区 - 连接服务器时建议设置合理的超时时间,避免网络异常时程序长时间阻塞
- 操作完成后务必关闭连接,避免占用服务器资源