Subprocess使用總結

Subprocess.Popen使用安全性要比python再帶commands強太多,Popen可以對參數進行安全校驗,直接上代碼

# -*- coding: utf-8 -*-

import subprocess
import errno


def ssh_host(ip="", password="test123"):
    args = "ssh root@%s" % ip
    print(args)
    cmd = ["/bin/bash", "-c", args]
    proc = subprocess.Popen(cmd,
                           stdin=subprocess.PIPE,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE,
                           universal_newlines=True)

    # 如果有多個輸入的話,可以使用write的方式,輸入到stdin
    try:
        proc.stdin.write("1\n")
        proc.stdin.write(password + "\n")
    except IOError as e:
        if e.errno != errno.EPIPE and e.errno != errno.EINVAL:
            raise

    # Send data to stdin.  Read data from
    # stdout and stderr, until end-of-file is reached.  Wait for
    # process to terminate
    # 如果只有一個輸入的話,建議直接使用input參數傳入,input中也可以傳入list參數
    out, err = proc.communicate(input=None)
    # out輸出執行的輸出內容,err如果有錯誤的話,則會有值,不等於空字符
    print(out, err)

    proc.stdout.close()
    proc.stdin.close()


if __name__ == "__main__":
    ssh_host()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章