在通过 SSH 从 Python 程序连接的 Linux VM 上运行脚本的任何方法

问题描述 投票:0回答:1

我通过下面的代码连接到Linux机器

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname, port, username=username, password=password)

我想在该服务器上运行下面的 script.sh 文件,并在 python 程序中接收 $max_session 变量的输出。

#!/bin/bash
cd /

config_file="/etc/ssh/sshd_config"
if [ ! -f "$config_file" ]; then
  echo "File $config_file does not exist."
  exit 1
fi

max_sessions=$(sudo grep -i "^MaxSessions" "$config_file" | awk '{print $2}')

if [ -z "$max_sessions" ]; then
  echo "MaxSessions is not set in the configuration file."
else
  echo "$max_sessions"
fi

此脚本文件与 python 程序位于同一文件夹中。

python-3.x linux shell ssh paramiko
1个回答
0
投票

请注意,使用 Paramiko SFTP 客户端可能会更容易 直接从服务器读取 /etc/ssh/sshd_config 并执行“grep” 在Python代码中。
--@AKX

并参考这篇post来实施

© www.soinside.com 2019 - 2024. All rights reserved.