多语言展示
当前在线:1359今日阅读:103今日分享:49

python中使用paramiko远程调用

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

Python;paramiko

方法/步骤
1

##1.导入paramiko模块#!/usr/bin/env python# -*- coding:utf-8 -*-                 #此头部指定后,才能兼容中文from __future__ import print_function  # 兼容python 3.0的print语法__author__ = 'zxh'import sysreload(sys)sys.setdefaultencoding('utf-8')print(sys.getdefaultencoding())import osimport commandsimport paramiko

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

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

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()

5

##5.调用效果图

注意事项
1

此经验乃实际操作,如有帮助请点赞或投票,谢谢~

2

同样也欢迎小伙伴们的关注,这个是给小编最大的鼓励~

推荐信息