windows 通过 python 远程执行linux命令
要在 Windows 上通过 Python 远程执行 Linux 命令,需要使用 SSH 客户端。以下是一些基本的步骤:
- 安装 Python 的 paramiko 模块,它是一个 SSH 客户端库,可以在 Windows 上连接到远程 Linux 服务器。
pip install paramiko
- 创建一个 SSHClient 对象,并使用 connect() 方法连接到远程服务器。
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('remote-server-ip', username='username', password='password')
- 使用 exec_command() 方法在远程服务器上执行命令,并使用 stdout、stderr 和 stdin 属性获取命令的输出和错误信息。
stdin, stdout, stderr = ssh.exec_command('ls -l')
print(stdout.read())
完整示例:
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('remote-server-ip', username='username', password='password')
stdin, stdout, stderr = ssh.exec_command('ls -l')
print(stdout.read())
ssh.close()
注意:在使用 SSHClient 连接远程服务器时,应该使用 SSH 密钥而不是密码进行身份验证,这样更加安全
原文地址: https://www.cveoy.top/t/topic/fckg 著作权归作者所有。请勿转载和采集!