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