大蟒蛇python教程共享shell调用python脚本(linux简单的shell编程)


python执行shell脚本
1.远程:paramiko
2.本地:subprocess

一、paramiko模块

首先要安装pip install cryptography==2.4.2,不然会报错

#coding:utf-8 #python批量执行远程shell脚本  import paramiko  class 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 execommand(self,**shell):         result = {}         for key in shell:             stdin, stdout, stderr = self.ssh.exec_command(shell[key])   #获取输入输出及错误             result[key] = stdout.read().decode(encoding="utf-8")             return result    if __name__ == "__main__":     mysqlcon = mysqlcon('10.xx.xx.x',22,'root','123456')     mysqlcon.conn()      command = '''         name="zhangsan"         age=23         salary=12000         echo "姓名:$name; 年龄:$age; 工资:${salary-"空"}"         '''   #shell命令     res = mysqlcon.execommand(shell=command)     print(res)      mysqlcon.close()

【传文件:sftp = ssh.open_sftp() sftp.put(‘源文件’,“要拷贝的地址”) sftp.get()–从linux往windows拷贝】

二、subprocess模块

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   64g   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   64g   26g  72% / tmpfs        tmpfs 2.8g     0  2.8g   0% /dev/shm /dev/sda1     ext4    976m   56m  853m   7% /boot  >>> print a 0

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   64g   26g  72% / tmpfs        tmpfs 2.8g     0  2.8g   0% /dev/shm /dev/sda1     ext4    976m   56m  853m   7%  >>> print a 0  >>> a = subprocess.check_call('dfdsf',shell=true) /bin/sh: dfdsf: command not found traceback (most recent call last):   file "<stdin>", line 1, in <module> file "/usr/lib64/python2.6/subprocess.py", line 502, in check_call raise calledprocesserror(retcode, cmd) subprocess.calledprocesserror: command '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 subprocess  obj = 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 subprocess  obj = 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 subprocess child1 = subprocess.popen(["cat","/etc/passwd"], stdout=subprocess.pipe) child2 = subprocess.popen(["grep","0:0"],stdin=child1.stdout, stdout=subprocess.pipe) out = child2.communicate()

其他方法:

需要了解更多python教程分享shell调用python脚本(linux简单的shell编程),都可以关注python教程分享栏目—计算机技术网(www.ctvol.com)!

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

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/pythontutorial/1053617.html

(0)
上一篇 2022年2月23日
下一篇 2022年2月23日

精彩推荐