举个栗子:python中使用paramiko远程调用

2017-11-16 0 1,500 百度已收录

在实际工作当中经常会碰到linux远程调用这样的场景,针对这样的场景,可以使用很多编程语言实现,本文采用python来实现此功能

工具/原料

方法/步骤

  1. 1

    ##1.导入paramiko模块

    #!/usr/bin/env python

    # -*- coding:utf-8 -*-                 #此头部指定后,才能兼容中文

    from __future__ import print_function  # 兼容python 3.0的print语法

    __author__ = 'zxh'

    import sys

    reload(sys)

    sys.setdefaultencoding('utf-8')

    print(sys.getdefaultencoding())

    import os

    import commands

    import paramiko

    举个栗子:python中使用paramiko远程调用

  2. 2

    ##2.创建 ssh 连接函数

    def connect(host):

        'this is use the paramiko connect the host,return conn'

        ssh = paramiko.SSHClient()

        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        try:

            ssh.connect(host, username='hadoop', password='123456', allow_agent=True)

            return ssh

        except:

            return None

    举个栗子:python中使用paramiko远程调用

  3. 3

    ##3.编写执行函数

    def exec_commands(conn, cmd):

        ##'this is use the conn to excute the cmd and return the results of excute the command'

        print (cmd)

        stdin, stdout, stderr = conn.exec_command(cmd)

        results = stdout.read()

        print(stdout.read())

        print(stderr.read())

        return results

    举个栗子:python中使用paramiko远程调用

  4. 4

    ##4.具体使用例子

    if __name__ == '__main__':

        # 远程执行命令

        data_date=sys.argv[1]

        exec_commands(connect('192.168.1.131'), "sh /opt/test/123.sh "+data_date)

        ##以下为多线程的例子,分别同时在多台机器上执行相同命令

        cmd = ['ifconfig', 'echo hello !']  # 你要执行的命令列表

        username = "root"

        passwd = "123456"

        threads = []  # 多线程

        print

        "Begin ……"

        for i in range(1,3):

            ip = '192.168.10' + str(i)

            a = threads.Thread(target=ssh2, args=(ip, username, passwd, cmd))

            a.start()

    举个栗子:python中使用paramiko远程调用

  5. 5

    ##5.调用效果图

    举个栗子:python中使用paramiko远程调用END

注意事项

  • 此经验乃实际操作,如有帮助请点赞或投票,谢谢~
  • 同样也欢迎小伙伴们的关注,这个是给小编最大的鼓励~
收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

栗子博客 网站 举个栗子:python中使用paramiko远程调用 https://www.lizi.tw/web/1501.html

建筑工地上施工员,闲暇时弄个博客打发时间,

常见问题
  • 1、杰齐1.7仅适用于PHP5.2 2、需Zend支持 3、尽量使用宝塔面板 4、尽量使用Windows 系统,关关对Linux支持不太友好。
查看详情

相关文章

评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务

举个栗子:python中使用paramiko远程调用-海报

分享本文封面