linux簡單的shell編程「shell調用python腳本」

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()

其他方法:

>import subprocess
child = subprocess.Popen('sleep 60',shell=True,stdout=subprocess.PIPE)
child.poll() #檢查子進程狀態
child.kill()     #終止子進程
child.send_signal()    #向子進程發送信號
child.terminate()   #終止子進程

原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/273791.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
投稿專員的頭像投稿專員
上一篇 2024-12-17 14:08
下一篇 2024-12-17 14:08

相關推薦

發表回復

登錄後才能評論