如果我理解了这个问题,并且根据我的测试,您将需要两个函数或方法。
1. 第一个函数使用 Pexpect 运行本地命令。您也可以使用第一个函数运行 ssh 命令,但前提是 IP 地址存在于 known_hosts 文件中:
pexpect.run("ssh yourUN@192.168.x.x 'whoami'")
否则,您将遇到"The authenticity of host '192.168.x.x (192.168.x.x)' can't be established." 错误。
2.为避免该错误,我建议使用 Paramiko 的 ssh 命令使用第二个函数。
完整代码如下:
注意 - 使用 Python 3.9 在 Linux 5.14.16 上测试。远程机器是 Ubuntu 8.04。
from getpass import getpass
import paramiko
import pexpect
def run_cli_commands(list_of_commands, password=None):
for c in list_of_commands:
print("Command:", c)
command_output, exitstatus = pexpect.run(
c,
events={"(?i)password": password if password is not None else getpass()},
withexitstatus=True)
print("Output:\n", command_output.decode())
def run_ssh_commands(list_of_commands, ip_address, username, password):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip_address, username=username, password=password)
for c in list_of_commands:
print("Command:", c)
stdin, stdout, stderr = ssh.exec_command(c)
print("Output:\n", stdout.read().decode())
run_cli_commands(["which ssh",
"systemctl status ssh",
"systemctl start ssh",
"systemctl status ssh", ], password="**********")
run_ssh_commands(["whoami",
"date", ], "192.168.x.x", "yourUN", "**********")
run_cli_commands(["systemctl stop ssh", ], password="**********")
print("Script complete. Have a nice day.")
输出:
Local command: which ssh
Output:
/usr/bin/ssh
Local command: systemctl status ssh
Output:
○ ssh.service - OpenBSD Secure Shell server
Loaded: loaded (/lib/systemd/system/ssh.service; disabled; vendor preset: disabled)
Active: inactive (dead)
Docs: man:sshd(8)
man:sshd_config(5)
Local command: systemctl start ssh
Output:
Local command: systemctl status ssh
Output:
● ssh.service - OpenBSD Secure Shell server
Loaded: loaded (/lib/systemd/system/ssh.service; disabled; vendor preset: disabled)
Active: active (running) since Thu 2021-12-09 23:13:05 EST; 174ms ago
Docs: man:sshd(8)
man:sshd_config(5)
Process: 4565 ExecStartPre=/usr/sbin/sshd -t (code=exited, status=0/SUCCESS)
Main PID: 4566 (sshd)
Tasks: 1 (limit: 2275)
Memory: 2.3M
CPU: 18ms
CGroup: /system.slice/ssh.service
└─4566 "sshd: /usr/sbin/sshd -D [listener] 0 of 10-100 startups"
SSH command: whoami
Output:
yourUN
SSH command: date
Output:
Thu Dec 9 23:13:04 EST 2021
Local command: systemctl stop ssh
Output:
Script complete. Have a nice day.