shell调用python脚本 linux简单的shell编程

Python执行shell脚本1。Remote: paramiko2。本地:子流程一. paramiko模块首先安装pip安装密码术==2.4.2,否则报错。#coding:utf-8#python批量执行远程shell脚本import paramikoclass MySQLCon: def __init__(self,name,port,uname,pwd): self.name = name self.port = port s...

Python执行shell脚本
1。Remote: paramiko
2。本地:子流程

一. paramiko模块

首先安装pip安装密码术==2.4.2,否则报错。

#coding:utf-8#python批量执行远程shell脚本import paramikoclass MySQLCon: def __init__(self,name,port,uname,pwd): self.name = name self.port = port self.uname = uname self.pwd = pwd def conn(self): self.ssh = paramiko.SSHClient() #创建SSHClient实例对象 self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #免密登陆 self.ssh.connect(hostname=self.name, port=self.port, username=self.uname, password=self.pwd) def close(self): self.ssh.close() def execom***nd(self,**shell): result = {} for key in shell: stdin, stdout, stderr = self.ssh.exec_com***nd(shell[key]) #获取输入输出及错误 result[key] = stdout.read().decode(encoding="utf-8") return resultif __name__ == "__***in__": mysqlcon = MySQLCon('10.xx.xx.x',22,'root','123456') mysqlcon.conn() com***nd = ''' Name="zhangsan" Age=23 Salary=12000 echo "姓名:$Name; 年龄:$Age; 工资:${Salary-"空"}" ''' #shell命令 res = mysqlcon.execom***nd(shell=com***nd) print(res) mysqlcon.close()

【传输文件:sftp = ssh . open _ sftp()sftp . put(‘源文件’,“要***的地址”)sftp . get()–从Linux***到Windows]

二、子流程模块

1.subprocess.call():执行命令并返回执行状态。当shell参数为False时,命令需要以列表的形式传入。当shell为True时,可以直接传入命令。

>>>> a = subprocess.call(['df','-hT'],shell=False)Filesystem Type Size Used Avail Use% Mounted on /dev/sda2 ext4 94G ***G 26G 72% / tmpfs tmpfs 2.8G 0 2.8G 0% /dev/shm /dev/sda1 ext4 976M 56M 853M 7% /boot >>> a = subprocess.call('df -hT',shell=True)Filesystem Type Size Used Avail Use% Mounted on /dev/sda2 ext4 94G ***G 26G 72% / tmpfs tmpfs 2.8G 0 2.8G 0% /dev/shm /dev/sda1 ext4 976M 56M 853M 7% /boot>>> print a0

2.subprocess.check_call():用法和subprocess.call()类似,只是当返回值不为0时,直接抛出异常。

>>>> a = subprocess.check_call('df -hT',shell=True)Filesystem Type Size Used Avail Use% Mounted on /dev/sda2 ext4 94G ***G 26G 72% / tmpfs tmpfs 2.8G 0 2.8G 0% /dev/shm /dev/sda1 ext4 976M 56M 853M 7% >>> print a0 >>> a = subprocess.check_call('dfdsf',shell=True)/bin/sh: dfdsf: com***nd not foundTraceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib***/python2.6/subprocess.py", line 502, in check_call raise CalledProcessError(retcode, cmd)subprocess.CalledProcessError: Com***nd 'dfdsf' returned non-zero exit status 127

3.subprocess.check_output():用法与上面两种方法类似。不同的是,如果返回值为0,则直接返回输出结果,如果返回值不为0,则直接抛出异常。需要注意的是,这个方法只在python3.x中可用

4.subprocess.popen ():
在一些复杂的场景中,我们需要使用一个流程的执行输出作为另一个流程的输入。在其他场景下,我们需要先进入一个输入环境,然后执行一系列指令。这时候就需要用到suprocess的Popen()方法了。该方法具有以下参数:

args:shell命令,可以是字符串,或者序列类型,如list,tuple。bufsize:缓冲区大小,可不用关心stdin,stdout,stderr:分别表示程序的标准输入,标准输出及标准错误shell:与上面方法中用法相同cwd:用于设置子进程的当前目录env:用于指定子进程的环境变量。如果env=None,则默认从父进程继承环境变量universal_newlines:不同系统的的换行符不同,当该参数设定为true时,则表示使用\n作为换行符

示例1,在/root下创建一个目录suprocesstest:

>>>> a = subprocess.Popen('mkdir subprocesstest',shell=True,cwd='/root')</pre>

2.例如,使用python执行几个命令:

>import subprocessobj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)obj.stdin.write('print 1 \n')obj.stdin.write('print 2 \n')obj.stdin.write('print 3 \n')obj.stdin.write('print 4 \n')obj.stdin.close()cmd_out = obj.stdout.read()obj.stdout.close()cmd_error = obj.stderr.read()obj.stderr.close() print cmd_out print cmd_error</pre>

也可以使用以下方法:

>import subprocessobj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)obj.stdin.write('print 1 \n')obj.stdin.write('print 2 \n')obj.stdin.write('print 3 \n')obj.stdin.write('print 4 \n')out_error_list = obj.communicate() print out_error_list</pre>

3.将一个子流程的输出作为另一个子流程的输入:

>import subprocesschild1 = subprocess.Popen(["cat","/etc/passwd"], stdout=subprocess.PIPE)child2 = subprocess.Popen(["grep","0:0"],stdin=child1.stdout, stdout=subprocess.PIPE)out = child2.communicate()

其他方法:

>import subprocesschild = subprocess.Popen('sleep 60',shell=True,stdout=subprocess.PIPE)child.poll() #检查子进程状态child.kill() #终止子进程child.send_signal() #向子进程发送信号child.terminate() #终止子进程

本文来自霜华投稿,不代表舒华文档立场,如若转载,请注明出处:https://www.chinashuhua.cn/24/570746.html

打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
() 0
上一篇 05-31
下一篇 05-31

相关推荐

  • shell脚本执行命令语句 教你编写一个简单的shell脚本

    在Linux中运行shell脚本有两种方式。您可以使用:bash script.sh或者,您可以像这样执行shell脚本:./script.sh可能很简单,但没有太多解释。别担心,我会用例子做必要的解释,这样你就能理解为什么在运行shell脚本时会使用给定的特定语法格式。我会用这行shell脚本让需要解释的

    2023-07-05 06:25:01
    1001 0
  • shell数组赋值的用法 如何使用shell数组

    什么是shell数组:通常,在使用shell脚本的过程中,我们会保留一系列数值以供参考。这种以特定名称保存一系列值的方式就是数组。当然,shell中只支持一维数组。在一个shell数组中,有多个值,每个值都可以称为数组的element,每个元素都会有一个对应的下标,用来定义对应的元素

    2023-06-26 12:46:01
    902 0
  • shell调用python脚本 linux简单的shell编程

    Python执行shell脚本1。Remote: paramiko2。本地:子流程一. paramiko模块首先安装pip安装密码术==2.4.2,否则报错。#coding:utf-8#python批量执行远程shell脚本import paramikoclass MySQLCon: def __init__(self,name,port,uname,pwd): self.name = name self.port = port s

    2023-05-31 06:56:01
    627 0
  • shell脚本实例 运维shell脚本经典实例

    因为这些天我很忙,所以今天我继续发这个实例。这是我们经常使用的数据库的备份,但是我这次给的是备份数据库目录数据,和直接备份某个数据库还是有区别的。后续将发送一个特殊实例。今天我们来看看这个案例:#!/bin/env/bash#定义参数存储时间DAY=`date +%Y%m%d '#检查相应的

    2023-03-29 03:10:02
    300 0

评论列表

联系我们

在线咨询: QQ交谈

邮件:admin@qq.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信