Python免秘钥ssh远程登录执行命令and本地执行shell命令

python远程执行

python paramiko 模块的应用

环境
# yum install python-dev
# yum install python-devel
# pip install pycrypto
# pip install paramiko
# pip install ssh
方法体
import paramiko
def DiskCheck(ip):
    try:
        # 建立一个sshclient对象
        ssh = paramiko.SSHClient()
        # 允许将信任的主机自动加入到host_allow 列表,此方法必须放在connect方法的前面
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        # 指定本地的RSA私钥文件,如果建立密钥对时设置的有密码,password为设定的密码,如无不用指定password参数
        # pkey = paramiko.RSAKey.from_private_key_file('/home/super/.ssh/id_rsa', password='12345')
        pkey = paramiko.RSAKey.from_private_key_file('/home/ptop/topicjie/scripts/keys/id_rsa')
        # 建立连接
        ssh.connect(hostname=ip,
                    port=22,
                    username='ptop',
                    pkey=pkey)
        # 执行命令
        stdin, stdout, stderr = ssh.exec_command("for i in $(df -h|grep data|awk '{print $6}'); do  touch $i/test.txt; done; df -h|grep data")
        # 结果放到stdout中,如果有错误将放到stderr中
        print(stdout.read().decode())
        print(stderr.read())
        # 关闭连接
        ssh.close()

提示:最好采用ssh免秘钥登录的模式,尽量不要出现明文密码

本机执行shell脚本

python中有很多调用本地shell脚本的方法 类似commands 等,不过现在官方推荐的是使用subprocess 进行本地shell脚本的调用,这个模块的方法较多。

import shlex
import subprocess

def execute_command(cmdstring, cwd=None, timeout=None, shell=False):
    if shell:
        cmdstring_list = cmdstring
    else:
         cmdstring_list = shlex.split(cmdstring)
    if timeout:
        end_time = datetime.datetime.now() + datetime.timedelta(seconds=timeout)
        #没有指定标准输出和错误输出的管道,因此会打印到屏幕上;
    sub = subprocess.Popen(cmdstring_list, cwd=cwd, stdin=subprocess.PIPE,shell=shell,bufsize=4096)
    #subprocess.poll()方法:检查子进程是否结束了,如果结束了,设定并返回码,放在subprocess.returncode变量中 
    while sub.poll() is None:
        time.sleep(0.1)
        if timeout:
            if end_time <= datetime.datetime.now():
                raise Exception("Timeout:%s"%cmdstring)

    return str(sub.returncode)
#方法测试
p=execute_command("hive -f "+path)
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值