Python 远程执行 Shell 命令:使用 subprocess 模块
您可以使用 Python 的 subprocess 模块来在本地远程执行 shell 命令。以下是一个示例代码:
import subprocess
# 远程主机IP地址和用户名
remote_host = '192.168.1.1'
remote_user = 'username'
# 要执行的命令
command = 'ls -l'
# 使用ssh连接到远程主机并执行命令
ssh_command = f'ssh {remote_user}@{remote_host} '{command}''
result = subprocess.check_output(ssh_command, shell=True)
# 输出结果
print(result.decode())
在上面的代码中,我们使用了 subprocess.check_output() 函数来执行远程命令,并将结果存储在 result 变量中。接着,我们使用 decode() 方法将结果从字节字符串转换为普通字符串,并打印它。请确保您已经在本地主机上安装了 ssh 命令行工具。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/nYIR 著作权归作者所有。请勿转载和采集!