码迷,mamicode.com
首页 > 编程语言 > 详细

python 实现远程主机执行命令函数

时间:2015-03-13 18:59:19      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:python

#!/usr/bin/python

# coding=utf-8

import os

import paramiko


\\定义 h_name 远程主机名 h_cmd 执行的命令

def remote_cmd(h_name,h_cmd):


        sshadd = h_name


        sshusr = ‘root‘


        sshpwd = ‘YourPasswd



        sshport = 22


        sen1 = ‘export JAVA_HOME= YourJdkPath ;‘


        sen2 = ‘命令1;‘


        sen3 = ‘命令2;‘


        num = ‘2‘ //命令数量


        paramiko.util.log_to_file(‘ssh.txt‘)


        ssh = paramiko.SSHClient()


        known_host="/root/.ssh/known_hosts"


        ssh.load_system_host_keys(known_host)


        privatekeyfile = os.path.expanduser(‘/root/.ssh/id_rsa‘)


        mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile,password=‘密钥密码‘)


        ssh.connect(hostname = sshadd, username = sshusr, password = sshpwd, port = sshport)


        stdin, stdout, stderr = ssh.exec_command(‘n=‘ + num + ‘;‘ + sen1 + sen2 + sen3 )


        return stdout.read().strip(‘\n‘)


python 实现远程主机执行命令函数

标签:python

原文地址:http://bobo123.blog.51cto.com/3133979/1620175

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!