所以我构建了一个程序,使用 tail -f 打印出我的 ubuntu 服务器的登录日志。 该程序使用 Paramiko 通过 ssh 连接并运行命令来跟踪日志。 该程序可以工作,但它从服务器打印出 motd,这是不必要的。
我尝试过使用 itertools 进行拼接。 尝试使用 next()。 还是不行。
这是我的代码:
import yaml, paramiko, getpass, traceback, time, itertools
from paramiko_expect import SSHClientInteraction
with open("config.yaml", "r") as yamlfile:
cfg = yaml.load(yamlfile, Loader=yaml.FullLoader)
def main():
command = "sudo tail -f /var/log/auth.log"
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
server_pw = getpass.getpass("Enter the password for your account %s on %s:" % (cfg['ssh_config']['username'], cfg['ssh_config']['host']))
sudo_pw = getpass.getpass("Enter the sudo password for %s on %s: " % (cfg['ssh_config']['username'], cfg['ssh_config']['host']))
ssh.connect(hostname = cfg['ssh_config']['host'], username = cfg['ssh_config']['username'], port = cfg['ssh_config']['port'], password = server_pw)
interact = SSHClientInteraction(ssh, timeout=10, display=False)
interact.send(command)
interact.send(sudo_pw + "\n")
with open(interact.tail(line_prefix=cfg['ssh_config']['servername']+': ')) as tail:
for line in itertools.islice(tail, 17, None):
print(line)
except KeyboardInterrupt:
print('Ctrl+C interruption detected, stopping tail')
except Exception:
traceback.print_exc()
finally:
try:
ssh.close()
except:
pass
if __name__ == '__main__':
main()
您收到 MOTD 是因为您正在打开交互式 shell 会话。我认为你不需要那个,恰恰相反。
SSHClient.exec_command
代替:
stdin, stdout, stderr = ssh.exec_command(command, get_pty=True)
stdin.write(sudo_pw + "\n")
stdin.flush()
for line in iter(stdout.readline, ""):
print(line, end="")
相关问题:
强制性警告:请勿使用
AutoAddPolicy
– 这样做您将失去针对 MITM 攻击的保护。正确的解决方案请参阅Paramiko“未知服务器”。