Loading [MathJax]/jax/output/CommonHTML/config.js
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >python脚本实现本地或远程执行命令

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

作者头像
py3study
发布于 2020-01-08 03:34:58
发布于 2020-01-08 03:34:58
3.8K00
代码可运行
举报
文章被收录于专栏:python3python3
运行总次数:0
代码可运行

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

实际操作: 1、安装paramiko

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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、创建脚本

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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 #更新

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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 删除。

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

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
Python执行或远程执行shell命令
最近想要实现通过脚本循环再Linux下运行shell命令,经过探索发现使用Python语言有几种解决方案,在此简单记录。
宋天伦
2020/10/28
7.6K0
ubuntu1~16.04.9 下安装python3.6 详细教程(在腾讯云服务器上安装实例)
1.输入 sudo add-apt-repository ppa:jonathonf/python-3.6
用户2416682
2019/09/27
2.2K0
ubuntu1~16.04.9 下安装python3.6 详细教程(在腾讯云服务器上安装实例)
Install Rancher 1
因为整合了 k8s 的编排功能, 并且有着非常友好的操作界面,所以在目前的容器技术圈中有着很大的影响力
franket
2021/08/10
7130
为kubernetes(k8s)单独配置kubectl工具
Kubernetes API 是一个 HTTP REST API。这个 API 是真正的 Kubernetes 用户界面,通过它可以完全控制它。这意味着每个 Kubernetes 操作都作为 API 端点公开,并且可以通过对该端点的 HTTP 请求进行。因此,kubectl 的主要目的是向 Kubernetes API 发出 HTTP 请求:
小陈运维
2022/01/06
1.1K0
腾讯云Ubuntu Server 16.04.1 LTS升级系统到Ubuntu 18.04.1 LTS
* 此修改方案为临时方案(/etc/resolv.conf文件系统重启后会自动还原),最终方案待定,下方为腾讯云原装Ubuntu 18.04.1 LTS系统镜像 systemd-resolve --status执行结果,仅供参考。
用户1196360
2018/11/23
8.4K0
腾讯云Ubuntu Server 16.04.1 LTS升级系统到Ubuntu 18.04.1 LTS
WIN10下创建Ubuntu18.04子系统及安装图形界面
控制面板——>程序——>程序和功能——>启用或关闭Windows功能——>适用于Linux的Windows子系统——>确定 (然后重启)
好派笔记
2021/09/17
3.1K0
ansible基础使用
由于在生产中, 出于安全性考虑, 不使用ssh互信进行ansible通信, 可以在配置文件中通过键值对的方式定义变量, 注明用户名与密码
buiu
2021/11/25
4970
Python Paramiko实现sftp文件上传下载以及远程执行命令
Paramiko模块是基于Python实现的SSH远程安全连接,用于SSH远程执行命令、文件传输等功能。
py3study
2020/02/29
10.3K0
zzupdate:单条命令升级 Ubuntu 18.04 LTS
Ubuntu 18.04 版本已经发布,并得到各个社区的一致好评,因为 Ubuntu 18.04 可能是 Ubuntu 多年来最令人兴奋的版本。
用户8639654
2021/10/14
6610
【亲测有效】Ubuntu18.04 sudo apt update无法解析域名的解决方案
拿起了封尘已久的ThinkPad,输入 sudo apt update 的时候,发现这个命令变得不好使了,具体出现的问题如下图所示:
Angel_Kitty
2019/09/09
13.8K1
原来Python是这样连接远程主机的,你会吗?
在软件测试的过程中,涉及到远程Linux主机环境测试的时候,难免会遇到需要执行shell命令的场景,比如通过shell命令去配置一些环境或者去检查用例执行的结果等等,那么就是用到了比较常用的工具paramiko。
软测小生
2021/09/06
2.4K0
docker 操作进阶
sudo docker exec -it merlingpu env LANG=C.UTF-8 /bin/bash
AI拉呱
2021/01/14
5010
python利用paramiko连接远程服务器执行命令的方法
python中的paramiko模块是用来实现ssh连接到远程服务器上的库,在进行连接的时候,可以用来执行命令,也可以用来上传文件。
菲宇
2019/06/11
1.4K0
paramiko模块——ssh远程连接服务器并执行命令
https://www.cnblogs.com/ghylpb/p/12158061.html
GH
2020/03/19
3.3K0
如何搭建 nginx 静态网站
Nginx是一款面向性能设计的HTTP服务器,相较于Apache、lighttpd具有占有内存少,稳定性高等优势。Nginx不采用每客户机一线程的设计模型,而是充分使用异步逻辑从而削减了上下文调度开销,所以并发服务能力更强。整体采用模块化设计,有丰富的模块库和第三方模块库,配置灵活。 在Linux操作系统下,Nginx使用epoll事件模型,得益于此,Nginx在Linux操作系统下效率相当高。同时Nginx在OpenBSD或FreeBSD操作系统上采用类似于epoll的高效事件模型kqueue。
星空之下
2018/10/17
4.8K0
如何搭建 nginx 静态网站
终于来了,Percona发布XtraBackup for MySQL 8.0
Percona在9月12日,终于宣布第一个测试用的XtraBackup for MySQL 8.0版本给大家试用:
数据和云
2018/10/08
9820
终于来了,Percona发布XtraBackup for MySQL 8.0
python3 paramiko 远程执行 ssh 命令、上传文件、下载文件
在win10的系统下,本来想要python3直接调用ansible库进行远程执行的,但是很可惜,ansible是基于linux系统的ssh服务进行远程调用,不太兼容windows。 那么下面来使用paramiko库,直接手写一个ssh远程调用。
Devops海洋的渔夫
2019/06/15
6K0
python paramiko
近段时间用Python写一个小东西,每次修改代码后要手工上传到服务器,觉得很麻烦,虽然有WinSCP,找了一下资料,发现paramiko可以实现自动上传文件的功能,可惜的是,折腾了半天,在Python3.3下没有成功,最后退而求其次安装了2.7才弄好,记录如下:
py3study
2020/01/06
1.6K0
python paramiko模块简介
    paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接。
py3study
2020/01/09
1.2K0
TopDocs:一款美观实用的在线文档编辑系统,支持Markdown语法
说明:最近博主对文档程序小有需求,找了很久发现都是单页,而且还不支持移动端,不是很理想,所以萌JJ大雕就专门花了半天时间,给博主写了一个,该文档程序基于graphql、nuxtjs、mongodb、keystonejs的实时在线文档编辑系统,可用作各种在线文档编辑和展示,支持markdown语法,对移动端特别友好,这里就开源分享出来,给对文档有需求的人。
子润先生
2021/05/28
1.1K0
相关推荐
Python执行或远程执行shell命令
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验