SSH 连接到网络设备并运行命令

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

我有一个可以使用用户名和密码连接的网络设备。 登录时,它会显示一个登录横幅(多行),然后显示一个自定义 shell,其中只能运行制造商提供的一组预设命令。

从 python 脚本连接到此设备、运行命令并获取命令输出的最佳方式是什么?

使用Fabric模块:创建一个连接对象,然后调用connection.run似乎只呈现一个交互式shell。下面是示例代码:

from fabric import Connection
from invoke.exceptions import UnexpectedExit
from invoke.watchers import Responder

def run_network_command(host, username, password, command):
    try:
        conn = Connection(host=host, user=username, connect_kwargs={
                "password": password,
            },
        )
        
        # Create responder for the custom shell prompt
        prompt_pattern = r"\[net-7\.2\] \w+>"
        shell_responder = Responder(
            pattern=prompt_pattern,
            response=f"{command}\n"
        )
        
        # Run command in the custom shell
        result = conn.run(
            command,
            pty=True,
            watchers=[shell_responder]
        )
        
        return result.stdout
        
    except UnexpectedExit as e:
        return f"Error executing command: {str(e)}"
    except Exception as e:
        return f"Connection error: {str(e)}"
    finally:
        try:
            conn.close()
        except:
            pass

# Example usage
if __name__ == "__main__":
    # Connection details
    host = "192.168.1.1"
    username = "root"
    password = "pass"
    command = "show version"
    
    # Run command and print output
    output = run_network_command(host, username, password, command)
    print(output)

实现这一目标的最佳方法是什么?

python ssh fabric
1个回答
0
投票

帕里科怎么样?

import paramiko


ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect(hostname='your_host', port=22, username='your_username',     password='your_password')


stdin, stdout, stderr = ssh.exec_command('your_command')
result = stdout.read()
ssh.close()

print(result.decode())
© www.soinside.com 2019 - 2024. All rights reserved.