Python;paramiko
##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.创建 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.编写执行函数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.具体使用例子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.调用效果图
此经验乃实际操作,如有帮助请点赞或投票,谢谢~
同样也欢迎小伙伴们的关注,这个是给小编最大的鼓励~