喜气youngyoung 2025-03-19 21:15 采纳率: 33.3%
浏览 16

用python的subprocess模块和ssh命令实现自动化交互的远程登录主机的功能

只能使用subprocess模块和ssh命令。
不能用paramiko,pexpect,expect,sshpass,免密登录等方法。

  • 写回答

4条回答 默认 最新

  • 道友老李 JWE233286一种基于机器视觉的水表指针读数识别及修正的方法 专利发明者 2025-03-19 21:15
    关注
    让【道友老李】来帮你解答,本回答参考gpt编写,并整理提供,如果还有疑问可以点击头像关注私信或评论。
    如果答案让您满意,请采纳、关注,非常感谢!
    如果要使用subprocess模块和ssh命令来执行远程命令,可以通过以下步骤来实现:
    1. 使用subprocess模块调用ssh命令连接到远程主机,并执行需要的命令。
    2. 在调用ssh命令时,可以使用ssh的“-t”选项来分配一个伪终端,从而避免一些输入输出的问题。 以下是一个简单的例子来演示如何使用subprocess和ssh命令来执行远程命令:
    import subprocess
    # 远程主机信息
    remote_host = 'remote_host'
    remote_user = 'remote_user'
    remote_password = 'remote_password'
    # 需要执行的远程命令
    remote_command = 'ls -l'
    # 构建ssh命令
    ssh_command = 'sshpass -p {} ssh -t {}@{} "{}"'.format(remote_password, remote_user, remote_host, remote_command)
    # 执行ssh命令并获取输出
    process = subprocess.Popen(ssh_command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    output, error = process.communicate()
    # 输出结果
    if process.returncode == 0:
        print("执行成功,输出为:")
        print(output.decode())
    else:
        print("执行失败,错误信息为:")
        print(error.decode())
    

    在这个例子中,我们使用subprocess.Popen来执行ssh命令,并通过communicate()方法获取命令的输出结果。需要注意的是,这里使用了sshpass命令来将密码传递给ssh命令,如果不使用免密登录方法,则需要输入密码来进行连接。 希望以上内容能解答你的问题。

    评论

报告相同问题?

问题事件

  • 创建了问题 3月19日