python 远程登陆一次执行多条命令

Posted on   风行天下-2080  阅读(418)  评论(0编辑  收藏  举报

1、http://t.zoukankan.com/xiamaojjie-p-13385223.html

执行多条linux命令,多条命令放在一个单引号下面,各命令之间用分号隔开,如:cmd_str = "cd /;cd etc;ls -l;" 且在末尾加上get_pty=True

demo如下:

复制代码
import paramiko


def remot_connect(hostname, port, username, password, cmd_str):
    # 创建SSHClient 实例对象
    ssh = paramiko.SSHClient()
    # 调用方法,表示没有存储远程机器的公钥,允许访问
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    # 连接远程机器,地址,端口,用户名密码
    ssh.connect(hostname, port, username, password, timeout=10)
    # 输出命令执行结果
    stdin, stdout, stderr = ssh.exec_command(cmd_str, get_pty=True)
    result = stdout.read()
    print(result.decode())

    # 关闭连接
    ssh.close()


if __name__ == '__main__':
    hostname = "121.196.120.113"
    port = 22
    username = "root"
    password = "123_Xiaohaikun"
    cmd_str = "cd /;cd etc;ls -l;"
    remot_connect(hostname, port, username, password, cmd_str)
复制代码

代码运行结果如图:

xshell上显示如图:

 

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2019-09-09 python相关cmdb系统

随笔 - 618, 文章 - 0, 评论 - 6, 阅读 - 37万

Copyright © 2025 风行天下-2080
Powered by .NET 9.0 on Kubernetes

点击右上角即可分享
微信分享提示