通过 Python 脚本拒绝所有用户基于密码的 SSH 登录

Deny password-based SSH login for all users through a Python script

我正在编写一个 Python 脚本来拒绝远程服务器 (Ubuntu 18.04) 的基于密码的 SSH 登录。我将 运行 我的主机系统 (Windows) 中的 Python 脚本。因此,我已经使用 paramiko 模块和初始化 SSH 客户端建立了与远程主机的 SSH 连接。

为了拒绝基于密码的 SSH 登录,我应该编辑 /etc/ssh/sshd_config 文件并将行 'PasswordAuthentication yes' 更改为 'PasswordAuthentication no' 请注意,我的远程系统允许无密码 sudo。我只需要在 sshd_config 文件中做这个替换。

下面给出的是我尝试过的命令:

ssh_client.exec_command("sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/g' /etc/ssh/sshd_config")

我遇到了错误:couldn't open temporary file .sedVg2nV6: Permission Denied

有人遇到过这个吗? 除了 sed 之外,还有其他方法可以替换配置文件的一部分吗? sed 仅适用于 .txt 个文件吗?

我觉得你应该改变
ssh_client.exec_command("sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/g' /etc/ssh/sshd_config")

ssh_client.exec_command("sudo sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/g' /etc/ssh/sshd_config")(sed命令将以root权限执行)