前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python脚本实现本地或远程执行命令

python脚本实现本地或远程执行命令

作者头像
py3study
发布2020-01-08 11:34:58
3.5K0
发布2020-01-08 11:34:58
举报
文章被收录于专栏:python3python3

功能: 1、执行本地shell命令,执行完成后获取结果 2、执行本地shell命令,执行中实时获取输出结果 3、执行远程shell命令,执行完成后获取结果 4、执行远程shell命令,执行中实时获取输出结果

实际操作: 1、安装paramiko

apt-get install  python3-pip libevent-dev libffi-dev libssl-dev -y
pip3 install paramiko -i https://pypi.mirrors.ustc.edu.cn/simple/  --trusted-host https://pypi.mirrors.ustc.edu.cn

2、创建脚本

root@om:~# mkdir /scripts/python -p
root@om:~# touch /scripts/python/shell.py
root@om:~# cat /scripts/python/shell.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import subprocess
import paramiko
import re
import sys
class Cmd(object):
    def onetime_shell(self,cmd):
        cmd = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE)
        cmd = cmd.communicate()
        cmd = cmd[0].decode().rstrip()
        return cmd
    def realtime_shell(self,cmd):
        cmd = subprocess.call(cmd, shell=True)
        return cmd
class Remote_cmd(object):
    def __init__(self,PrivateKey,IP,Port,User):
        self.private_key = paramiko.RSAKey.from_private_key_file(PrivateKey)
        self.ssh = paramiko.SSHClient()
        self.set_missing_host_key_policy = self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.connect = self.ssh.connect(hostname=IP, port=Port, username=User,pkey=self.private_key)
    def onetime_shell(self,cmd,notice=False):
        stdin, stdout, stderr = self.ssh.exec_command(cmd)
        result = stdout.read().decode('utf-8').rstrip()
        if notice:
           self.ssh.close()
        return result

    def realtime_shell(self,cmd,notice=False):
        try:
           stdin, stdout, stderr = self.ssh.exec_command(cmd)
           for line in stdout:
               print(line.strip("\n"))
           for error in stderr:
               print(error.strip("\n"))
           if notice:
              self.ssh.close()
        except Exception as e:
           print("execute command %s error, error message is %s" % (cmd, e))
           return ""

例子: 1、本地执行shell命令,执行完成后获取结果: mkdir /tmp/shell #创建目录/tmp/shell echo shell >> /tmp/shell/shell.log # 输出shell 写入/tmp/shell/shell.log 2、本地执行shell命令,实时获取输出结果 apt-get update #更新 3、远程执行shell命令,执行完成后获取结果 mkdir /tmp/remote_shell #创建目录/tmp/remote_shell echo remote_shell >> /tmp/remote_shell/remote_shell.log #输出remote_shell写入/tmp/remote_shell/remote_shell.log 4、远程执行shell命令,实时获取输出结果 apt-get update #更新

root@om:~# cat exec_shell.py 
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
sys.path.append('/scripts/python/')
from shell import Cmd,Remote_cmd
class ExecShell (object):
   def __init__(self):
       self.cmd = Cmd()
       self.remote_nfs_server = Remote_cmd('/root/.ssh/id_rsa','nfs-server','22','root')
   def local_onetime_shell(self):
       print("执行本地shell命令,执行完成后获取结果")
       self.cmd.onetime_shell('mkdir /tmp/shell')
       self.cmd.onetime_shell('echo shell >> /tmp/shell/shell.log')
       re = self.cmd.onetime_shell('cat  /tmp/shell/shell.log')
       print(re)
   def local_realtime_shell(self):
       print("执行本地shell命令,执行中实时获取输出结果")
       self.cmd.realtime_shell('apt-get update')
   def remote_onetime_shell(self):
       print("执行远程shell命令,执行完成后获取结果")
       self.remote_nfs_server.onetime_shell('mkdir /tmp/remote_shell')
       self.remote_nfs_server.onetime_shell('echo remote_shell >> /tmp/remote_shell/remote_shell.log')
       re = self.remote_nfs_server.onetime_shell('cat /tmp/remote_shell/remote_shell.log')
       print(re)
   def remote_realtime_shell(self):
       print("执行远程shell命令,执行中实时获取输出结果")
       self.cmd.realtime_shell('apt-get update')
execshell = ExecShell()
execshell.local_onetime_shell()
execshell.local_realtime_shell()
execshell.remote_onetime_shell()
execshell.remote_realtime_shell()

# 执行脚本结果
root@om:~# ./exec_shell.py 
执行本地shell命令,执行完成后获取结果
shell
执行本地shell命令,执行中实时获取输出结果
Hit:1 http://mirrors.aliyun.com/docker-ce/linux/ubuntu xenial InRelease
Get:2 http://repo.percona.com/apt jessie InRelease [15.9 kB]                                                                                                                            
Hit:3 http://us.archive.ubuntu.com/ubuntu xenial InRelease                                                                                                   
Get:4 http://security.ubuntu.com/ubuntu xenial-security InRelease [107 kB]                                
Hit:5 http://us.archive.ubuntu.com/ubuntu xenial-updates InRelease                                                   
Ign:2 http://repo.percona.com/apt jessie InRelease                                  
Hit:6 http://us.archive.ubuntu.com/ubuntu xenial-backports InRelease                
Fetched 123 kB in 1s (68.6 kB/s)                             
Reading package lists... Done
W: GPG error: http://repo.percona.com/apt jessie InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 9334A25F8507EFA5
W: The repository 'http://repo.percona.com/apt jessie InRelease' is not signed.
N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use.
N: See apt-secure(8) manpage for repository creation and user configuration details.
执行远程shell命令,执行完成后获取结果
remote_shell
执行远程shell命令,执行中实时获取输出结果
Hit:1 http://mirrors.aliyun.com/docker-ce/linux/ubuntu xenial InRelease
Get:2 http://repo.percona.com/apt jessie InRelease [15.9 kB]                                                                                                                            
Hit:3 http://us.archive.ubuntu.com/ubuntu xenial InRelease                                                                                                   
Get:4 http://security.ubuntu.com/ubuntu xenial-security InRelease [107 kB]                                
Hit:5 http://us.archive.ubuntu.com/ubuntu xenial-updates InRelease                                                   
Ign:2 http://repo.percona.com/apt jessie InRelease                                  
Hit:6 http://us.archive.ubuntu.com/ubuntu xenial-backports InRelease                
Fetched 123 kB in 1s (63.9 kB/s)                             
Reading package lists... Done
W: GPG error: http://repo.percona.com/apt jessie InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 9334A25F8507EFA5
W: The repository 'http://repo.percona.com/apt jessie InRelease' is not signed.
N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use.
N: See apt-secure(8) manpage for repository creation and user configuration details.
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档