广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python脚本实现本地或远程执行命令
  • 869
分享到

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

脚本命令python 2023-01-31 06:01:46 869人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

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

功能:
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.

--结束END--

本文标题: python脚本实现本地或远程执行命令

本文链接: https://www.lsjlt.com/news/189640.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • python脚本实现本地或远程执行命令
    功能:1、执行本地shell命令,执行完成后获取结果2、执行本地shell命令,执行中实时获取输出结果3、执行远程shell命令,执行完成后获取结果4、执行远程shell命令,执行中实时获取输出结果 实际操作:1、安装paramiko ...
    99+
    2023-01-31
    脚本 命令 python
  • 怎么远程执行Linux脚本和命令
    这篇文章主要介绍“怎么远程执行Linux脚本和命令”,在日常操作中,相信很多人在怎么远程执行Linux脚本和命令问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”怎么远程执行Linux脚本和命令”的疑惑有所帮助!...
    99+
    2023-06-03
  • 如何远程执行Linux脚本和命令
    小编给大家分享一下如何远程执行Linux脚本和命令,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!对于 paramiko 安装直接 pip 或者 PyCharm 这...
    99+
    2023-06-16
  • shell中使用expect命令进行远程执行命令脚本
    expect是用来实现自动交互功能的工具之一,使用expect-send来实现交互过程。 注意: 1、脚本的执行方法与bash shell不一样,比如:expect example.sh 2、向一个脚本传递参数时,bas...
    99+
    2022-06-04
    用expect进行远程执行命令 shell中使用expect命令进行远程执行命令脚本
  • ssh远程执行命令方法和Shell脚本实例
    写这篇博客之前,我google了一堆相关文章,大都是说修改/etc/sudoers,然后NOPASSWD:指定的cmd,但是真心不管用,没有远程虚拟终端这个方法就是浮云,ubuntu10.04 server...
    99+
    2022-06-04
    脚本 实例 命令
  • 实现 Python 脚本生成命令行
    目录Fire使用方法方法支持类支持重新改写有时候我们会有这样的一个需求: 我们定义了一个 Python 的方法,方法接收一些参数,但是调用的时候想将这些参数用命令行暴露出来。 比如说...
    99+
    2022-11-11
  • linux怎么在重启或启动时执行命令或脚本
    这篇文章主要为大家展示了“linux怎么在重启或启动时执行命令或脚本”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“linux怎么在重启或启动时执行命令或脚本”这篇文章吧。方法 1:如何使用 /e...
    99+
    2023-06-16
  • CentOS使用expect批量远程执行脚本和命令
    我们有时可能会批量去操作服务器,比如批量在服务器上上传某个文件,安装软件,执行某个命令和脚本,重启服务,重启服务器等,如果人工去一台台操作的话会特别繁琐,并浪费人力。 这时我们可以使用expect,向目标服务器上发送指令...
    99+
    2022-06-04
    CentOS expect 远程执行 脚本 命令
  • 如何在shell中使用expect命令进行远程执行命令脚本
    如何在shell中使用expect命令进行远程执行命令脚本?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。expect是用来实现自动交互功能的工具之一,使用expect-send...
    99+
    2023-06-09
  • shell脚本如何实现同时多台远程主机执行命令
    这篇文章主要介绍shell脚本如何实现同时多台远程主机执行命令,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!实现需求在对单台机器做操作时我们会用“ssh ip”的方式登录到机器上,可以写这样一个工具vssh ip1,...
    99+
    2023-06-09
  • PHP执行Shell脚本或Bash脚本文件并返回命令输出详情
    PHP执行shell脚本或者Bash脚本文件实例。 system和exec函数可能被配置文件禁用,可以通过修改php配置文件删除被禁用的函数。 1.通过system函数执行 使用实例: ...
    99+
    2023-08-31
    bash php 开发语言
  • Python实现脚本转换为命令行程序
    目录搭建骨架脚本使用 Pyscaffold 创建应用程序CLI 工具化测试搭建骨架脚本和模块在我的职业生涯中,我写过、用过和看到过很多随意的脚本。一些人需要半自动化完成任务,于是它们...
    99+
    2022-11-11
  • 有哪些ssh远程执行命令方法和Shell脚本
    本篇内容主要讲解“有哪些ssh远程执行命令方法和Shell脚本”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“有哪些ssh远程执行命令方法和Shell脚本”吧!ssh执行远程操作命令格式代码如下:...
    99+
    2023-06-09
  • Python远程linux执行命令实现
    1、远程登录到linux上,使用到的模块paramiko #远程登陆操作系统 def ssh(sys_ip,username,password,cmds): try #创建ssh客户端 clien...
    99+
    2022-06-04
    Python远程linux执行命令 Python linux远程命令
  • linux中shell脚本实现root切换到普通用户执行脚本或命令的示例分析
    这篇文章将为大家详细讲解有关linux中shell脚本实现root切换到普通用户执行脚本或命令的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。需求:安装deb包,设置程序安装后启动,不需要root...
    99+
    2023-06-09
  • 如何实现Python脚本生成命令行
    这篇文章主要讲解了“如何实现Python脚本生成命令行”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“如何实现Python脚本生成命令行”吧!有时候我们会有这样的一个需求:我们定义了一个 Py...
    99+
    2023-06-30
  • hive-shell批量命令执行脚本的实现方法
    如下所示: #!/usr/bin/bash HADOOP_HOME="/opt/module/cdh-5.3.6-ha/hadoop-2.5.0-cdh5.3.6" HIVE_HOME='/opt/module/cd...
    99+
    2022-06-04
    hive shell 命令
  • 关于命令行执行Python脚本的传参方式
    目录命令行执行Python脚本的传参应用场景方式一方式二python-命令行传参sys.argv实际运用argv获取参数getopt模块实例实际场景运用命令行执行Python脚本的传...
    99+
    2022-11-11
  • redis脚本命令执行问题实例分析
    这篇文章主要介绍“redis脚本命令执行问题实例分析”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“redis脚本命令执行问题实例分析”文章能帮助大家解决问题。1、redis-cli命令行中执行:#&...
    99+
    2023-06-29
  • 用Python实现命令行闹钟脚本实例
    前言: 这篇文章给大家介绍了怎样用python创建一个简单的报警,它可以运行在命令行终端,它需要分钟做为命令行参数,在这个分钟后会打印”wake-up”消息,并响铃报警,你可以用0分钟来测试,它会立即执行,...
    99+
    2022-06-04
    命令行 闹钟 脚本
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作